Wall Avoiding Robot Help


I am fairly new to Arduino programming, but I read a couple books on the subject. I decided to build a wall avoiding robot as a first more complex project.
The robot is done and it works pretty well. I am planning to improve it in the future, adding more features. I am using 2 dc motors to drive the robot, and a Sharp IR sensor to measure distance. Right now the robot can go straight forward, if it senses something within 30 centimeters in front of it it turn 90 degrees to the right. And here is the problem. The turning is determined by a time delay of 500 ms. However, during this time period the robot turns different angles on different surfaces. On my carpet it turns 90 degrees, but on a wood floor it does a 180. What I am trying to do is to eliminate this problem. Here are the parts of the code that are relevant.

void loop() {
  sensorDistance = analogRead(sensorPin);
  if (sensorDistance <= closeDistance) {
void turnRight() {
  digitalWrite(redLedPin, HIGH);
  digitalWrite(greenLedPin, LOW);
  digitalWrite(pin12EN, HIGH); //right wheel backward
  digitalWrite(pin1A, LOW); 
  digitalWrite(pin2A, HIGH);
  digitalWrite(pin34EN, HIGH); //left wheel forward
  digitalWrite(pin4A, HIGH);
  digitalWrite(pin3A, LOW);

What I was trying to do is to put an if function into the turnRight function and make the robot turn to the right until the sensor reading reaches a specific value, and then return, and go forward. It did not work at all.

Any ideas on how to achieve this 90 degree turn?


I think, you need a feedback from the wheels, in order to know if wheels are rotating and how fast/long. Optical encoders would help to provide such feedback. SFE has some.