2wd Robot Car Problem

Hey, i m trying to make a simple robot car project: An automatic car that stops when an obstacle is near 10 cm and reverse the direction , i wrote the code and it didn't work as i wanted: the car stops when an obstacle is near and reverse the direction when it's gone !! , also the car rotate on its place ! Please help me thank you :confused: :confused:

////////CAPTEUR ULTRASON PORT
int trig = 2;
int echo = 3;
long lecture_echo;
long cm;
//////////////// BRIDGE L289
int IN4 = 13;
int IN3 = 12;
int IN2=9;
int IN1=8;

int enA=6;
int enB =5;
//Pour inverser la direction du moteur
int aux;
int y,x;
void setup(){
//Capteur ultrason
pinMode(trig, OUTPUT);
digitalWrite(trig, LOW);
pinMode(echo, INPUT);
//Bridge
pinMode(IN4, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN1,OUTPUT);
Serial.begin(9600);
x=1;
y=0;
}

void loop(){
 //Vitesse 
analogWrite(enA,255);
analogWrite(enB,255);
// Signal capteurs envoie et reception
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
lecture_echo = pulseIn(echo,HIGH);
cm = lecture_echo /58;
Serial.print("Distance en cm :");
Serial.println(cm);
//test si la distance est inférieur a 10cm ( je voudrai inverser le sens)
if (cm<10){
  //inverse du sens
aux=y;
y=x;
x=aux;
//stop du moteur pendant 5s
digitalWrite(IN1, 0); // rotation sens 2
 digitalWrite(IN2, 0);
  digitalWrite(IN3, 0); // rotation sens 2
  digitalWrite(IN4, 0);
delay(500);

}
//Roulement dans le sens inverse
digitalWrite(IN1, x); // rotation sens 2
 digitalWrite(IN2, y);
  digitalWrite(IN3, y); // rotation sens 2
  digitalWrite(IN4, x); 
}
/*************************FIN DU PROGRAMMES**************************/

The program does what you wrote. As a first aid reformat the code (IDE CTRL+T) for better overview.

IMO you should get rid of delay() and use a state machine. The states should reflect both the presence of the object, as well as the current move of the robot. Try to start with states Normal, ObstacleAhead, Turning, Reversing...

DrDiettrich:
The program does what you wrote. As a first aid reformat the code (IDE CTRL+T) for better overview.

IMO you should get rid of delay() and use a state machine. The states should reflect both the presence of the object, as well as the current move of the robot. Try to start with states Normal, ObstacleAhead, Turning, Reversing...

i didn't get it?

Forget the distance for now and just write some simple code to make the car go forward for 1 second, reverse for 1 second, turn left then turn right. When that is working look carefully at the state of IN1, IN2, IN3 and IN4 in each case. That should show you why your original code makes the thing rotate in place.

Steve