Using Relays with Arduino – Turning on the Lights
Warning!!! This project deals with AC electricity which is dangerous if you don’t know how to treat it safely. You must treat electricity with caution. There are many books and websites about electrical safety procedures and if you’re not sure how to be safe you should read that information. The most basic advice I can give is always assume any exposed wires are live and touching them will hurt a lot at best and kill at worst.
Microcontrollers are good at controlling small devices, but frequently we DIY-ers want to use them to control things that aren’t so micro. In this post I’ll talk about how to turn on household lights with the Arduino microcontroller. Actually this technique isn’t limited to lights, it works for anything that gets plugged into the wall like a table saw or a small rail gun.
The first thing you need is a cheap extension core that you are willing to cut in half. After cutting and stripping the wires you need to solder in a relay. A relay is just like a light switch only instead of using your finger to flip the switch you use a small amount of voltage. Any 5 or 12 volt relay would work, but I already had some OJE-SH-105DM relays sitting around. These relays handle 5Amps at 240V AC. This means they can safely handle 5 Amps at 120V like you find in the US power grid. To get a feel for how much power that is I used Ohm’s Law which states amps*volts=power or in our case 5A * 120V yields 600 watts. That’s enough wattage for me, but if you want to blow up the moon with a giant laser then you just need to use a bigger relay.

I spliced the relay into the black wire on my power cord. For safety reasons you must splice the relay into the live wire. The standard coloring convention is that the black wire is live and the white wire is neutral. If you splice the relay into the wrong wire even when the relay is off the light would still have power to it and you could get electrocuted. I used a DMM to verify which wires were active, neutral, and ground. You can see the schematic for details. Once the relay is wired into the cable I verified that when I applied the trigger voltage (+5V for my 105DM) to the relay that I could hear it flip positions and also verified it was acting as a switch for the extension cord by using my trusty sidekick Mr. DMM again. At this point I knew everything was working as expected so I finished wiring the extension cord together and wrapped it with electrical tape in a safe manor. This needs to be done before you ever plug the extension cord into the wall. Remember you are working with 120V of AC power which is dangerous if not handled properly. If you aren’t sure that you’re being safe then you should find one of the many other websites or books dealing with AC wiring safety. Sorry for sounding like your mother, but I want to make it clear that if you mess this up and shock yourself or burn down your house it’s not my fault. At this point you have a magical extension cord that can power things on and off simply by applying voltage to the relay. Ok maybe it’s not so magical. Apply voltage to the cable seems to be more work than just plugging it in, but trust me in a little while it will be awesome! Test it with your light bulb and a power source to make sure everything is working.
The last step and the one that makes this project useful is getting the microcontroller to control this relay. To do that you can use the following circuit. Most motors and relays shouldn’t be connected directly to a microcontroller because they are inductive and require more current that a microcontroller can safely supply. If you are using a low current 5 volt relay you may be able avoid this circuit (you’d still need to clamp the relay with a diode), but using this circuit should work fine with these small relays so if in doubt use this circuit.
In this circuit the transistor acts as a switch and it allows you to turn on the relay. This circuit works for relays using 5, 9, or 12 volts (the common trigger voltages for relays). I picked a 5 volt relay because that lets me use the Arduino board’s 5V volt output thus eliminating the need for another power source. You also need to protect the microprocessor from back EMF current and that is what the diode is doing.
The cost to build the circuit below should be under $15 dollars and half of that is for a cheap extension cord. RadioShack or online electronic stores will have all the other components.
The code to run this was amazingly simple since the transistor and relay make turning on the extension cord as simple as turning on or off an LED. Here is a program that lets you toggle on and off the relay with the space bar.
// Maurice Ribble
// 4-6-2008
// http://www.glacialwanderer.com/hobbyrobotics
// This code just lets you turn a digital out pin on and off. That's
// all that is needed to verify a relay curcuit is working.
// Press the space bar to toggle the relay on and off.
#define RELAY_PIN 3
void setup()
{
pinMode(RELAY_PIN, OUTPUT);
Serial.begin(9600); // open serial
Serial.println("Press the spacebar to toggle relay on/off");
}
void loop()
{
static int relayVal = 0;
int cmd;
while (Serial.available() > 0)
{
cmd = Serial.read();
switch (cmd)
{
case ' ':
{
relayVal ^= 1; // xor current value with 1 (causes value to toggle)
if (relayVal)
Serial.println("Relay on");
else
Serial.println("Relay off");
break;
}
default:
{
Serial.println("Press the spacebar to toggle relay on/off");
}
}
if (relayVal)
digitalWrite(RELAY_PIN, HIGH);
else
digitalWrite(RELAY_PIN, LOW);
}
}
Credits
I’m not sure who designed this circuit diagram, but I found it referenced on the Arduino website and it was very useful while designing my relay circuit.
I would like thank Oracle, spiffed and the others who helped me make this a better and safer article.




sanspot said,
June 4, 2008 @ 6:36 am
HI! i found out this tutorial very interestin….problem is in the code…it does not work.When i compile it says that in the void loop function > was not declared in this scope…any idea why?
I’d really like to make this work!
Thanks
Glacial Wanderer said,
June 4, 2008 @ 7:34 am
For some reason when I pasted the code into this some of the code was corrupted. It should be fixed now.
You could also get the code from this link which is the file I used when testing this. http://www.glacialwanderer.com/_blog/blog2008/04_April/relay.pde
sanspot said,
June 4, 2008 @ 9:38 am
thanks for the link, i saw it after i posted …but the problem remains the same…when i plug arduino in the usb the light bulb suddenly turn on, when it should be off untill i tell arduino to turn it on right? I am wondering if the problem is in the circuit….it is the same of your, expect for one thing…you connect on the breadboard from the bulb three wires, two from the relay(green wires) and another, that i don’t understand were is it from( the black one).
I have only the two wires from the relay. i would post a photo if i could.
sanspot said,
June 4, 2008 @ 9:41 am
in fact i got two wires from the bulb: one goes to the relay one on the plug of the wall.Then from the plug the remaining wire goes in the relay…then from the relay the 5 volt wires are plugged in the breadbord…
Glacial Wanderer said,
June 4, 2008 @ 5:31 pm
The 3 wires going into the relay are +5V, pin3(signal), and ground to the grounding wire. I suspect your problem is with the circuit some how. You can test the relay without an Arduino (thus eliminating the software complication). All you need to do take the signal wire (it’s currently connected to pin 3), and put that to +5V to turn on the relay and GND to turn off the relay. You should hear the relay flip on and off. If that doesn’t work then adjust your relay circuit until that works. Once that’s working you can connect the arduino again and see if the software half is working.
sanspot said,
June 5, 2008 @ 1:17 am
I now understand what that black wire is…but I put a another wire that goes from the 220V plug to the gnd on the bread board ( as your circuit, in which you have the two green wires of the relay and the black one that comes from the blue wire on the plug…).
In both cases ( with and without the black wire ) the relay works if i conect it to a battery…even when connected to the Arduino…the problem is that instead of being off waiting for Arduino to turn on it is always on…the relay just don’t wait for arduino to turn on the bulb…I don’t understand where the problem is
Glacial Wanderer said,
June 5, 2008 @ 5:52 am
So it sounds like you’ve narrowed it down to the arduino software. As you can see the program is very simple. Have you tried running the Blink example program? http://www.arduino.cc/en/Tutorial/Blink Maybe you aren’t loading the program properly or something. Once you’ve got an LED blinking you can change the blink program to use pin 3 and it should blink your lightbulb. You could also use a DMM and check the voltage of pin 3 with the current program. I’d then start modifying to it’s simplest state so it would set pin 3 high to verify that turns on the ligth bulb, and recompile it with pin 3 low to see that turns off the lightbulb. My best guess right now is that the program isn’t getting loaded correctly. Once you’ve got those simple versions working make sure you remember that you need to make a serial connection before the spacebar will toggle the light on and off (but it should be defaulting to off).
atomriot said,
September 12, 2008 @ 8:46 am
I first have to say Nicely done. This was exactly what I was looking for!
I have implemented this layout for a project for work. I am in much the same book as you where I am a software guy tinkering in the world of electronics.
My implementation uses 3 of your circuits and i have 2 of them working just fine but the third will not throw the relay. When I hook up the DMM I see the 5v on the pin from the Arduino, and I see around .7v on the base pin of the 2N2222. and when I check the collector pin, it is around 3.23v when its switched.
I cannot figure out what is not working. I have changed out the 2N2222 and tested resistance in the 1K resistor and verified the diode isn’t passing back current, and I don’t see any crossover on the soldering and I can manually flip the relay. I am just not sure what it is doing though to get the 3.23V on the collector. Tonight I am going to try and replace everything 1 by 1 but as I said it all tests out individually.
Any ideas?
Glacial Wanderer said,
September 12, 2008 @ 10:28 am
Are you using the same pin on the Arduino to test all 3 of your circuits? If you’re using a circuit board and there is flux on it, you might want to try washing that off with alcohol. Then triple check for shorts. If none of those are the problem I’d try replacing each component like you planned on doing.
atomriot said,
September 12, 2008 @ 11:49 am
Yes, same pin for testing. and i tested all three on three different pins. I will have to give the alcohol thing a try but I will most likely try new components on a different part of the board with clean new solders.
Thanks for the input! I will post back after i try it.
atomriot said,
September 13, 2008 @ 12:43 pm
Ok, I don’t get it. I removed all the components and tried them on a breadboard and it worked just fine. I moved them to 2 different places on my circuit board and it does the 3.23v thing when active. I have tried cleaning it as you said but i see no difference and the other 2 sets of this circuit work fine.
I am lost on this one. Thanks again for your input though!
atomriot said,
September 14, 2008 @ 8:48 pm
well, I know I implied defeat before but I am stubborn headed I guess. After trying 4 more 2N2222′s since everything else seemed to test out, i all but gave up on soldering and started making it on the breadboard again with all new parts. when i tested it…i got the 3 volt thing again and the relay wouldn’t kick. then i though about it and wondered what the little transistor transistor would do if I had it backwards. I switched it around and then it worked…
so the batch of transistors i got from radio shack were labeled backwards and that is what has been causing all of this frustration. so now on my board i have 2 facing one way and one facing another but the orientation of the diodes and ground wires are still the same.
thanks again for your input, and sorry to have flooded your post:)
Roland said,
January 26, 2009 @ 10:14 pm
I am currently using reed relays connected directly to the IO pins of my Arduino Diecimila. See elexp.com, part#22RD-5. Coil is 5v, 500 ohm. That’s only 10mA!
Easily within specs. Cheap too, $1.10 each for 10 or more.
joe said,
February 13, 2009 @ 12:35 pm
That’s not Ohm’s law you’re stating
Bryan Johns said,
April 1, 2009 @ 1:20 pm
How would one wire up a 12v relay instead of the 5v one you used? Basically I’m a little confused about using 5v (arduino) and 12v in the same circuit.
Maurice Ribble said,
April 1, 2009 @ 4:13 pm
I believe the circuit would be the same as above. You just need to make sure your 2n2222 transistor and diode support 12+ volts. Then replace the 5V power supply with a 12V power supply.
Alan Wend said,
May 27, 2009 @ 1:01 am
I’m not a EE but I’m pretty sure you are not supposed to make assumptions about which prong of the power cord is hot and which is ground. You should use a double-pole relay and interrupt both wires.
Thanks for doing this. I’m going to set up an Arduiono as a thermostat to run my swamp cooler. Most
swapmp coolers have separate controls for the pump and the fan, so there are opportunities to save energy and water by running just the fan if the outside temp is already cool enough. Also, if you have temp sensors outside, inside the house, and at one of the vents, you can figure out the humidity. Is there some kind of little display panel that would fit in the Ardiouno box?
Maurice Ribble said,
May 27, 2009 @ 5:22 am
That sounds like a neat project! I’m not sure what display you are using, but I’ve used this one and it works well. http://www.sparkfun.com/commerce/product_info.php?products_id=461
There is a standard so I think it is ok to to use a single pole relay. I’ve looked at some lamp switches and they are single pole. I don’t see any problems with a double pole relay as long as you have a 3 prong plug with the separate ground.
Hobby Robotics » DIY Outdoor Time-Lapse Photography said,
June 13, 2009 @ 7:38 pm
[...] The basic premise is to run an Arduino as a timer and once an hour it turns on a relay. The reason for the relay is minimize power usage while the Arduino is running as a timer. When the relay is powered up the servo and camera also get turned on. Then the Arduino uses a servo to turn on the camera and take a picture. A 5 volt regulator is used to make sure the system could provide enough current to the servo and camera. After seeing how little current my camera draws, I realized I could have used the 5 volt regulator on the Ardunio board, but the regulator is cheap so there is no harm in using it like I did. You want to make sure the coil on the 5 volt relay you choose uses less than 40 mA or you will exceed the max current draw from an Arduino pin which could damage the Arduino after extended use. If you want to use a relay with a greater than 40 mA current draw you should use a circuit like I described in this article. [...]
Steve said,
June 16, 2009 @ 4:02 am
Here’s a device that might simplify things.
http://www.powerswitchtail.com
peter said,
June 23, 2009 @ 9:07 pm
@steve: patent pending, eh? How’s that search for prior art going?
matto said,
July 1, 2009 @ 1:09 pm
I’m loving this tutorial.. its something that everyone who’s into arduino stuff should know.
Are there any considerations / modifications you can suggest for applying this to a British power supply (240v)?
Thanks
Maurice Ribble said,
July 6, 2009 @ 8:46 am
The main thing that would change is making sure the relay you choose supports 240 volts at the current you want. The other thing to consider is the British probably use different colors for their wires. You want to make sure you put the relay on the active wire. If you don’t know the color for the active wire I’m sure google can help out.
Zashkaser said,
August 5, 2009 @ 11:23 am
I wanted to ask, is there any chance for a modified version of the directory listing script, with an iphone-stylish like design?
Maurice Ribble said,
August 5, 2009 @ 2:49 pm
Zashkaser, I’m not sure what you mean by “directory listing script”. Maybe you mean code? Anyways I don’t plan to do any modifications to this for the iphone since I don’t have one or plan to get one. Perhaps someone else will.
Ricardo Carvalho said,
September 3, 2009 @ 4:14 am
hey guys, I’ve got a few questions and was wondering you you could help:
1. The relay that you mention for the tutorial: OJE-SH-105DM,095 tolerates voltage up to 240V, meaning this would be OK for UK mains right? What does the term contact rating mean?
2. Do relays normally have a maximum restriction and not a minimum restriction?
3. You mention that your circuit produces 600w (5*120V), so us here in Europe would produce 1200w, correct? What relation does this have with the wattage of the light bulb we use?
4. If I want to have more than 1 light bulb, do I need to have one relay for each one?
5. I would like to have my lights fade in and out as it they were pulsating like a heart beat, what type of light bulb would be best suited for this? (using the arduino of course)
Thanks in advance for your help!!
ric
Ricardo Carvalho said,
September 3, 2009 @ 4:32 am
I found this UK company that sells all sorts of different relays which I presume work at 5A @ 240VAC but there are some characteristics that I’m still not quite understanding:
http://search.digikey.com/scripts/DkSearch/dksus.dll
–> Coil Voltage? Does it have to be exactly the same as the arduino board? (5V)
–> Control On / Control Off? How does this affect my circuit? Do I need to worry about this?
–> Coil Current? Why is this different from the Current discribed in the Contact Rating?
Of these ones from the list which is the best suited for using with arduino?
again thanks for your help!!!
Maurice Ribble said,
September 3, 2009 @ 6:04 am
1) Yes, 240V means it should work in the UK.
3) Yes, it should support 1200W on 240V. In releation to a light bulb this means you could drive 12 100W light bulbs with a single relay.
4) You can run multiple light bulbs from a single relay, but they will all go on and off at the same time. If you want to control each lightbulb independently. If you need to control lots of Lights independently look into shift out registers which let you expand the number of outputs supported by a microcontroller.
5) You can’t use florescent bulbs when dimming. And incandescent bulb should work. You could either do dimming with pulse width modulation or additional hardware to control voltage. If you go with PWM make sure the relay is fast enough (might need solid state). Also the relay will make a lot of noise and you need to calculate it’s life span. You might want to consider hacking a light dimmer switch. I don’t know what the best answer is here. I’d recommend researching this and doing some small experiments.
Most any relay that is driven by 5V input and supports your required amps is fine if you aren’t doing light dimming. With light dimming things get more complicated and you will need to figure that out.
Jake said,
October 2, 2009 @ 7:16 pm
PDF of the circuit from Arduino: http://www.arduino.cc/playground/uploads/Learning/relays.pdf
raziiq said,
December 24, 2009 @ 1:14 am
Hi there.
I am trying to build the same project, but i am using a SSR instead of simple relays, so i think i dont need Transistor, right?
Maurice Ribble said,
December 27, 2009 @ 10:03 pm
Raziiq, that is correct.
Vinz said,
January 22, 2010 @ 11:03 am
Hi,
I read these posts but I still have a doubt.
In my house I already have a relay based light switching system. I mean, I have push buttons on the wall, connected to a finder 220vots relay, connected to a 220volt lamp (consider about 60-80w in the worst case). I push teh button on the wall one time and the light turns on, I push teh button on the wall another time and the light turns off. Simple, isn’t it?
I’ve already put other puch buttons in parallel to the existing relay and everyting works fine and I can switch the same lamp from different places in the house.
Now I’d like to put in parallel my beautiful Arduino and use it to switch the same lamp. I just have to put something (a transistor? another smaller relay?) in parallel to the existing relay and simulate the pushing of the button on the wall, giving to the 220v relay a 220v pulse to switch on/off.
In other words, I just need to control a 220v relay from arduino, using the minimal electronic. I have to do this to many lamps and other appliances and I have to do it in a cheap but safe way, so no costly redoundant, unneeded components, but just the minimal right ones.
Some of you gentle people would help me in solving this simple, basic electric problem?
I thank you very much and I’me sure this is a common problem and the right solution would help many people…
Vinz
James Fowler said,
February 17, 2010 @ 1:12 am
I won’t lie im a coder by no means lol i know basic electronics and i bought this for some inspiration but i fear i jumped in over my head with rocks in my pockets lol
how would i go about having this exact same circuit but 2 or 3 diffrent relay controls my problem isn’t with the electronics my problem is with the code i want to be able to press 1 to toggle pin 12 on and off press 2 for 11 on off and press 3 for 10 on / off thats it lol but for the life of trying to play with the code i can”t figure it out lol it certainly is no html
Maurice Ribble said,
February 17, 2010 @ 6:46 am
Vinz, your use case sounds like the exact circuit in the article. Is there something specific you have a question about? If not just use that circuit.
James, you just need to do something similar to what I did for the spacebar. I recommend checking out some of the tutorials here (http://arduino.cc/en/Tutorial/HomePage) to get an understanding of how the code works. If you spend time understanding a few simple examples I’m sure you can write the code to do what you want.
James Fowler said,
February 18, 2010 @ 1:15 am
I solved my problem after much thought and a bit of help if anyone else is intrested
#define RELAY1 13
#define RELAY2 12
void setup()
{
pinMode(RELAY1, OUTPUT);
pinMode(RELAY2, OUTPUT);
Serial.begin(9600); // open serial
Serial.println(“Press 1 or 2 to toggle relay on/off”);
}
boolean relay1State = false; // Assume off to start with
boolean relay2State = false;
void loop()
{
static int relayVal = 0;
int cmd;
while (Serial.available() > 0)
{
cmd = Serial.read();
switch (cmd)
{
case ’1′:
{
relay1State = !relay1State; // If true make false if false make true
digitalWrite(RELAY1, relay1State);
break;
}
case ’2′:
{
relay2State = !relay2State; // If true make false if false make true
digitalWrite(RELAY2, relay2State);
break;
}
default:
{
Serial.println(“There are only 2 options Relay 1 or Relay 2″);
}
}
}
}
Mark Crosbie said,
April 27, 2010 @ 3:59 pm
Hey really good tutorial and helpful comments from all, working on a project at college were we need to turn on lights individually through an arduino, perhaps a set of christmas lights! Probably have a lot more questions but for Robbie I was wondering did you put this code in the arduino software or did you put it in Flash CS4 Code actionscript? If not any tips on transferring it into flash?
Thanks very much,
Mark Crosbie,
The Project Free Bird Team.
http://www.theprojectfreebird.wordpress.com
Mark Crosbie said,
April 28, 2010 @ 4:12 am
Hey sorry, just noticed I said Robbie instead of James Fowler, although if anyone has any tips on my last post am all ears!
Thanks
Maurice Ribble said,
April 28, 2010 @ 7:15 am
The code above is uploaded to the Arduino. If you want to control the lights with flash you’ll probably do that over serial (or if you want wireless use something like xbee). You’d need to write a flash app that does sends Arduino commands and then modify the Arduino code to process those commands. I’m sure if you looked on an the Arduino site there would be tutorials on how to do this. I’ve never used flash because the Adobe tools are closed source and too expensive for me. I have done this sort of interfacing with C, perl, hacking directing in xterm, and probably the easiest was processing.org.
Ciaran Mc Guirk said,
April 28, 2010 @ 11:50 am
hey guys, i’m a bit simple when it comes to electronic blueprints. was wondering if there was clearer pictures of wiring up the relay and what way the breadboard wiring works. sorry for the hassle. thanks a million, it would be appreciated
Ciaran Mc Guirk said,
April 28, 2010 @ 11:52 am
hey guys, i’m a bit simple when it comes to electronic blueprints. was wondering if there was clearer pictures of wiring up the relay and what way the breadboard wiring works. sorry for the hassle. thanks a million, it would be appreciated if you could get back asap
Phil said,
May 14, 2010 @ 11:43 am
I blow a breaker every time the relay switches on.
Maurice Ribble said,
May 14, 2010 @ 11:52 am
Ciaran, I don’t have time to revisit this right now. Sorry. I bet with some googling you can fine what you want.
Phil, that means your wiring for the lighbulb is wrong. You must be shorting ground to power. Double check your wiring to make sure there aren’t any shorts.