WHILE-Loop is not broken by violated condition

Calling on the experts out there:

I am trying to build an "autonomous car" that uses ultrasonic distance measurement to avoid obstacles.

In order to avoid collisions, the car is only supposed to be moving while the distance in front of it is larger than 10 (centimeters).

However, although the measured distances seem accurate, the WHILE-loop won't break when the distance becomes shorter than 10.

I use the following code to measure the distance:

//Ultrasonic distance measurement Sub function
int Distance_test() {
  digitalWrite(Trig, LOW);   
  digitalWrite(Trig, HIGH);  
  digitalWrite(Trig, LOW);   
  float Fdistance = pulseIn(Echo, HIGH);  
  Fdistance= Fdistance / 58;       
  return (int)Fdistance;

And this is my WHILE-loop:

   int distance_front = Distance_test();
  Serial.print("Distance front (initial): ");

 while(distance_front > 10){
    forward()      //moves the car forward
    int distance_front = Distance_test();  
    Serial.print("Distance front (loop): ");

    stop()         //stops the car

Inspecting the outputs to the serial monitor shows that the code indeed enters the WHILE-Loop only when distance_front is lager than 10. After that, it keeps measruing distance_front and updating t every second, as intended. So far, so good.

However, once distance_front drops below 10, as indicated by the updated valuest on the serial monitor, the programme will not exit the loop and the car just keeps going forward.

After carefully inspecting my code and the measrued distances, I have no idea how a value below 10 will not violate the WHILE-condition. Have I overlooked something essential?

I would greatly appreciate your help on this!



 int distance_front = Distance_test();

This is a brand new variable it is not the same variable as used in the

 while(distance_front > 10){



 distance_front = Distance_test();



Of course, that did it!

Thanks a lot!

Follow the design pattern of putting all your declaration at the beginning of a module. It’s safer.

That delay(1000) could cause a crash. Your holding down the gas and closing your eyes for a full second every time through the loop.

-jim lee

In addition to the comment in Reply #4 you should not be using WHILE for this task. Just use IF and allow loop() to do the repetition.


The one second delay was only chosen for debugging purposes, in practice it would obviously need to be much shorter.

But thanks for the IF-Loop suggestion, that should indeed be better!