1

My Ultra sonic sensor (HC-SR04) is returning these types of values when it has nothing in front:

Ping: 144cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 105cm
Ping: 105cm
Ping: 94cm
Ping: 0cm
Ping: 378cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 106cm
Ping: 106cm
Ping: 0cm
Ping: 0cm
Ping: 0cm
Ping: 106cm
Ping: 250cm
Ping: 0cm
Ping: 108cm
Ping: 0cm
Ping: 108cm
Ping: 0cm

I am not able to understand why I am getting 0 cm. This value is critical in the program that I am using. Here is a test code which gives me these output:

#include <NewPing.h>

#define TRIGGER_PIN  A5
#define ECHO_PIN     A4
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN);

void setup() {
  Serial.begin(115200);
}

void loop() {
  delay(1000);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

Because of these 0s my robot is making turns which are not expected.

Any idea why this might happen ?

1 Answer 1

3

The documentation for the NewPing library states:

Constructor

NewPing sonar(trigger_pin, echo_pin [, max_cm_distance]);

and

max_cm_distance is optional [default = 500cm].

Then:

sonar.ping_cm(); - Send a ping, returns the distance in centimeters or 0 (zero) if no ping echo within set distance limit

So it would seem that if there is nothing in front of your sensor closer than 500cm, this library returns 0cm. Probably not the best design, but at least it is disclosed.

Thus, you need to write your code such that a 0cm measurement is treated as no obstruction visible; more like an infinite cm measurement.

1
  • 1
    The library defines NO_ECHO as 0 so you check sonar.ping_cm() == NO_ECHO for clarity.
    – Craig
    Commented Aug 1, 2018 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.