Help with Obstacle Avoiding Robot

Hey!
I made am obstacle avoiding robot (circuit diagram:)
And now I don’t know how to code it as per my needs (I’m new to arduino uno, rather, coding in general)
Some help would be really appreciated.

Link to my code:

I want it to:

  1. Go straight
  2. When an obstacle is there, go left and check again.
  3. If an obstacle is there even after the left turn, take an extreme right or if not then go straight.
    4)After taking the right turn, check again if its not there then go straight
  4. or take a u-turn.

I tried to do so but the bot keeps on taking a right turn and goes straight.

In the circuit,
I changed the motor pins from 2,3,4,5 to
6,3,10,5

3 - left motor forward
6 - left motor backward
10 - right motor forward
5 - right motor backward

for the sensor,
trigger - 12
echo - 11

I want the distance of the obstacle and the bot to be 15 cm.

try_3.ino (1.21 KB)

Hi, here is a working example of obstacle avoidance with the ultrasonic sensor:

http://arduino-info.wikispaces.com/RobotKitMenu-8

Please post your code.
In code tags

const int trig = 12;
const int echo = 11;
const int leftBackward = 6;
const int leftForward = 3;
const int rightForward = 10;
const int rightBackward = 5;

int duration = 0;
int distance = 0;

void setup() 
{
  pinMode(trig , OUTPUT);
  pinMode(echo , INPUT);
  pinMode(leftForward , OUTPUT);
  pinMode(leftBackward , OUTPUT);
  pinMode(rightForward , OUTPUT);
  pinMode(rightBackward , OUTPUT);
  
  Serial.begin(9600);

}

void loop()
{
  digitalWrite(trig , HIGH);
  delayMicroseconds(1000);
  digitalWrite(trig , LOW);


  duration = pulseIn(echo , HIGH);
  distance = (duration/2) / 28.5 ;
  Serial.println(distance);
  

  if ( distance > 20 )
  {
    digitalWrite(leftForward , HIGH);
    digitalWrite(leftBackward , LOW);
    digitalWrite(rightForward , HIGH);
    digitalWrite(rightBackward , LOW);
  }
  else if ( distance < 20)
   {
    analogWrite(leftBackward , 100);
    analogWrite(rightForward , 100);
   }
    if ( distance < 20)
    {
      analogWrite(leftBackward , 100);
      analogWrite(rightForward , 100);
    }
    
    else 
    {
      digitalWrite(leftForward , HIGH);
      digitalWrite(leftBackward , LOW);
      digitalWrite(rightForward , HIGH);
      digitalWrite(rightBackward , LOW);
     }
    
   }