Need help with loops

I am trying to implement the below pseudo-code for an arduino tank connected to a Sharp distance sensor which attached to the front of the tank:
“If (distance<30), then rotate counterclockwise until distance>30”

What loop should I use?
I had problems getting my loop to stop(the tank did not stop rotating even when the distance was (I think less than 30)):

(the below code is in the void loop() function)

if (distance<30){
while(distance<30){
digitalwrite(left,HIGH);
}
}

Could delay be used to allow the tank to rotate for a specific amount of time?

Thankyou

“If (distance<30), then rotate counterclockwise until distance>30”

distance = getDistance();
if (distance<30)
    {
    // Turn left
    digitalWrite(left,HIGH);
    digitalWrite(right, LOW);

    while (getDistance() <= 30)
       {}  // Still turning

    // Stop turning
    digitalWrite(left,LOW);
    }

Note that you can’t just use the variable ‘distance’ repeatedly and expect it to magically change value. You have to re-check the distance sensor each time to detect changes.

Could delay be used to allow the tank to rotate for a specific amount of time?

If you know how fast the tank rotates, yes.

I had problems getting my loop to stop(the tank did not stop rotating even when the distance was (I think less than 30)):

With this code:

if (distance<30)
{
  while(distance<30)
  {
    digitalwrite(left,HIGH);
  }
}

It never will stop rotating. The variable distance never gets a new value in the while loop, so if the while loop starts, distance will ALWAYS be less than 30.

You need to do something to make distance change in the while loop, if you ever want it to end. Like, I don’t know, maybe take a distance reading.

PaulS: It never will stop rotating. The variable distance never gets a new value in the while loop, so if the while loop starts, distance will ALWAYS be less than 30.

Another reason is that once the 'left' output pin is set HIGH it will stay HIGH until explicitly set LOW (which is not shown in the code).

Plus you hardly need the “if” and the “while”. Why not:

  while (distance < 30)
  {
    digitalwrite(left,HIGH);
  }

But as others have said, as you can see, nothing is going to change distance. You really want something like:

  while (getDistance () < 30)
  {
    digitalwrite(left,HIGH);
  }

 digitalwrite(left,LOW);  // stop turning left

Where getDistance is a function that returns the current distance.