I’m trying to control 2 motors with the motor shield by typing in values into the Serial Monitor. After I attempt to load the code, I get a message saying ‘Direction’ was not declared in this scope. How can I make this code work?
//ARDUINO CAR with 2 Motors
#include <AFMotor.h>
AF_DCMotor motor2(2, MOTOR12_1KHZ);
AF_DCMotor motor3(3, MOTOR12_1KHZ);
void setup()
{
Serial.begin(9600);
Serial.println(“Motor time”);
motor2.setSpeed(125);
motor3.setSpeed(125);
}
void loop()
{
if (Serial.available()) {
//read serial as ascii integer
int ser = Serial.read();
//Print the value in the serial monitor
Serial.println(ser);
if(ser >= 48 && ser <= 57){
//The ascii equivilent of numbers 0 - 9 are 48 - 57
// so subtracting 46 from the ascii gives us 2 - 12
int Direction = ser - 46;
}}
if (Direction == 8 )
{Serial.print(“Foward”);
motor2.run(FORWARD);
motor3.run(FORWARD);
delay(500);}
if (Direction == 6)
{Serial.print(“Right”);
motor3.run(BACKWARD);
motor2.run(FORWARD);
delay(500);}
if (Direction == 4)
{Serial.print(“Left”);
motor2.run(BACKWARD);
motor3.run(FORWARD);
delay(500);}
if (Direction == 2)
{Serial.print(“Backward”);
motor2.run(BACKWARD);
motor3.run(BACKWARD);
delay(500);}
}