All, I had trouble finding some simple example code for controlling a standard DC motor using an Arduino.
This must be a popular thing to do. In the end I wrote my own example, which works OK, here it is.
It would be helpful to have something like this as a standard example.
//Standard PWM DC control
int pwmPinM1 = 5; //M1 Speed Control
int pwmPinM2 = 6; //M2 Speed Control
int dirPinM1 = 4; //M1 Direction Control
int dirPinM2 = 7; //M1 Direction Control
void controlM1(boolean forward, char sp)
{
char pwmVal = forward == false ? sp : 255 - sp;
digitalWrite(dirPinM1, forward);
analogWrite(pwmPinM1, pwmVal);
}
void controlM2(boolean forward, char sp)
{
char pwmVal = forward == false ? sp : 255 - sp;
digitalWrite(dirPinM2, forward);
analogWrite(pwmPinM2, pwmVal);
}
void forwardM1(char sp)
{
controlM1(true, sp);
}
void forwardM2(char sp)
{
controlM2(true, sp);
}
void backwardM1(char sp)
{
controlM1(false, sp);
}
void backwardM2(char sp)
{
controlM2(false, sp);
}
void stopM1(void)
{
// Stop using backward because of a known issue
// with low(ish) PWM values on pin 5 and 6
backwardM1(0);
}
void stopM2(void)
{
// Stop using backward because of a known issue
// with low(ish) PWM values on pin 5 and 6
backwardM2(0);
}
void setup(void)
{
pinMode(dirPinM1, OUTPUT);
pinMode(pwmPinM1, OUTPUT); // May not be necessary
pinMode(dirPinM2, OUTPUT);
pinMode(pwmPinM2, OUTPUT); // May not be necessary
}
void loop(void)
{
// Both forward the hard way
controlM1(true, 255);
controlM2(true, 255);
delay(5000);
// Both backwards the hard way
controlM1(false, 255);
controlM2(false, 255);
delay(5000);
// Use a helper to turn in opposite directions
forwardM1(100);
backwardM2(100);
delay(5000);
// Use a helper to turn in opposite directions
backwardM1(100);
forwardM2(100);
delay(5000);
// Use a helper to stop both motors
stopM1();
stopM2();
delay(5000);
}