Arduino Uno - HC-SR04 Distance Sensor Code Question


the block of code bellow is from an “Obstacle Avoidance Line Follower Robot” project, that I found on web. I created this project for personal use and I have the following problem. At first we define an integer value named distance which is the distance in cm that “sonar.ping_cm()” function returns. After that, it checks if distance is equal to 0 and its true then it sets the distance to 30. In the end it checks if distance is less or equal to 15 and if its true then it calls a function.
So what I really want is, when HC-SR04 sensor finds a distance that is lower or equal than 15 then the function moveForward should be called. I can’t understand why lines 4, 5, 6 must be used in order to work. If I delete them, then my robot will keep calling the function moveForward() even if the distance is not less or equal to 15.


  1. void loop() {
  2. delay(70);
  3. int distance = sonar.ping_cm();
  4. if (distance == 0) {
  5. distance = 30;
  6. }
  7. if(distance<=15) {
  8. moveForward();
  9. }


Thanks for your time, appreciate your help!

What’s wrong with

if(distance<=15 && distance != 0) {

It depends on the library you use, but in most I have seen, The sonar returns zero when it cannot read the distance. it does not mean the distance is zero, just that it’s undefined (too far or too close)

Good thought ! Thank you !