using serial monitor to control dc motor but only reading "1" as input

I am using an arduino uno set-up to run 2 dc motor through an l293d ic

int enA = 9;
int in1 = 8;
int in2 = 7;
int enB = 3;
int in3 = 5;
int in4 = 4;
int val;

void setup() {
 (Serial.begin(9600));
 // Set all the motor control pins to outputs
 pinMode(enA, OUTPUT);
 pinMode(enB, OUTPUT);
 pinMode(in1, OUTPUT);
 pinMode(in2, OUTPUT);
 pinMode(in3, OUTPUT);
 pinMode(in4, OUTPUT);
}

void loop() {
 if (Serial.available()){
   val = Serial.read();}
   {
 if (val = 0) {
   digitalWrite(in1, LOW);
   digitalWrite(in2, LOW);
   digitalWrite(in3, LOW);
   digitalWrite(in4, LOW);
   delay(10);
   analogWrite(enA, 0);
   analogWrite(enB, 0);
   delay(100);
   Serial.println("Speed is = 0");}

else if (val = 1){
     digitalWrite(in1, HIGH);
     digitalWrite(in2, LOW);
     digitalWrite(in3, HIGH);
     digitalWrite(in4, LOW);
     delay (200);
     analogWrite(enA, 190);
     analogWrite(enB, 190);
     Serial.println("Speed is = 1");}

else if (val = 2){
     digitalWrite(in1, HIGH);
     digitalWrite(in2, LOW);
     digitalWrite(in3, HIGH);
     digitalWrite(in4, LOW);
     delay (200);
     analogWrite(enA, 255);
     analogWrite(enB, 255);
     Serial.println("Speed is = 2");}
}
}

The L293d is an H-bridge with the following specs:
I am having problems in the serial monitor portion. No matter which number I type into serial monitor, it will only run speed 1 as seen below. The dc motors run but do not stop running.
Questions:

  1. How can I input different numbers in serial monitor to stop the motors or run them at different speeds?
  2. How would I stop this loop after a number is input in serial monitor?

Serial Monitor readout.png

l293d_h_bridge.png

Serial Monitor readout.png

l293d_h_bridge.png

In your if statements, = is assignment, == is comparison. You want to do comparisons in the if statements. See the if statement reference.

val = Serial.read();

To conver to a numeric value try

val = Serial.read() - '0'; // Thats a zero

or

if (val == '0')

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.