Factoring out the common code in your state machine makes the code more readable and easier to modify:
// Note: analogWrite(p, 0) == digitalWrite(p, LOW) and analogWrite(p, 255) == digitalWrite(p, HIGH)
void ControlMotors(byte L1, byte L2, byte R1, byte R2) {
analogWrite(ControlMotorLeft1, L1);
analogWrite(ControlMotorLeft2, L2);
analogWrite(ControlMotorRight1, R1);
analogWrite(ControlMotorRight2, R2);
}
void IRInputCheck() {
if (irrecv.decode(&results)) {
switch (results.value) {
case BUTTON_front:
currentState = MovingForward;
ControlMotors(150, 0, 150, 0);
break;
case BUTTON_back:
currentState = Backward;
break;
case BUTTON_right:
currentState = Turnright;
break;
case BUTTON_left:
currentState = Turnleft;
break;
case BUTTON_speedup:
if (currentState == MovingForward) {
analogWrite(ControlMotorLeft1, 250);
analogWrite(ControlMotorRight1, 250);
}
break;
case BUTTON_speeddown:
if (currentState == MovingForward) {
digitalWrite(ControlMotorLeft1, 100);
analogWrite(ControlMotorRight1, 100);
}
break;
} // End: switch
irrecv.resume();
} // End: if decode
}
void loop() {
if (currentState == Idle)
digitalWrite(TheLED, LOW);
else {
digitalWrite(TheLED, HIGH);
IRInputCheck(); // Only allow IR control if not Idle
}
// Pushbuttons override Idle, manual and automatic behaviors
if (!digitalRead(PushButtonOFF))
currentState = Idle;
if (!digitalRead(PushButtonAUTO))
currentState = AM_MovingForward;
switch (currentState) {
case Idle:
Serial.println("Idle");
ControlMotors(0, 0, 0, 0);
if (!digitalRead(PushButtonON))
currentState = rest;
break;
case rest:
Serial.println("Rest");
ControlMotors(0, 0, 0, 0);
break;
case MovingForward:
Serial.println("Moving Forward");
ControlMotors(150, 0, 150, 0);
if (digitalRead(IRS) == HIGH)
currentState = Backward ;
break;
case Backward:
Serial.println("Backward");
ControlMotors(0, 255, 0, 255);
if (digitalRead(IRS) == HIGH)
currentState = MovingForward ;
break;
case Turnleft:
Serial.println("Turn left");
ControlMotors(0, 255, 255, 0);
break;
case Turnright:
Serial.println("Rest");
ControlMotors(255, 0, 0, 255);
break;
case AM_MovingForward:
Serial.println("Auto Mode");
ControlMotors(255, 0, 255, 0);
digitalWrite(ControlMotorLeft1, HIGH);
if (digitalRead(IRS) == HIGH)
currentState = AM_Backward ;
// if (sonar.ping_cm() <= 8)
// currentState = AM_Backward ;
break;
case AM_Backward:
Serial.println("Backward");
ControlMotors(0, 255, 0, 255);
delay(1000);
currentState = Turn;
break;
case Turn:
Serial.println("Turn");
ControlMotors(255, 0, 0, 255);
delay(1000);
currentState = AM_MovingForward;
break;
}
}