HC-SR04 sensor return 0 value

Issue #326 resolved
Tom Ming created an issue

@John Maloney

I use HC-SR04 sensor to read distance, sometimes it returns 0 value, but Arduino sketch dose not return 0 value.

How to solve it,Thanks.

Comments (7)

  1. John Maloney repo owner

    I have noticed the same thing. It is probably a timing issue. Could you send the Arduino code you are using or a link to it? I will investigate.

  2. Tom Ming reporter

    @John Maloney

    Hi John,

    The Arduino code is below.

    #include <Servo.h>
    
    Servo servo_14;
    
    float checkdistance_13_15() {
      digitalWrite(13, LOW);
      delayMicroseconds(2);
      digitalWrite(13, HIGH);
      delayMicroseconds(10);
      digitalWrite(13, LOW);
      float distance = pulseIn(15, HIGH) / 58.00;
      delay(10);
      return distance;
    }
    
    void setup(){
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      pinMode(15, INPUT);
      servo_14.attach(14);
    }
    
    void loop(){
      Serial.println(checkdistance_13_15());
      if (checkdistance_13_15() < 20) {
        servo_14.write(90);
        delay(3000);
    
      } else {
        servo_14.write(150);
        delay(0);
    
      }
    
    }
    

  3. John Maloney repo owner

    Thanks for the Arduino code. The checkDistance() function ends with a 10 msec delay. That may be to prevent any lingering echos of the last "ping" from being received early in the next distance reading cycle or perhaps the hardware needs that time to prepare for the next cycle.

    As a test, you could try adding a delay to the MicroBlocks script that samples the distance:

    scriptImage41672200.png

    If that eliminates the spurious zero readings then I can add the delay to the MicroBlocks library code.

  4. John Maloney repo owner

    In my testing, adding a 10 msec wait to the end of the distance function eliminated the false zero readings. I will make that change in the next Pilot release.

  5. Log in to comment