Controlling little motors: Relay Shield

We will use a Motor Shield to control little motors. The Motor Shield is designed to fit on top of an Arduino and it can control up to 4 little DC motors. There are several different types of motors (such as steppers and servos), the simplest of which is referred to as a “DC motor”. This type of motor is the simplest, give it a current and it turns!

The actual shield we are using is documented here, and it looks like this:


Installing the shield

First, you’ll need to push the supplied motor shield onto your Mega. Be careful: make sure you have the pins aligned properly (the motor shield does not supply all of the pins offered on the Arduino). Notice that the shield is short 2 pins on both sides:


The Library

Download the Motor Shield library from here. Unzip it and place it in the ~/Documents/Arduino/libraries folder (on OSX). Once is is there, you will only need to include the lib.

Powering and wiring up the motor

It is recommended to power the motor with an external power supply. That way, the Arduino can be powered by a 9V battery, and the motors can be powered independently. To do this you need to remove the connector on the PWR pins. You can see the connector here:


In this image the connector has been removed. For our purposes, this is the CORRECT way to power the motors:


By removing this connector, the power supply for the motor will not interfere with the Arduino.

Have a look at the following image. The motor is powered by 4 AA batteries, and the Arduino is powered by a 9V battery. In this image, the little motor is attached to the M2 connector. Have a look for the letters “M2” on the shield.

You know that the motor is powered when the green LED light is on.


Controlling the motor

Now that everything is set up, we can start controlling the motor. The shield allows you to change the speed of the motor, and change its direction.

Unplug the 9V, plug in the USB. Launch Arduino, and copy-paste the following code into it:

#include <AFMotor.h>
AF_DCMotor motor(2, MOTOR12_2KHZ);

void setup() {
 Serial.begin(9600); // set up Serial library at 9600 bps

void loop() {
 motor.setSpeed(200); // Speed settings go from 0-255; // Tells motor to run forwards
 delay(2000); // Wait for 2 seconds; // Stop
 delay(4000); // Wait for 4 seconds
 motor.setSpeed(100); // Set a lower speed; // Tells motor to run backwards
 delay(5000); // Wait for 5 seconds

Compile and send it off to the Arduino. In a few seconds the motor will start spinning this way and that!

When you have it working as you would like it, you can unplug the USB cable, plug the 9V back in and VOILA! you are on your way to controlling any old recycled toy you can find! See the video below for what to expect: