# Motor Control Problems

I’m trying to make the Arduino+Motor Shield to control a motor both with speed and direction. The plan is to talk to the Arduino via “serial” and when you enter A, it would set to one direction and B would be the other, then you would set your speed. So, if A is forward, and I wanted speed 150, I would type A, “Enter”, 150, “Enter”. I hope this makes sense. Motor library included. I’m new to programming too. All of the print lines are just to show me what the Arduino is thinking. And the first print, the one printing what the serial is receiving, always says -1. I have gotten a program to work going just one way, but I can’t get direction control to work.

``````#include <AFMotor.h>
int val;
int dir;

AF_DCMotor motor(3);

void setup ()  {
Serial.begin(9600);
Serial.print("Start");
motor.setSpeed(0);
motor.run(RELEASE);
}

void loop ()
{
if (Serial.available() > 0)
{
dir = 41;
dir = 42;
if (val == -1)
val = 0;
val = val * 10 + int(Serial.read() - '0');
Serial.println(val, DEC);
Serial.print("Direction: ");
Serial.println(dir, DEC);
}
else {
if (val != -1 && dir == 41) {
Serial.println(val, DEC);
motor.run(FORWARD);
motor.setSpeed(val);
val = -1;
}
delay(15);

if (val != -1 && dir == 42) {
Serial.println(val, DEC);
motor.run(BACKWARD);
motor.setSpeed(val);
val = -1;
}
delay(15);

}
}
``````

Thanks for any help and I’m happy to answer any questions or clarify anything.

``````if (int(Serial.read() == 41))
``````

Serial.read() returns a value, which you compare to 41, using the equality operator. The equality operator returns a value, 41. You are then converting that to an int, and performing the if test on that value, like this:

``````if(41)
{
// do something
}
``````

Since 41 is true, the body of the if test is performed. I really don't think you want to do it this way.

Two weeks from now, will you remember what to enter to get the motor to turn one way?

Try this:

``````int val = Serial.read();
if(val == ')')
{
// Do something
}
``````
``````    if (int(Serial.read() == 42))
dir = 42;
``````

Same problems here. In addition, you are read another byte from the serial port.

0x41 is the hex value for A, not the decimal value, by the way.

``````    if (val == -1)
val = 0;
``````

On the first pass through loop, val has not been explicitly assigned a value.

You are reading as many as 5 times from the serial port, every time you determine that there is at least one byte to read.

Fix these issues, and then we can talk about the problem you are having, if you are still having a problem.