Ultrasonic sensor reading 0 in loop

I'm building an ultrasonic sensor for my rain water tanks. I decided to use an average of 10 readings instead of a single reading, since there's some noise. But I'm having a strange problem when I read the sensor in a loop, which is that every other reading is 0. Not sure if it's because I'm reading too quickly, or if I'm doing something obviously wrong. Before I added the loop I was reading it every 2 seconds.

My code (mostly from randomnerdtutorials):

  for (i=0; i<numSamples; i++) {
    // Clears the trigger pin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    // Read echoPin, return the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);
    Serial.print(duration); Serial.print(" ");
    totalDuration += duration;
  }
  duration = totalDuration/i;   // average of numSamples

And typical output:
11363 0 11385 0 11362 0 11361 0 11359 0

That happens to me as well. I just drop any distance of 1 or less as bogus data. Not sure why it happens,

1 Like

What is the time between pings? Maybe too short? Your numbers look like about 195cm (77 inches), is that about right? What is the maximum distance to tank bottom?

A zero is always returned when the pulseln() times out waiting for the HIGH! Basically that means no echo was returned in the timeout limit you set. When you do not set the time limit in microseconds, the time out occurs in 1 second. So basically there was no echo of the ultrasonic pulse. I suggest you ignore zeros because you are getting some valid echos.

Serial.print(duration * 0.0172); Serial.print(" ");

Should be close to centimeters.

Is numSamples "2" or "10"? Maybe put a "delay(200);" at the end of each for-loop?

Some time ago I had exactly the same problem when using HC-SR04 sensors, they are mostly bugged and get stuck with "0 cm" (or sometimes "3 cm") readings until powered off and on again, or using a trick I discovered to "recover" that lock situation (by temporarily putting Echo pin as OUTPUT, bringing it LOW then after a vew milliseconds change it back as INPUT) .

So if you're currently using SR04 take this probable issue in consideration. And give HY-SRF05 sensors a try: their cost is a bit higher (a few cents) but I've never had problems with those!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.