NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.7

harrygover:
Hi there,

Apologies if this has been answered already, im a beginner so just trying some small experiments out. When the sensor distance exceeds its maximum it defaults to 0cm. Is there anyway this can be changed to the max distance value?

Thanks

This is a common question/confusion but if you think about it, it makes total sense that it works the way it does.

Imagine you set the max distance to 100cm. Now the way the library works, any non-zero value means there's something in front of the sensor. Let's say the object was 100cm away, it would return a value of 100.

If instead, it would return the max distance when there wasn't an object at all in the way, how would you know there wasn't an object at all? Or if there was an object 100cm away? So there would be no difference between an object detected at 100cm and no object at all. That's not good logic, and it makes it impossible to know what the condition is.

Keep in mind that a result of 0 doesn't mean the object is further away than the max distance. It means there isn't an object AT ALL, which is why a value of 0 makes total sense.

If, however, for your use, you want this ambiguous logic, that's totally possible. Simply read the sensor distance, then if 0 make it any value you want. For example:

if (dist == 0) {
 dist = 100;
}

Or whatever you want it to be. Writing the library in this way, you can both detect when an object doesn't exist or just set the max distance (if that makes sense to your project).

Basically, this is where your programming needs to take over and deal with the results as your program needs.

Tim