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.

94 Comments

  1. 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 […]

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

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

  4. Raphael Cerqueira said,

    October 17, 2010 @ 10:46 pm

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

    http://arduitter.blogspot.com/2010/10/rf-links-reliable-messaging.html

  5. newbie said,

    April 30, 2011 @ 2:14 pm

    Hello!

    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…

  6. Rian said,

    October 5, 2011 @ 2:30 am

    Hi,

    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.

    Thanks,

    Rian

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

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

  9. Rian said,

    October 8, 2011 @ 3:05 am

    Ignore the above I worked it out.

  10. kardamyla said,

    October 8, 2011 @ 2:29 pm

    Hi,
    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 http://search.digikey.com/scripts/DkSearch/dksus.dll?Detail&itemSeq=105585863&uq=634536768231996536&DPU=submit
    This is the manual for the Axis 207 207W camera http://www.axis.com/files/manuals/um_207w_mw_33158_en_1208.pdf. 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

  11. 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 http://digikey.com as they have a large variety of relays.

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

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

  13. kardamyla said,

    October 8, 2011 @ 2:37 pm

    Sorry this is the link http://www.ibou.fr/cameras/cameras.html

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

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

  16. fabienne said,

    November 21, 2011 @ 3:18 am

    Nevermind!

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

  17. Saw0 said,

    November 29, 2011 @ 9:57 pm

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

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

  19. 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
    }
    delay(250);
    // debounce
    }
    }

    Give that a try?

    R//Chez

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

    David

    //Blink_Randomly

    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
    }

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

    D

  22. Light controller | Jeff's projects said,

    January 15, 2012 @ 5:24 pm

    […] control circuit, not the sensing circuit, was based on http://www.glacialwanderer.com/hobbyrobotics/?p=9.  The difference between my version and his is that I thought the transistor was unnecessary, so I […]

  23. 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 […]

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

    February 15, 2012 @ 11:37 pm

    […] http://www.glacialwanderer.com/hobbyrobotics/?p=9 […]

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

    Tim

  26. 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 […]

  27. 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 http://www.glacialwanderer.com/hobbyrobotics/?p=9 (2) Plenty of OTC temp, and humidity sensors to choose from. Soil moisture should just be a […]

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

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

  30. 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 […]

  31. 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 […]

  32. 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
    Condition1:
    Ardruino will turn on the relay (let say PIN 13) stand alone, without communicating with the computer.
    Condition2:
    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

  33. 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 http://www.glacialwanderer.com/_blog/blog2008/04_April/hb_relay1.jpg
    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.

  34. 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 […]

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

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

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

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

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

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

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

  42. Greg LeBreton said,

    February 25, 2013 @ 9:48 pm

    Hi,
    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.
    Cheers.

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

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