What is a better algorithm for wall following with an ultrasonic sensor? This wall following algorithm uses the ultrasonic sensor.  It has a horrible worst case behavior.  Place the robot about 3 cm too far from the wall.  Instead of moving closer to the wall, the robot turns toward the wall and spins.

Place the robot too close to the wall and it works very well.

The sensor points out from the right side of the robot, in front of the powered wheels.





How should the algorithm be changed to handle the "too far away" case?
If a significant distance from the wall, you'll need to turn 90 degrees in place clockwise, drive up to the wall and turn 90 degrees in place counterclockwise.
I'd suggest mounting a touch sensor in front of the vehicle handle the part of driving up to the wall, if that is not possible, estimate from the scanned distance how far the vehicle should drive.

If close to the wall but not close enough to have the wall-following algorithm work correctly, I'd suggest "wiggling":
Repeat the following steps until close enough to the wall:


rotate left wheel forward by a small angle while blocking the right
wheel. 
rotate right wheel forward by a small angle while blocking the
left wheel. 
rotate left wheel backward by a small angle while
blocking the right wheel. 
rotate right wheel backward by a small
angle while blocking the left wheel.


In each step use the same angle (determine an optimal angle by trial and error)