FIGURE 6. Basic wiring diagram for connecting an
Arduino microcontroller to an H-bridge module. When
using a shield, the electrical contact between the Arduino
and module is incorporated in the edge connectors.
/*
DC motor driver speed test
Motor connected to
digital pins 4&5
*/
const int M1_Ctrl = 6;
const int M1_Dir = 7;
Listing 2 — PWM
Motor Speed
Control Demo.
void setup() {
pinMode(M1_Ctrl, OUTPUT);
pinMode(M1_Dir, OUTPUT);
digitalWrite(M1_Dir, LOW); //Set direction
}
void loop() {
for(int i=96; i<=255; i++) { //Sweep speed from
analogWrite(M1_Ctrl, i); // 96 to 255
delay(35); //Delay 35ms
// between changes
}
analogWrite(M1_Ctrl, 0); //Turn motor full
// off
delay(1000); //Wait one second
}
an L298 motor bridge IC. The shield I used is from DFRobot
(available at Robotstore.com, among other online
retailers). Another option is the DFRobot Romeo which
combines an Arduino and the L298 shield in one unit.
The shield includes the L298 chip itself, plus the
necessary flyback diodes to protect the L298 from back-EMF produced by the motors. Power for the motors is
separate from the power to the Arduino and the logic
circuitry on the shield.
(Note the addition of the 0.1 µF ceramic disc capacitors
46 SERVO 06.2011
/*
DC motor driver test
Motors connected to digital pins
4&5, and 6&7
*/
const int M1_Ctrl = 6; //Set pin
// assignments
const int M1_Dir = 7;
const int M2_Ctrl = 5;
const int M2_Dir = 4;
void setup() {
pinMode(M1_Ctrl, OUTPUT); //All pins are
// OUTPUTS
pinMode(M1_Dir, OUTPUT);
pinMode(M2_Ctrl, OUTPUT);
pinMode(M2_Dir, OUTPUT);
}
void loop() { //Loop through motion
// routines
robot_fwd();
delay(3000); //Delay 3 seconds before
// moving on
robot_rev();
delay(3000);
robot_right();
delay(3000);
robot_left();
delay(3000);
Listing 1 — Mini
T-Bot Demo.
robot_stop();
delay(1500);
}
//Motion routines for forward, reverse,
// spin right, spin left, and stop
void robot_fwd() {
digitalWrite(M1_Dir, HIGH);
digitalWrite(M1_Ctrl, HIGH);
digitalWrite(M2_Dir, LOW);
digitalWrite(M2_Ctrl, HIGH);
}
void robot_rev() {
digitalWrite(M1_Dir, LOW);
digitalWrite(M1_Ctrl, HIGH);
digitalWrite(M2_Dir, HIGH);
digitalWrite(M2_Ctrl, HIGH);
}
void robot_left() {
digitalWrite(M1_Dir, LOW);
digitalWrite(M1_Ctrl, HIGH);
digitalWrite(M2_Dir, LOW);
digitalWrite(M2_Ctrl, HIGH);
}
void robot_right() {
digitalWrite(M1_Dir, HIGH);
digitalWrite(M1_Ctrl, HIGH);
digitalWrite(M2_Dir, HIGH);
digitalWrite(M2_Ctrl, HIGH);
}
void robot_stop() {
digitalWrite(M1_Ctrl, LOW);
digitalWrite(M2_Ctrl, LOW);
}
at the motors. For best results, solder these directly to the
terminals on the motor. The capacitors help to suppress
noise caused by the motors which can interfere with the
proper functioning of the microcontroller.)