How to interlock Push buttons to control a dc motor

How i can control a dc motor using 3 interlocked push buttons.
if we press the forward button then must be first push the stop button then reverse button.
if forward button is pressed then reverse button must be disabled or vice versa.

const int stopPin = 2; // Stop pushbutton pin
const int cwPin = 3; // Forward pushbutton pin
const int ccwPin = 4; // Reverse pushbutton pin
const int ledPin = 5; // Power LED pin
const int motorPin = 9; // Motor Output pin
const int motorPin2 = 10; // Motor Output pin

boolean stopState = 0; // variable for reading the stop button status
boolean cwState = 0; // variable for reading the CW Button status
boolean ccwState = 0; // variable for reading the CCW Button status

void setup() {
// initialize the pin as an Output:
pinMode(motorPin, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(ledPin, OUTPUT);

// initialize the pushbutton pin as an input:
pinMode(stopPin, INPUT_PULLUP);
pinMode(cwPin, INPUT_PULLUP);
pinMode(ccwPin, INPUT_PULLUP);
digitalWrite(motorPin, LOW);
digitalWrite(motorPin2, LOW);



  • this function turns motor foward
    void cwMotor() {
    Serial.println(F("Function Motor is running CW"));
    digitalWrite(motorPin, LOW);
    digitalWrite(motorPin2, HIGH);
    digitalWrite(ledPin, HIGH);



  • this function turns motor backwards
    void ccwMotor() {
    Serial.println(F("Motor is running CCW"));
    digitalWrite(motorPin, HIGH);
    digitalWrite(motorPin2, LOW);
    digitalWrite(ledPin, HIGH);
    delay (3000); //Delay for CCW auto stop
    digitalWrite(motorPin, LOW); //Delay for CCW auto stop
    digitalWrite(motorPin2, LOW); //Delay for CCW auto stop
    digitalWrite(ledPin, LOW); //Delay for CCW auto stop


  • Stop the motor form moving
    void stopMotor() {
    Serial.println(F("Motor is stoped"));
    digitalWrite(motorPin, LOW);
    digitalWrite(motorPin2, LOW);
    digitalWrite(ledPin, LOW);

void loop() {
// read the state of the stop button value:
stopState = digitalRead(stopPin);
cwState = digitalRead(cwPin);
ccwState = digitalRead(ccwPin);

if (cwState == LOW) {

if (ccwState == LOW){

else if (stopState == LOW) {


You just need a variable that keeps track of the state of the system - something like this pseudo code

fwdButtonState = readFwdButtonPin
revButtonState = readRevButtonPin
stopButtonState = readStopButtonPin

if (stopButtonState == LOW) { // assumes low when pressed)
  make motor stop
  motorState = 'S';

if (motorState == 'S') {
  if (fwdButtonState == LOW) {
     make motor go fwd
     motorState = 'F'
  else if (revButtonState == LOW) {
     make motor go in rev
     motorState = 'R'  


PS ... When posting code please use the code button </>

so your code 
looks like this

and is easy to copy to a text editor See How to use the Forum

Also please use the AutoFormat tool to indent your code for easier reading.

Robin2 Thanks a lot, Yes i will follow your advise for next post.
Thanks a lot and best Regards