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) { if (int(Serial.read() == 41)) dir = 41; if (int(Serial.read() == 42)) dir = 42; if (val == -1) val = 0; if (int(Serial.read() != 46 || int(Serial.read() != 42))) val = val * 10 + int(Serial.read() - '0'); Serial.println(int(Serial.read())); Serial.print("I received: "); Serial.println(val, DEC); Serial.print("Direction: "); Serial.println(dir, DEC); } else { if (val != -1 && dir == 41) { Serial.print("I received: "); Serial.println(val, DEC); motor.run(FORWARD); motor.setSpeed(val); val = -1; } delay(15); if (val != -1 && dir == 42) { Serial.print("I received: "); 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.