# Why is one part of my code being executed over the part before it?

The following code doesn't behave the way I would like it to. Inside the loop function im measuring the distance in front of the robot and if it is less than 15cm than the robot should move back and if it is less than 15cm on the left then move forward. When i run the program however only the left side is being checked and acted upon whilst the the if statement about the front and moving back is not doing anything. Something to note also is that when i swap the if statements and put the front checking ahead of the left checking it works but the left side is no longer being checked. Why is it that the if statement block in front is being executed over the previous one?

``````     void loop(){

if(front.calculateDistance() < 15){
MoveBack(200);
}else{
stopMoving();
}

if(left.calculateDistance() < 15){
MoveForward(200);
}else{
stopMoving();
}
}
``````

This is what the move methods do (move back and stopmoving just change input directions):

``````void MoveForward(int rspeed) {
// turn on motor A
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
analogWrite(enA, rspeed);
// turn on motor B
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
analogWrite(enB, rspeed);
}
``````

The problem is with your logic. You are saying:

1. If it's too close in front then move backwards
2. Otherwise stop all movement
3. If it's too close on the left then move forwards
4. Otherwise stop all movement.

That means that if it's too close in front, but not too close on the left, then it will think about moving backwards, but then immediately stop because it's not too close on the left.

You need to think more about the whole space at once, not just one individual direction. For instance, what do you do if it's too close in front and too close on the left? At the moment you'll crash into whatever is in front.

So you should be thinking about four conditions:

1. Too close in front AND too close on the left
2. Too close in front BUT NOT too close on the left
3. NOT too close in front BUT too close on the left
4. NOT too close in front AND NOT too close on the left.

Then you can choose the right action to perform.

If your specific setup means that it can never be too close in front at the same time as being too close on the left you can collapse it into a simpler form:

1. IF it's too close in front then move backwards
2. ELSE IF it's too close on the left then move forwards
3. ELSE stop all movement.