HCSRO4 ultrasonic sensor returning 0 distance in between each normal value on the serial monitor

I'm trying to make an ultrasonic senor which sets of a buzzer whenever the measured distance is below a certain value (40cm), however the buzzer is going off constantly when I run the program because on the serial monitor the distance reads zero in between each actual value that's accurately read. Code below.

long duration;
int distance;

const int trigPin = 10;
const int echopin = 11;
const int buzzer = 5;

void setup(){
  pinMode(trigPin, OUTPUT);
  pinMode(echopin, INPUT);
  pinMode(buzzer, OUTPUT);
  Serial.begin(115200);
}

void loop(){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echopin, HIGH);

  distance = duration * 0.034 / 2;

  Serial.print("Distance: ");
  Serial.println(distance);

  if (distance < 40)
  {
    tone(buzzer, 440);
  }

  else
  {
    digitalWrite(buzzer, LOW);
  }

}

if (distance < 40 && distance != 0)

Thanks, That works at first but then after it goes off once it keeps going off constantly, any other ideas?

Well, what does pulseln() return if no echo is heard?

I'm not sure, I'm new to all this stuff sorry I just followed a tutorial for most of that code

Then time to begin to read the documentation.

wdym by documentation

Google knows! Ask Google for information on "arduino pulseln".

ok so it looks like every second echo isnt being returned in time and is giving the zero, i played around with time out times and for some reason every second echo isnt coming back, any idea why this would happen?

How long do you wait between sending out pulses? Must wait for all echos to die out.

just tried increasing the delay between pulses, still didnt do anything.

void loop(){
  delay(100);
  digitalWrite(trigPin, LOW);

nice, that made it work, thanks! i thought i had to change the delays that were already in place and just make them longer, didn't realise i actually had to put a new one in

  • Remember delay( . . . ) is blocking, i.e. stops normal program flow for this amount of time.

  • You can use the millis( ) function to make non-blocking TIMERs.
    See the Blink Without Delay example in the IDE.

And assume all tutorials have problems!