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

// 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()
  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 =;
    switch (cmd)
    case ' ':
        relayVal ^= 1; // xor current value with 1 (causes value to toggle)
        if (relayVal)
          Serial.println("Relay on");
          Serial.println("Relay off");
        Serial.println("Press the spacebar to toggle relay on/off");
    if (relayVal)
      digitalWrite(RELAY_PIN, HIGH);
      digitalWrite(RELAY_PIN, LOW);


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.


  1. 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 &gt was not declared in this scope…any idea why?
    I’d really like to make this work!


  2. 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.

  3. 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.

  4. 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…

  5. 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.

  6. 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

  7. 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? 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).

  8. 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?

  9. 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.

  10. 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.

  11. 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!

  12. 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:)

  13. 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, part#22RD-5. Coil is 5v, 500 ohm. That’s only 10mA!
    Easily within specs. Cheap too, $1.10 each for 10 or more.

  14. joe said,

    February 13, 2009 @ 12:35 pm

    That’s not Ohm’s law you’re stating :-)

  15. 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.

  16. 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.

  17. 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?

  18. 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.

    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.

  19. 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. [...]

  20. Steve said,

    June 16, 2009 @ 4:02 am

    Here’s a device that might simplify things.

  21. peter said,

    June 23, 2009 @ 9:07 pm

    @steve: patent pending, eh? How’s that search for prior art going?

  22. 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)?


  23. 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.

  24. 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?

  25. 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.

  26. 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!!


  27. 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:

    –> 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!!!

  28. 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.

  29. Jake said,

    October 2, 2009 @ 7:16 pm

    PDF of the circuit from Arduino:

  30. 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?

  31. Maurice Ribble said,

    December 27, 2009 @ 10:03 pm

    Raziiq, that is correct.

  32. Vinz said,

    January 22, 2010 @ 11:03 am

    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…


  33. 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 :P

  34. 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 ( 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.

  35. 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 =;

    switch (cmd)
    case ’1′:
    relay1State = !relay1State; // If true make false if false make true
    digitalWrite(RELAY1, relay1State);
    case ’2′:
    relay2State = !relay2State; // If true make false if false make true
    digitalWrite(RELAY2, relay2State);
    Serial.println(“There are only 2 options Relay 1 or Relay 2″);

  36. 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.

  37. 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!

  38. 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

  39. 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

  40. 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

  41. Phil said,

    May 14, 2010 @ 11:43 am

    I blow a breaker every time the relay switches on.

  42. 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.

  43. jeff said,

    August 17, 2010 @ 12:32 pm

    hey there… i’ve used this example with some good results… but just got completely stumped when i tried to wire up 5 circuits… and one by one all my relays seem to be stuck on now… would i need more than the 5v coming off the arduino to get this working? i still hear the relays clicking, but they are always on– does that mean they got too much current? also, if you wire several circuits such that they are all drawing from the same power, is the circuit closest too the power receiving more current than the others (whatever relay i put there sounds different)… any help you could give me would be great… thanks

  44. Maurice Ribble said,

    August 17, 2010 @ 1:05 pm

    Jeff, do you have 5 transistors and 5 pins coming from the Arduino so you have one pin to control each relay?

    Take a look at the spec for your relay and figure out how much current the coil takes. It might be something like 100 mA. So 5 relays would be 500 mA which might mean you need an external 5V power supply to get enough current.

    Just to make sure the software and wiring is correct try disconnecting 4 of the relays to verify a single one still works with the wiring and software changes.

  45. jeff said,

    August 17, 2010 @ 2:24 pm

    too clarify, whichever relay is connected to digitalPin 0 is louder than the others… but on the software end I’m sending osc:

    /*/digitalWrite $1

    so, shouldn’t all the outs act the same?

  46. jeff said,

    August 17, 2010 @ 2:29 pm

    I have 5 transistors, and 5 relays (your circuit 5 times)…

    when i unhook all of them, and just try one the relays click (so long as i use digitalOut 0), but are stuck on… could I have killed the relay with too little current?

    also, if i am toggling all the outs, I should be able to hook up any out and get the same results right? does this sound like a software problem also?

  47. jeff said,

    August 17, 2010 @ 2:44 pm

    if the nominal current is 20mA, then I’m looking at 100mA total?
    and do i also need to consider that each relay’s coil resistance is 250 ohms?

  48. Maurice Ribble said,

    August 19, 2010 @ 7:52 am

    Jeff, I don’t understand most of your questions. Could you try restating them in complete thoughts?

    To answer the ones I do understand. If your circuit is similar to mine you don’t need to worry about the ohms (I’d suggest reading about ohms law to understand why). 100 mA is correct if each relay is 20 mA and you have 5.

  49. Jeff said,

    August 19, 2010 @ 5:37 pm

    sorry for the confusion-

    i bought an external regulated 5vdc power souce (1000mA), so when it comes the only connection to the arduino will be the digital outs- right?

    how’s does external power work in terms of grounding the dc circuit? do i still need use the ground on the arduino as well?

    as far as weirdness i found when trouble shooting, i found the digital out 0 made all the relays click louder than the other digital outs– so i’m looking at the software to fix that right? (i guess i don’t understand, if power is coming from 5v on the arduino, or an external power, what’s being sent out a digital out?)

    and lastly, is it possible to damage a component by powering it with too little current?
    when i try to run only one (normally open) relay, its stuck closed– but i should have enough current for one relay circuit, no problem? so the relay is damaged? does that make sense?

    do you have any recommendations for an electronics primer- the book i have (the art of electronics) is a bit too dense for me so far

  50. Silenc3 said,

    August 26, 2010 @ 11:34 pm

    Hi, im kinda new to the arduino boards so im not really sure whats the right info to look for so i was hoping someone could answer my question?

    With arduino can you A. Program it to flip a switch from an external source that would input information that the arduino board would take and interpret the data too turn the relay off and on?


    B. If A is possible thru some means can i then just hook up the arduino board to a power source and use the external device to input off and on to whatever the board is hooked up too

    sorry if this sounds stupid i dont know much about this i only recently got into this

  51. gamelan and electronics: relay | Jeff Aaron Bryant said,

    September 5, 2010 @ 7:06 pm

    [...] first built a circuit as described on this post and it worked great. I soldered the circuit into a PCB and it was totally fine. The second worked [...]

  52. lifeinla said,

    September 9, 2010 @ 12:22 pm

    complete noob here, but interested b4 i get to buying and trying this out to know if you can integrate a motion sensor into this a circuit like this – so that the bulb is on as motion is detected.

  53. Matthew A said,

    September 24, 2010 @ 2:28 am

    I, as well as the others in this room, am a noob and just have a quick question. I am trying to use a Ping))) as well as a servo in combination with an arduino board to convert my boring ole light switch into a cool state-of-the-art motion detector switch. As you may guess, I plan on using the Ping))) to detect motion up to a certain point and then turn the Servo to flip the switch on the light. However, my question comes in the..physics.., if you will, of the situation. When hooking up this project is it safe to connect the arduino directly to the power from the house in order to properly flip the power on and off? I understand the arduino can carry a maximum of 5V, but the house would be pushing 120V to light the light bulb. Will I blow the hardware no matter what or is there a way to hook up everything to were the power just goes passed the arduino and onto the light fixture. Thanx for any help at all I am an inspired engineer and am excited to work with this here Arduino :)

  54. Raphael Cerqueira said,

    October 17, 2010 @ 10:46 pm

    I think you would like to see your work been used.

  55. newbie said,

    April 30, 2011 @ 2:14 pm


    I have a quick question (full disclosure – I suck at all things circuit design, programmer here)

    Where is the white wire (+5v) going) on the breadboard ?

    Thank you in advance…

  56. Rian said,

    October 5, 2011 @ 2:30 am


    Your write up has helped me a lot with getting started in controlling things with Arduino.

    I do have a question about the circuit though that has me stumped.

    What modification would I have to make to have an LED come on while the relay is off and then have the LED go off when the relay is switched on without using an output pin from Arduino just to control it.



  57. Maurice Ribble said,

    October 5, 2011 @ 6:37 am

    All you need is inverter off of pin3. There are logic buffers that would do this or you could use a pnp transistor.

  58. Rian said,

    October 6, 2011 @ 4:45 am

    It has been 10+ years since I knew what the common electrical components do so I’m struggling a bit. Is anyone able to elaborate on Maurice’s comment because while I know what these things are and basically what they do I have no idea how to intergrate them into the circuit.

  59. Rian said,

    October 8, 2011 @ 3:05 am

    Ignore the above I worked it out.

  60. kardamyla said,

    October 8, 2011 @ 2:29 pm

    I’m and end user, I do not know anything about relays. I been trying for days to hook up a relay to turn on a light using an Axis camera with an I/O switch. This is the relay
    This is the manual for the Axis 207 207W camera the camera is 3,3 volt with a max 50ma, I dont even know if this is correct relay. I’m willing to pay someone for help me make this work. Thank you

  61. kardamyla said,

    October 8, 2011 @ 2:32 pm

    This is what I got from Axis

    Thank you for contacting Axis Communications. While I have not tested a specific relay to use. I would suggest looking at as they have a large variety of relays.

    The relay should be 3.3volts and a max of 50ma.

  62. kardamyla said,

    October 8, 2011 @ 2:36 pm

    This company makes a relay that works but they are asking 70 euro=110 dollars plus 30 shipping. For a relay that cost 5 dollars. I know they need to make a profit but this outrageous.

  63. kardamyla said,

    October 8, 2011 @ 2:37 pm

    Sorry this is the link

  64. francis said,

    October 30, 2011 @ 8:41 am

    hey really i need the circuit fast and i dint understand urs (bcs im not good)so could just tell me how to connect i saw a 5 pin realy at the store urs is a 4pin so could ya just show to me i dint get the cicuit (the relay part)

  65. fabienne said,

    November 21, 2011 @ 2:49 am

    Hi there, first i’d like to say thanks so much for this super sweet & simple tutorial! setting up the circuit and understanding how things should theoretically work (as an inexperienced arduino tinkerer) was a piece of cake!

    there’s only one aspect i am not getting or having problems with. This spacebar on off switch doesn’t seem to be working for me. I tried to test out the circuit on an LED but connecting the ground of the LED directly to the ground on the breadboard and putting the relay inbetween the 5v and the positive lead of the LED. From what i understood this should work..

    but then i realized that i dont understand how the arduino ‘knows’ when i hit the spacebard. i realize its written in the code but in terms of hardware, how does the arduino recognize the keyboard on my computer? It seems like this ought to be a simple solution.

    also, any suggestions for how to use a PIR sensor in place of the spacebar?

  66. fabienne said,

    November 21, 2011 @ 3:18 am


    simple ‘rookie’ oversight since im so unfamiliar with the arduino application!
    thank you so much! still looking for any suggestions on integrating the PIR though… !

  67. Saw0 said,

    November 29, 2011 @ 9:57 pm

    fabienne, which PIR do you have, and how do you want it to act exactly?

  68. David said,

    January 3, 2012 @ 10:16 am

    Thanks for a simple, effective tutorial.

    I do have one small problem though. Everything works, apart from when I connect the diode. I don’t want to fry my arduino with flyback voltage from the relay, but the circuit just doesn’t work with it in there.

    The diode I have is a 1N4004G, not just 1N4004. Would that make a difference?

    Thanks for anyone’s help. I’ll be sure to post again if I manage to work it out.

  69. Chez said,

    January 4, 2012 @ 10:59 pm

    David, you wouldn’t fry the Arduino, only the transistor. What you might try (I’m doing this now) is sinking the relay from the Arduino instead of the 2N2222. Most silicon devices can sink (provide connection to ground) more current than they can source (provide connection to VCC). I’m running a relay of about the same size directly from the Arduino. So tie the relay to Arduino pin 3 but tell the code HIGH means off, LOW means on.

    Here’s a push-button toggle program I modified from the “button.ino” example:

    // constants won’t change. They’re used here to
    // set pin numbers:
    const int buttonPin = 2; // the number of the pushbutton pin
    const int ledPin = 13; // the number of the LED pin

    // variables will change:
    int buttonState = 0; // variable for reading the pushbutton status
    int relayState = 0; // relay is off at start

    void setup() {
    // initialize the LED pin as an output:
    pinMode(ledPin, OUTPUT);
    // initialize the pushbutton pin as an input:
    pinMode(buttonPin, INPUT);

    void loop(){
    // read the state of the pushbutton value:
    buttonState = digitalRead(buttonPin);

    // check if the pushbutton is pressed.
    // if it is, the buttonState is HIGH:
    if (buttonState == HIGH) {
    // change relay state
    // see if relay is on or off:
    if (relayState == HIGH) {
    digitalWrite(ledPin, HIGH);
    relayState = 0;
    // if relay is on, turn it off
    // counterintuitive, but HIGH turns relay off
    else {
    digitalWrite(ledPin, LOW);
    relayState = 1;
    // if relay is off, turn it on
    // counterintuitive, but LOW turns relay on
    // debounce

    Give that a try?


  70. David said,

    January 5, 2012 @ 1:53 pm

    Hey R//Chez,

    Thanks for the tip! I’ve changed the 240v wiring on the relay to [on as default], messed around with my code and made it work. (I won’t mention the part when I forgot to turn the transistor around).

    Here’s the code I’m using to achieve a randomish strobe of the lamp every few seconds.

    Thanks for the help!



    int ledPin = 3; // Transistor connected to digital pin 3
    long randOn = 0; // Initialize a variable for the ON time
    long randOff = 0; // Initialize a variable for the OFF time

    void setup() // run once, when the sketch starts
    randomSeed (analogRead (0)); // randomize
    pinMode(ledPin, OUTPUT); // sets the digital pin as output

    void loop() // run over and over again
    randOn = random (30, 130); // generate ON time between 0.1 and 1.2 seconds
    randOff = random (1000, 6000); // generate OFF time between 2 and 9 seconds
    digitalWrite(ledPin, HIGH); // sets the Transistor OFF
    delay(randOff); // waits for a random time while OFF
    digitalWrite(ledPin, LOW); // sets the Transistor ON
    delay(randOn); // waits for a random time while ON

  71. David said,

    January 5, 2012 @ 1:55 pm

    Forgot to mention, I left the Transistor in, as a safeguard. It’s cheaper to replace than an Uno.


  72. Light controller | Jeff's projects said,

    January 15, 2012 @ 5:24 pm

    [...] control circuit, not the sensing circuit, was based on  The difference between my version and his is that I thought the transistor was unnecessary, so I [...]

  73. Coffee Maker Mod - (Baltimore) Harford Hackerspace said,

    January 23, 2012 @ 10:11 am

    [...] wall cord and the power switch on the coffee pot. The relay is controlled by his arduino. He used this tutorial as a guide. [Show as slideshow] Share [...]

  74. Sources d’information utilisées « Bon Matex said,

    February 15, 2012 @ 11:37 pm

    [...] [...]

  75. Tim said,

    February 18, 2012 @ 8:57 pm

    Hello people,

    Thanks for the great tutorial, very easy to follow.
    But unlike Fabienne, who said: “but then i realized that i dont understand how the arduino ‘knows’ when i hit the spacebard. i realize its written in the code but in terms of hardware, how does the arduino recognize the keyboard on my computer? It seems like this ought to be a simple solution.”,
    I can’t to overcome the simple rookie oversight. Could anyone help me out and explain to me
    how the keyboard function works?

    Many many thanks!


  76. Roombox Blog | Third functionality: Switching relays using arduino said,

    March 1, 2012 @ 10:08 am

    [...] i’ve managed to switch relays using my arduino kit. I found this circuit on the web and edited it to switch a couple of relays instead of [...]

  77. Easiest/cheapest way to computerize and automate a grow? said,

    March 30, 2012 @ 10:57 pm

    [...] moisture sensors that can be connected to a computer? (1) Microcontroller + Relay = WIN (2) Plenty of OTC temp, and humidity sensors to choose from. Soil moisture should just be a [...]

  78. Diego Aguilera said,

    May 21, 2012 @ 10:38 am

    NO and NC relays.

    First off, I don’t want to scare anyone off from doing a project like this. This is just a caution. Relays come in different variations: normally open, normally closed, and CO (Change over). Depending on your project, depends on the relay you need to buy. For example, if you have a circuit that will constantly be on and off when the Arduino sends a voltage to it, you want a normally closed. If your light is normally off and turns on when the Arduino tells it to turn on, then buy a normally open. The reason for picking the correcnt relay is current. Because a relay will always have some internal resistance, you will have power loss in the relay (P = i*r). This loss is always in the form of heat. Normally closed relays are designed to be able to handle current being constantly supplied. If you don’t account for this current, the relay could burn up. Not to say it’s going to catch fire. It will most likely smoke and just never work again. But why risk it? I’ve also used this same circuit with a relay from Sparkfun to turn my Christmas tree off/on for a few weeks. It worked just fine. Great write up!

  79. Salvo's Blog said,

    June 8, 2012 @ 8:03 am

    Scheda relè / Relay Shield…

    Realizzare una scheda relè è abbastanza semplice   (Immagini realizzate utilizzando fritzing) Necessario: 1 Prototyping board 1 Relè 5V DC (SRD-05VDC) 1 Diodo 1N4007 1 Resistenza da 1 kΩ (io ho usato una da 465Ω e va bene lo stesso) 1 Transistor NPN (2…

  80. Cool Data Log images | The art of data acquisition said,

    June 21, 2012 @ 2:53 pm

    [...] Image by jmsaltzman First mockup of Arduino-controlled garden, here switching a relay attached to a submersible pump to automatically water two [...]

  81. Arduino Garage Door Opener Pt 2 | The Heffies said,

    July 27, 2012 @ 7:49 pm

    [...] done it even close to correctly. To do so, I used this Arduino sketch that this fellow had on his site, that allows you to control the relay using the serial interface on the Arduino, by hitting the [...]

  82. Mr.Mechatronics said,

    August 10, 2012 @ 5:59 am

    Hi there,
    This is more interesting question…
    Speaking of Home automation/security:

    I have a relay which I will be using to bypass my existing switch(light) SPST
    Ardruino will turn on the relay (let say PIN 13) stand alone, without communicating with the computer.
    The output will trigger using its internal clock , let say 1st day :12:00 am up to 12:15am then switch on 12:30am-12:32…….RANDOM time in RANDOM INTERVAL……up to 3:00am.
    Condition 3:
    Audrino will make a random combination in 7 days…but limited only between 12:00 to 3:00am.
    (to fool the burglars that they are expected…hmmmm)
    I hope that this will also be helpful to others…never mind the electric bill ….security is PRICELESS!
    And please help me with the code.. A only know basic switching—-ramdomized switching give me headache!
    TNX in advance

  83. Taku said,

    August 21, 2012 @ 11:54 pm

    Hey there, very great project. I live in europe and since the color coding is different and can even differ from cable to cable could you please tell us exactly which wire you connected to what pin on the relay and also tell us which color is which on your particular cable. Is it black – liveWire/phases ; green – ground ; white – neutral ???
    And why does the green cable have two different greens with the one more cyan looking?? Shouldn’t the green part be the same color if the cable was spliced ? Why is the black wire twisted together with the green one under the cap ? And on what pin did you connect the black and the green to the relay. I understand most of the stuff but those are the things that confuse me.

    Also if I look at
    I can see 9 cables: 2 black cables going to the relay, 2 green cables going to the relay, 2 green (more cyan looking) cables + 1 black cable under the cap, 2 white cables under a cap,

    So if I’m counting correct thats 9 cables from a spliced wire that had 3 wires before being spliced. So if my math doesn’t trick me 3+3 makes 6. Please explain. Are those the wires that would be going to the arduino ??

    It would be really nice if you could answer my question so I could go on with my project. Thanks a lot.

  84. Interruptor “touch” com Arduino Pro Mini said,

    August 30, 2012 @ 11:15 am

    [...] à parte técnica, usei isso para o relé, só troquei o transistor 2N2222 por um BC548 (tem funcionado bem). E o código, usei o exemplo da [...]

  85. more details said,

    September 14, 2012 @ 1:10 am

    I’m really inspired along with your writing talents as smartly as with the layout on your blog. Is that this a paid subject or did you modify it your self? Either way keep up the excellent high quality writing, it is uncommon to peer a great weblog like this one these days..

  86. J5 said,

    November 8, 2012 @ 4:29 pm

    Great project! what does the diode do in this circuit and why do we need it? Also, what does the transistor do and why do we use it?

  87. Derek Harrington said,

    November 16, 2012 @ 5:31 pm

    Both of these are for using the +5 volts to switch the relay. I think the ouput pins on Arduino are not a full +5V, but there is a constant 5V source on the board. This is not a “pin” though.

    So, Arduino pin 3 goes to the base of the transistor. Activating the base will let current flow through the collector to the emitter side. (top to bottom on the schematic).

    If you look at the 5V source at the top, it is linked to the relay and out the relay down to the transistor. So, there is always 5V at the relay, but the transistor is keeping it from being grounded. Once pin 3 goes high, the transistor opens and the 5V source can run current to ground. Then the relay will be tripped. The 5V has to be able to get to ground.

    The diode only lets current flow one way. If it got to choose it would go the path of least resistance, so it may not go through the relay. The diode forces the current from the 5V source to go through the relay.

  88. dZ. said,

    November 20, 2012 @ 12:54 pm

    quick nice and easy :)

    thank you !

    my 0.1 prototype works like a charm on an arduino ethernet connected to a cheap wifi router.
    0.2 will use v usb to connect a classic arduino to the router through usb, next will use a ATtiny84 in place of the arduino :) )

    see ya !

  89. Brad said,

    November 29, 2012 @ 3:13 pm

    HAHAHA yes!!
    thank you so much! its very simple, and straight forward. Up until now i have been making manual switches from motors that physically turn the dial or switch on anything that was 120v. That was taking a very long time, and using all my motors to turn the on / off switches. I kept thinking there has got to be a better way! Obviously i am new to this..but you made it so easy… A relay hunh? what a beautiful thing.

  90. jek said,

    December 28, 2012 @ 4:25 pm

    how about adding physical switch of the bulb..because it is essential to have a hardware part switch not only in the arduino. Does anybody can make it?

  91. Pedro said,

    February 20, 2013 @ 8:14 pm

    Hello! I’m just not understanding correctly the term “plug into the wall”… ou mean like a connecting the wires into a normal 220v/50hz jack that is on the wall? (I’m from europe)

    if it’s not this can someone clarify me a litle bit better this concept? thank you!

  92. Greg LeBreton said,

    February 25, 2013 @ 9:48 pm

    Any idea why this would give a huge voltage spike through A1 when the relay shuts down?
    Any idea how to avoid that?
    Nice and simple circuit though.

  93. NoxAsch said,

    June 28, 2013 @ 12:08 am

    Hello, Sir/Mr can I know how to add more appliances for this circuit ? and can you please email a circuit diagram for the relay circuit for more than 2 appliances, and it will be helpful if you can explain about the circuit and how the circuit work. Thanks ! Great project !

  94. Phil said,

    July 13, 2013 @ 3:40 pm

    @Greg LeBreton – voltage spike is likely caused by the relay. When power first starts to flow through the relay, energy builds up inside the coil & metallic structure which the coil is wound around. When this energy builds up high enough, this is what pulls the switch closed inside the relay. When power to a relay is then cut off, the stored energy is no longer being held in place and it will generate a reverse voltage as it discharges back into the circuitry connected to the relay’s coil. The purpose of the diode is to short out this voltage spike before it can do any damage to anything else in the circuit. A collapsing magnetic field can transition faster than a field being built-upwards, so it can actually make more voltage in collapse than whatever voltage level you used to build the field! The diode is oriented in circuit so that when the 2N2222 is sinking the relay to ground, the positive 5 volts will not be able to flow through the diode and will instead flow through the relay’s coil, otherwise the relay will not work and I might worry about too much current being pulled from that 5 volt source! I would recommend double-checking that the diode is in the right way before powering this off of the arduino’s built in 5 volt supply.

RSS feed for comments on this post