Category Archives: relays

Arduino 8: Relays

A relay is a switch that allows a small current from the Arduino to turn on or off a device drawing a much larger current.  This is usually a concern if you want the Arduino to control an electric motor, which will typically want to draw more current than the Arduino can handle. Relays are the key to turning your Arduino into a controller for any motorized project, and are great fun in combination with any motorized construction kit like Lego, K’Nex or FischerTechnik. I bought a set of Fischertechnik Mechanic and Static kits with a grant a few years back, and combined with the Arduinos they make wonderful platforms for computer-controlled mechanical models, like working elevators and light-seeking robots.

Relays come in different shapes, but typically have four pins:   an input voltage Vin from a power supply, ground, a data pin to turn the relay on or off (this is what the Arduino does), and an output voltage pin to the device you want to control.  Buy a relay that can be controlled by 5V DC (the Arduino) – the output depends on what you want to control with it. Lots of larger motors want 12V DC or so, so get a relay that can handle a bit more than that. The relay should come with a spec sheet telling you which pin is which. If not, Google “relay spec sheet” and the part number, and you’ll probably find the document online.

Image made with Fritzing (http://fritzing.org/)

In this project we have the Arduino read the state of a pushbutton, and use that to turn a small DC motor on and off. You might wonder what’s the point – just wire the pushbutton to the motor power supply and forget the Arduino. The point is, the pushbutton can be replaced by any sensor, so the Arduino can use any input signal to trigger the motor.  Use a 9V battery to power the Arduino and motor, so it doesn’t have to run off the weaker supply delivered by the USB cable. This means you need to get a 9V battery clip (or wall power supply), and solder it to a 2.1mm center-positive plug to fit the Arduino power connector. The new Duemilanove board will automatically sense the power supply when connected, but older boards have a little jumper next to the USB connector that needs to be switched from USB to EXT.

In the picture, the top left pin of the relay is the data pin, going to pin 13; the bottom right pin is ground; the pin just right of that is Vin on the Arduino; and the bottom right pin goes to the motor’s + terminal. The other motor terminal goes to ground. The pushbutton has one terminal connected to +5V, the other connected both to digital input pin 2 and to a 10K resistor leading to ground.

Program:

int buttonPin = 2;
int relayPin = 13;
int state=0;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(relayPin, OUTPUT);
}
void loop() {
state = digitalRead(buttonPin);
if (state==HIGH) {
digitalWrite(relayPin, HIGH);
} else {
digitalWrite(relayPin, LOW);
}
delay(100);
}
Advertisements