Ultrasonic Sensor Reading 0cm Randomly

I am trying to program a simple obstacle avoidance robot with a stationary ultrasonic sensor(will add more) and two motors. I am using the NewPing.h library for ease of use, but the ultrasonic sensor is giving back a 0cm value randomly, with my simple code, it calls the wrong command. Is there a resource that I can use as a reference for doing something this simple? Most robots use a servo attached to the ultrasonic sensor, which I can not do for many reasons. If you want to look at the mess that is my code, I have attached it. Should I use the “no library” approach so then I can do a constrain() or am I doing something wrong?

Test_1.ino (1.8 KB)

If the “0” reading is only occasional, just ignore it. It is not a valid distance in any case.

If statements similar to this one can be used to make that decision.

  if(sonar.ping_cm () < 100){ //if object within --cm

Provide more details and forum members can provide better informed help.

By the way, what is this doing in setup()? It is not a valid construction and your program won’t compile.

sonar.ping_cm () = constrain(sonar.ping_cm (), 10, 200);

More members will see your code if posted properly. Read the how to use this forum-please read sticky to see how to properly post code. Remove useless white space and format the code with the IDE autoformat tool (crtl-t or Tools, Auto Format) before posting code.

Use something like this to ignore 0 readings.

 if (distance <= 100 && distance > 0) //if object within --cm

I have used greater than and less than statements to ignore the random 0 values. Still learning the definition of conditional and what is allowed in IF statements, but I am well underway.