In this tutorial, we are going to connect two DC motors to Arduino Uno through motor shield. They are part of the components in Hackabot Robot Kit.
2. Connect the DC motors to the motor shield
There are two terminals in each DC motor. Connect one of the motors to the two connectors of port “M4” and the other motor to port “M3”. Connect the a battery holder which holds four AA size batteries. Black wire connects to “GND” and red wire (+6V) connects to “+M” connector.
3. Stack the motor shield on top of the Ardunio Uno controller board.
It looks like this with the power and motor wires connected. Note: I removed one of the batteries to cut the power. Remember, we did not program the Arduino yet.
4. Download the motor library
The motor shield that comes with the kit is compatible with the motor shield made by AdaFruit as far as I know. You will need to download and import the motor library for the following program to work.
5. A program to move the robot forward
Before uploading the program, please separate the motor shield from the Arduino Uno controller first. This is to protect the board and your computer in case there is bad wiring done in previous steps.
Compile and upload the following program. Unplug your USB programming cable from Arduino Uno after uploading. Attach the controller to the motor shield again. Now, if you put the last battery in, the robot should move forward (hopefully). In case the robot keeps rotating or goes backward, you will have to swap the two wires in port M4 and/or those in port M3 on the motor shield.
The program here is actually very simple. First, it includes the header file from the motor library. It declares two motor objects (motor1 , motor2). They are connected to port 3 and 4 respectively.
When the program executes the first time, it calls the setup() routine. In this routine, the motors are set to speed of 200 (max value : 255).
Once the setup() routine is done, it executes the loop() routine over and over. In this example, it turns both motors forward. It delays by 1 second (1000 ms) before looping back to the beginning of the routine.
It is very easy to modify the program to move the robot in different directions. e.g.