这些随机值可能只是噪音,因为您的接收器可能正在感应其他超声波源。
这是一个示例,我在其中获取多个读数(poop_measurements
测量值),然后对其取平均值:
long getDuration() {
digitalWrite(TRIGGER, LOW);
delayMicroseconds(10);
digitalWrite(TRIGGER, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER, LOW);
return pulseIn(ECHO, HIGH);
}
void loop() {
float duration = 0, distance = 0;
int poop_measurements = 10;
for (int i = 0; i < poop_measurements; i++) {
duration += getDuration();
}
duration = duration/poop_measurements;
distance = (duration / 2) / 29.1;
if (distance < 30 ){
digitalWrite(RELAY, HIGH);
} else{
digitalWrite(RELAY, LOW);
}
Serial.print("CM: ");
Serial.println(distance);
}