[SOLVED]4 DC Motors not working with Switch...Case statement

I am working on 4 DC motors and wish to run them simultaneously (as in a car) on the basis of serial message received. My hardware is an Uno and an L293D motor shield. Only 1 motor works (the one on port M1) and I don’t know why the other three don’t run. Anyone is welcome to assist me in the code.


#include <AFMotor.h>

AF_DCMotor M1(1);
AF_DCMotor M2(2);
AF_DCMotor M3(3);
AF_DCMotor M4(4);
int SR;

void setup() {
  // put your setup code here, to run once:
  M1.setSpeed(225);
  M1.setSpeed(225);
  M1.setSpeed(225);
  M1.setSpeed(225);

  Serial.begin(9600);
  Serial.println("Forward = 1");
  Serial.println("Backward = 2");
  Serial.println("Left = 3");
  Serial.println("Right = 4");
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0) {
    SR = Serial.parseInt();

    switch(SR) {
       
    case(1):
    M1.run(FORWARD);
    M2.run(FORWARD);
    M3.run(FORWARD);
    M4.run(FORWARD);
    delay(2000);
    M1.run(RELEASE);
    M2.run(RELEASE);
    M3.run(RELEASE);
    M4.run(RELEASE);
    break;

    case(2):
    M1.run(BACKWARD);
    M2.run(BACKWARD);
    M3.run(BACKWARD);
    M4.run(BACKWARD);
    delay(2000);
    M1.run(RELEASE);
    M2.run(RELEASE);
    M3.run(RELEASE);
    M4.run(RELEASE);
    break;

    case(3):
    M1.run(BACKWARD);
    M2.run(FORWARD);
    M3.run(BACKWARD);
    M4.run(FORWARD);
    delay(2000);
    M1.run(RELEASE);
    M2.run(RELEASE);
    M3.run(RELEASE);
    M4.run(RELEASE);
    break;

    case(4):
    M1.run(FORWARD);
    M2.run(BACKWARD);
    M3.run(FORWARD);
    M4.run(BACKWARD);
    delay(2000);
    M1.run(RELEASE);
    M2.run(RELEASE);
    M3.run(RELEASE);
    M4.run(RELEASE);
    break;
  }
 } 
}

It looks like you used copy and paste in setup:

  M1.setSpeed(225);

That line appears four times. I'll guess that you intended to set the speed for the other three motors.

Thanks @wildbill for assisting me :slight_smile: