Guide for Relay Module with Arduino

This article shows how to control mains voltage with the Arduino using a relay module. We make a brief introduction to the relay module and build a simple project example with the Arduino. The example we’ll build shows how to control a relay module with an Arduino and a PIR motion sensor.

By the end of this tutorial, you should be able to control any electronics appliances with your Arduino using a relay module.

Introducing the Relay Module

A relay is an electrically operated switch that can be turned on or off, letting the current go through or not, and can be controlled with low voltages, like the 5V provided by the Arduino pins.

Controlling a relay module with the Arduino is as simple as controlling any other output as we’ll see later on.

relay-module

This relay module has two channels (those blue cubes). There are other models with one, four and eight channels. This module should be powered with 5V, which is appropriate to use with an Arduino. There are other relay modules that are powered using 3.3V, which is ideal for ESP32, ESP8266, and other microcontrollers.

Get a relay module:

Relay Pinout

The following figure shows the relay module pinout.

The six pins on the left side of the relay module connect high voltage, and the pins on the right side connect the component that requires low voltage—the Arduino pins.

Mains voltage connections

The high-voltage side has two connectors, each with three sockets: common (COM), normally closed (NC), and normally open (NO).

relay-labeled

  • COM: common pin
  • NC (Normally Closed): the normally closed configuration is used when you want the relay to be closed by default, meaning the current is flowing unless you send a signal from the Arduino to the relay module to open the circuit and stop the current.
  • NO (Normally Open): the normally open configuration works the other way around: the relay is always open, so the circuit is broken unless you send a signal from the Arduino to close the circuit.

If you just want to light up a lamp occasionally, it is better to use a normally-open circuit configuration.

Pin wiring

The low-voltage side has a set of four pins and a set of three pins.

img_6361

The set at the right consists of VCC and GND to power up the module, and input 1 (IN1) and input 2 (IN2) to control the bottom and top relays, respectively.

The second set of pins consists of GND, VCC, and JD-VCC pins. The JD-VCC pin powers the electromagnet of the relay.

Note: notice that the module has a jumper cap connecting the VCC and JD-VCC pins; the one shown here is blue, but yours may be a different color. The jumper cap allows you to choose whether the circuit is physically connected to the Arduino circuit or not, and you can choose to have it on or not. With the jumper cap on, the VCC and JD-VCC pins are connected. That means the relay electromagnet is directly powered from the Arduino’s power pin, so the relay module and the Arduino circuits are not physically isolated from each other (this is the configuration we’ll use). Without the jumper cap, you need to provide an independent power source to power up the relay’s electromagnet through the JD-VCC pin. That configuration physically isolates the relays from the Arduino with the module’s built-in optocoupler.

The connections between the relay module and the Arduino are really simple:

  • GND: goes to ground
  • IN1: controls the first relay (it will be connected to an Arduino digital pin)
  • IN2: controls the second relay (it should be connected to an Arduino digital pin if you are using this second relay. Otherwise, you don’t need to connect it)
  • VCC: goes to 5V

Example: Controlling a Lamp with a Relay Module and PIR Motion Sensor

dsc09897

In this example, we create a motion sensitive lamp. A lamp lights up for 10 seconds every time motion is detected.

Motion will be detected using a PIR motion sensor. If you are not familiar with the PIR motion sensor, you can read the following post:

To control the lamp with mains voltage we’ll use a relay module in normally-open configuration.

Safety warning

Before proceeding with this project, I want to let you know that you’re dealing with mains voltage. Please read the safety warning below carefully.

Warning: when you are making projects that are connected to mains voltage, you really need to know what you are doing, otherwise you may shock yourself. This is a serious topic, and we want you to be safe. If you’re not 100% sure what you are doing, do yourself a favor and don’t touch anything. Ask someone who knows!

Parts required

Here’s the needed parts for this example:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Code

Copy the following code to your Arduino IDE and upload it to your Arduino board.

Warning: you shouldn’t upload new code while your Arduino is connected to the relay.

/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/

// Relay pin is controlled with D8. The active wire is connected to Normally Closed and common
int relay = 8;
volatile byte relayState = LOW;

// PIR Motion Sensor is connected to D2.
int PIRInterrupt = 2;

// Timer Variables
long lastDebounceTime = 0;  
long debounceDelay = 10000;

void setup() {
  // Pin for relay module set as output
  pinMode(relay, OUTPUT);
  digitalWrite(relay, HIGH);
  // PIR motion sensor set as an input
  pinMode(PIRInterrupt, INPUT);
  // Triggers detectMotion function on rising mode to turn the relay on, if the condition is met
  attachInterrupt(digitalPinToInterrupt(PIRInterrupt), detectMotion, RISING);
  // Serial communication for debugging purposes
  Serial.begin(9600);
}

void loop() {
  // If 10 seconds have passed, the relay is turned off
  if((millis() - lastDebounceTime) > debounceDelay && relayState == HIGH){
    digitalWrite(relay, HIGH);
    relayState = LOW;
    Serial.println("OFF");
  }
  delay(50);
}

void detectMotion() {
  Serial.println("Motion");
  if(relayState == LOW){
    digitalWrite(relay, LOW);
  }
  relayState = HIGH;  
  Serial.println("ON");
  lastDebounceTime = millis();
}

View raw code

How the code works

First, we create variables to hold the pin the relay IN1 pin is connected to and to save the relay state:

int relay = 8;
volatile byte relayState = LOW;

The PIR motion sensor is connected to pin 2:

int PIRInterrupt = 2;

We need to create some auxiliary variables to handle timers with the PIR motion sensor. The lastDebounceTime variable saves the last time motion was detected. The debounceDelay saves how much time the lamp should remain on after motion is detected (here we’re setting 10 seconds = 10000 milliseconds)

long lastDebounceTime = 0;
long debounceDelay = 10000;

In the setup(), we set the relay as an OUTPUT and turn it off by default:

pinMode(relay, OUTPUT);
digitalWrite(relay, HIGH);

Because we’re using a normally open configuration, there is no contact between the COM and NO sockets unless you trigger the relay. The relay is triggered when the input goes below about 2 V. That means if you send a LOW signal from the Arduino, the relay turns on, and if you send a HIGH signal, the relay turns off;  it works with inverted logic.

Set the PIR motion sensor as an interrupt:

pinMode(PIRInterrupt, INPUT);
// Triggers detectMotion function on rising mode to turn the relay on, if the condition is met
attachInterrupt(digitalPinToInterrupt(PIRInterrupt), detectMotion, RISING);

Whenever the PIR motion sensor is triggered, it calls the detectMotion() function declared at the end of the code to turn the relay on:

void detectMotion() {
    Serial.println("Motion");
    if(relayState == LOW){
        digitalWrite(relay, LOW);
    }
    relayState = HIGH;
    Serial.println("ON");
    lastDebounceTime = millis();
}

In the loop(), we check whether 10 seconds have passed since the relay is on. If that condition is true, we can turn the relay off.

if((millis() - lastDebounceTime) > debounceDelay && relayState == HIGH){
    digitalWrite(relay, HIGH);
    relayState = LOW;
    Serial.println("OFF");
}

Schematic

Assemble all the parts as shown in the schematic diagram.

Warning: do not touch any wires that are connected to mains voltage. Also make sure you have tighten all screws of the relay module.

schematics

The lamp is connected to the relay using a normally open configuration. The Arduino controls the relay through pin 8 (pin 8 is connected to the relay IN1 pin). Finally, the PIR motion sensor is connected to pin 2.

Demonstration

After uploading the code and wiring the circuit, you can test your setup.

When motion is detected, your lamp lights up. If there isn’t motion for 10 seconds, the lamp turns off.

relay-module-gif

Wrapping Up

Controlling a relay module with the Arduino is as simple as controlling an output – you just need to send HIGH or LOW signals using an Arduino digital pin. With the relay module you can control almost any AC electronics appliances (not just lamps).

We hope you’ve found this guide useful. If you like this project, you may also like our premium Arduino course:

We have more than 60 free tutorials and projects with the Arduino. If you’re looking for a guide for a specific module, we probably have what you’re looking for.

Finally, you can also get access to our FREE resources here.

Thanks for reading.

January 15, 2019



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

57 thoughts on “Guide for Relay Module with Arduino”

  1. Oi Rui!
    Tenho acompanhado e lido as suas interessantes e excelentes postagens; Aproveitando o ensejo, gostaria de lhe pedir/sugerir para fazer algum projeto que use módulo GPS como esse, por exemplo, Ublox GY-NEO6MV2 GPS Module; Obrigado

    Reply
      • Any way we can omit the use of another 5V power adapter? Because doing so will waste sockets. Can we, say, draw the power from the same wire that powers the light, and feed that same mains power into Arduino (with a bit of circuits to drop the power to 5V before feeding to Arduino)?

        Reply
  2. If people aren’t comfortable working with mains voltage, a good procedure is to get an inexpensive wireless-remote plug module (can be gotten at Ebay and in big box stores) and use the relay to bridge the contacts in the battery powered remote. One relay for “on”, the other for “off”.

    That way the maker doesn’t handle high voltage and it’s much safer even if it adds a little expense.

    Reply
      • One thing I found with my relay board was that some of the contacts on the back of the board run at 240v (I had made the somewhat silly assumption that the only bits I had to worry about not touching were the 240v terminals, and grabbed the back without even thinking about it, fortunately with one dry dry hand.

        Reply
  3. hi, I think that this can be done directly, without using arduino, with just a relay, a PIR and an LDR… take a look here and tell what do you think 🙂

    youtube.com/watch?v=2dxhbXHYEG0

    Reply
  4. Hi, I’m enjoying your tutorials, they are well documented, relevant and very easy to follow.

    Would love to see you write a tutorial demonstrating how to use more than 1 different type of sensor at a time, for example a distance sensor and say a tilt sensor that could be combined for use on a wheeled robot that could detect objects in front as well as if it has been picked up or knocked over.

    Thanks again for your educational tutorials.

    Andrew

    Reply
  5. I have made many of these without an Arduino, but I guess the lesson here is how to control a relay with the Arduino. OK, I get it …

    Reply
  6. Did you simulate the circuit first on a computer program like Proteus? I tried to simulate the circuit in this project with Proteus but when I ran it, the light was always on regardless whether I changed the PIR sensor logic from 0 to 1. Though I didn’t have a relay module library so I made the module from diode and transistor instead.

    Reply
    • Hi.
      We haven’t tested this on Proteus. So, I don’t know the reason for that strange behavior.
      If you’re using an LED instead of a relay, you need to keep in mind that the relay works with inverted logic.
      This means you send a LOW to turn it on, and a HIGH to turn it off.
      I hope this helps.

      Reply
  7. No pull up/down resistors are shown on the relay board inputs? I am planning to use an ESP8266 and this is 3.3v not 5v as the relay board is, should I being using a voltage convertor?

    Reply
    • Hi Chris.
      To power the relay module you need to supply 5V in the Vin pin (of the relay board).
      To control the relay, you can send a 3.3V or 5V signal to the In1 or In2 pins.
      I hope this helps.
      Regards,
      Sara 🙂

      Reply
  8. May i know how come the subfunction detectmotion() was not included in the loop() function still the project progress as if detectmotion() keeps looping? Thks 🙂

    Reply
    • Hi.
      That happens because we create an interrupt in the setup():
      attachInterrupt(digitalPinToInterrupt(PIRInterrupt), detectMotion, RISING);
      This line means that when an interrupt is detected in RISING mode in the PIRInterrupt pin (digital pin 2), the detectMotion() function is called.
      RISING mode simply means that the function will be triggered when the pin goes from LOW to HIGH (this means when motion is detected).
      Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems.
      I hope this helps.
      Regards,
      Sara 🙂

      Reply
  9. Thank you for the tutorial! It’s very clear and concise.

    I’m building a similar project but with a Strobe Siren connected instead of a lamp.

    I have a question though. Would the 1-Channel 5V relay do the trick as well since it’s just one external device being connected? My observation is that you only need as many relays as devices you wish to control with your Arduino. Am I right?

    Reply
    • Hi.
      Raymond.
      Yes, you are right.
      You can use a 1-channel relay module if you just want to control an output.
      Regards,
      Sara

      Reply
  10. Great project, very useful!

    It would be possible to keep the lamp turned on for a larger period of time, like 5-10 minutes, without damaging the relay or the arduino board?

    Thanks 😀

    Reply
  11. Hi,
    When i attempt to run this code, I get an error with the line
    attachInterrupt(digitalPinToInterrupt(PIRInterrupt), detectMotion, RISING);
    the error says that there is an undeclared identifier. Do you have any idea what this means?

    Thank you

    Reply
  12. Thanks for this guys, really appreciated 🙂
    One doubt, when you warn about “upload new code while your Arduino is connected to the relay”, do you mean the 5v connection or the high voltage connection?

    Reply
  13. when dealing with mains, it is ALWAYS recommended and much cleaner to use the relay board in OPTO-ISOLATED made. You should really have done this in this demo.

    Reply
    • From what I can tell, the relay board has optocouplers on it and there is no connection that circumvents those. Therefore I don’t know what you are talking about.

      Reply
    • Can you go a little more into why this is a good idea please? I built an arduino and an array to control garden watering cycles (so I can do it or not based on the weather forecast) and sometimes it seems like the arduino resets when it flips the relay. Would opto-isolation be likely to stop this happening (if so, I guess I need to use another power supply to go to the relay?

      Reply
  14. this was really helpful on showing how to use a relay with Arduino. It helped me understand the code and how to connect it

    Reply
  15. Nice Tutorial, much easier to read than forums or Q and A sites!

    I thought you may want to add in your box about Jd-vcc , that most of the generic boards are not idiot-proof because the GND and VCC are right next to each other so make sure you put that jumper in the right place!

    Why didn’t they swap the order of the pins to GND, JD-VCC, VCC or just a gap? Oh well…

    Reply
  16. Hi everyone, I don-t know if you-ve expirience this issue with this modules where an ondulating mains voltage remains between the central point of the relay and the NO contact. This voltage may faintly power on some aparatus and I don-t understand why this voltage remains
    electronics.stackexchange.com/questions/523364/relay-contact-insulation-doesnt-seem-to-be-enough

    Reply
  17. Hi! Excellent tutorial! Thank you! Just one question. Sometimes the relay stays turning on like a loop and does not stop. Do you know why this happens? I just changed the delay to 2000. Thank you! Kind regards!

    Reply
      • Hi! When I pass in front of the sensor the relay turns on. And then when I get far from the sensor range the the relays turns off. But sometimes, not always, the relay does not turn off when I get far from the sensor range, instead it keeps turning on and off sometimes 2, 3, 4 times. Sometimes It does not stop, just when I get close to the sensor again. I changed the code in: long debounceDelay = 10000; to 2000 (2 seconds).
        The rest of the code is the same.
        Could it be because of that? Or what could it be?
        Thanks for answering! Kind regards!

        Reply
  18. Hi Sara
    I want to do something similar but using a dual coil relay to switch 12 volt dc.
    Is there a sketch to suit a dual coil relay ?
    Can the code be modified to suit. It is just the dual coil bit that I need to know about.
    Thanks

    Reply
  19. Hi,
    Interesting project. I need a help from you regarding the following;
    Instead of PIR sensor I need to send a signal to Arduino via PC serial/COM port using jQuery script to activate the light. Can you help me for this? Many thanks.

    Reply
  20. made an clap switch using an arduino uno and 5v relay sigle channel but the relay channel is not working with 9 volt batteries although my light is also 9v but its not working.. can you please tell me how to solve it

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.