ESP32 Relay Module - Control AC Appliances (Web Server) | Random Nerd Tutorials (2024)

Using a relay with the ESP32 is a great way to control AC household appliances remotely. This tutorial explains how to control a relay module with the ESP32. We’ll take a look at how a relay module works, how to connect the relay to the ESP32 and build a web server to control a relay remotely (or as many relays as you want).

ESP32 Relay Module - Control AC Appliances (Web Server) | Random Nerd Tutorials (1)

Learn how to control a relay module with ESP8266 board: Guide for ESP8266 Relay Module – Control AC Appliances + Web Server Example.

Watch the Video Tutorial

Watch the following video tutorial or keep reading this page for the written instructions and all the resources.

Introducing Relays

A relay is an electrically operated switch and like any other switch, it that can be turned on or off, letting the current go through or not. It can be controlled with low voltages, like the 3.3V provided by the ESP32 GPIOs and allows us to control high voltages like 12V, 24V or mains voltage (230V in Europe and 120V in the US).

1, 2, 4, 8, 16 Channels Relay Modules

There are different relay modules with a different number of channels. You can find relay modules with one, two, four, eight and even sixteen channels. The number of channels determines the number of outputs we’ll be able to control.

ESP32 Relay Module - Control AC Appliances (Web Server) | Random Nerd Tutorials (2)

There are relay modules whose electromagnet can be powered by 5V and with 3.3V. Both can be used with the ESP32 – you can either use the VIN pin (that provides 5V) or the 3.3V pin.

Additionally, some come with built-in optocoupler that add an extra “layer” of protection, optically isolating the ESP32 from the relay circuit.

Get a relay module:

Relay Pinout

For demonstration purposes, let’s take a look at the pinout of a 2-channel relay module. Using a relay module with a different number of channels is similar.

ESP32 Relay Module - Control AC Appliances (Web Server) | Random Nerd Tutorials (3)

On the left side, there are two sets of three sockets to connect high voltages, and the pins on the right side (low-voltage) connect to the ESP32 GPIOs.

Mains Voltage Connections

ESP32 Relay Module - Control AC Appliances (Web Server) | Random Nerd Tutorials (4)

The relay module shown in the previous photo has two connectors, each with three sockets: common (COM), Normally Closed (NC), and Normally Open (NO).

  • COM:connect the current you want to control (mains voltage).
  • NC(Normally Closed):the normally closed configuration is used when you want the relay to be closed by default. The NC are COM pins are connected, meaning the current is flowing unless you send a signal from the ESP32 to the relay module to open the circuit and stop the current flow.
  • NO(Normally Open):the normally open configuration works the other way around: there is no connection between the NO and COM pins, so the circuit is broken unless you send a signal from the ESP32 to close the circuit.

Control Pins

ESP32 Relay Module - Control AC Appliances (Web Server) | Random Nerd Tutorials (5)

The low-voltage side has a set of four pins and a set of three pins. The first set 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.

If your relay module only has one channel, you’ll have just one IN pin. If you have four channels, you’ll have four IN pins, and so on.

The signal you send to the IN pins, determines whether the relay is active or not. The relay is triggered when the input goes below about 2V. This means that you’ll have the following scenarios:

  • Normally Closed configuration (NC):
    • HIGH signal – current is flowing
    • LOW signal – current is not flowing
  • Normally Open configuration (NO):
    • HIGH signal – current is not flowing
    • LOW signal – current in flowing

You should use a normally closed configuration when the current should be flowing most of the times, and you only want to stop it occasionally.

Use a normally open configuration when you want the current to flow occasionally (for example, turn on a lamp occasionally).

Power Supply Selection

ESP32 Relay Module - Control AC Appliances (Web Server) | Random Nerd Tutorials (6)

The second set of pins consists of GND, VCC, and JD-VCC pins. The JD-VCC pin powers the electromagnet of the relay. Notice that the module has a jumper cap connecting the VCC and JD-VCC pins; the one shown here is yellow, but yours may be a different color.

With the jumper cap on, the VCC and JD-VCC pins are connected. That means the relay electromagnet is directly powered from the ESP32 power pin, so the relay module and the ESP32 circuits are not physically isolated from each other.

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 ESP32 with the module’s built-in optocoupler, which prevents damage to the ESP32 in case of electrical spikes.

Wiring a Relay Module to the ESP32

Connect the relay module to the ESP32 as shown in the following diagram. The diagram shows wiring for a 2-channel relay module, wiring a different number of channels is similar.

Warning: in this example, we’re dealing with mains voltage. Misuse can result in serious injuries. If you’re not familiar with mains voltage ask someone who is to help you out. While programming the ESP or wiring your circuit make sure everything is disconnected from mains voltage.

Alternatively, you can use a 12V power source to control 12V appliances.

In this example, we’re controlling a lamp. We just want to light up the lamp occasionally, so it is better to use a normally open configuration.

We’re connecting the IN1 pin to GPIO 26, you can use any other suitable GPIO. See ESP32 GPIO Reference Guide.

Controlling a Relay Module with the ESP32 – Arduino Sketch

The code to control a relay with the ESP32 is as simple as controlling an LED or any other output. In this example, as we’re using a normally open configuration, we need to send a LOW signal to let the current flow, and a HIGH signal to stop the current flow.

ESP32 Relay Module - Control AC Appliances (Web Server) | Random Nerd Tutorials (8)

The following code will light up your lamp for 10 seconds and turn it off for another 10 seconds.

/********* Rui Santos Complete project details at https://RandomNerdTutorials.com/esp32-relay-module-ac-web-server/ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.*********/const int relay = 26;void setup() { Serial.begin(115200); pinMode(relay, OUTPUT);}void loop() { // Normally Open configuration, send LOW signal to let current flow // (if you're usong Normally Closed configuration send HIGH signal) digitalWrite(relay, LOW); Serial.println("Current Flowing"); delay(5000); // Normally Open configuration, send HIGH signal stop current flow // (if you're usong Normally Closed configuration send LOW signal) digitalWrite(relay, HIGH); Serial.println("Current not Flowing"); delay(5000);}

View raw code

How the Code Works

Define the pin the relay IN pin is connected to.

const int relay = 26;

In the setup(), define the relay as an output.

pinMode(relay, OUTPUT);

In the loop(), send a LOW signal to let the current flow and light up the lamp.

digitalWrite(relay, LOW);

If you’re using a normally closed configuration, send a HIGH signal to light up the lamp. Then, wait 5 seconds.

delay(5000);

Stop the current flow by sending a HIGH signal to the relay pin. If you’re using a normally closed configuration, send a LOW signal to stop the current flow.

digitalWrite(relay, HIGH);

Control Multiple Relays with ESP32 Web Server

ESP32 Relay Module - Control AC Appliances (Web Server) | Random Nerd Tutorials (9)

In this section, we’ve created a web server example that allows you to control as many relays as you want via web server whether they are configured as normally opened or as normally closed. You just need to change a few lines of code to define the number of relays you want to control and the pin assignment.

To build this web server, we use the ESPAsyncWebServer library.

Installing the ESPAsyncWebServer library

Follow the next steps to install theESPAsyncWebServerlibrary:

  1. Click here to downloadthe ESPAsyncWebServer library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should getESPAsyncWebServer-masterfolder
  3. Rename your folder fromESPAsyncWebServer-mastertoESPAsyncWebServer
  4. Move theESPAsyncWebServerfolder to your Arduino IDE installation libraries folder

Alternatively, in your Arduino IDE, you can go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded.

Installing theAsync TCP Library for ESP32

TheESPAsyncWebServerlibrary requires theAsyncTCPlibrary to work. Follow the next steps to install that library:

  1. Click here to download the AsyncTCP library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should getAsyncTCP-masterfolder
  3. Rename your folder fromAsyncTCP-mastertoAsyncTCP
  4. Move theAsyncTCPfolder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Alternatively, in your Arduino IDE, you can go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded.

After installing the required libraries, copy the following code to your Arduino IDE.

/********* Rui Santos Complete project details at https://RandomNerdTutorials.com/esp32-relay-module-ac-web-server/ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.*********/// Import required libraries#include "WiFi.h"#include "ESPAsyncWebServer.h"// Set to true to define Relay as Normally Open (NO)#define RELAY_NO true// Set number of relays#define NUM_RELAYS 5// Assign each GPIO to a relayint relayGPIOs[NUM_RELAYS] = {2, 26, 27, 25, 33};// Replace with your network credentialsconst char* ssid = "REPLACE_WITH_YOUR_SSID";const char* password = "REPLACE_WITH_YOUR_PASSWORD";const char* PARAM_INPUT_1 = "relay"; const char* PARAM_INPUT_2 = "state";// Create AsyncWebServer object on port 80AsyncWebServer server(80);const char index_html[] PROGMEM = R"rawliteral(<!DOCTYPE HTML><html><head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> html {font-family: Arial; display: inline-block; text-align: center;} h2 {font-size: 3.0rem;} p {font-size: 3.0rem;} body {max-width: 600px; margin:0px auto; padding-bottom: 25px;} .switch {position: relative; display: inline-block; width: 120px; height: 68px} .switch input {display: none} .slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; border-radius: 34px} .slider:before {position: absolute; content: ""; height: 52px; width: 52px; left: 8px; bottom: 8px; background-color: #fff; -webkit-transition: .4s; transition: .4s; border-radius: 68px} input:checked+.slider {background-color: #2196F3} input:checked+.slider:before {-webkit-transform: translateX(52px); -ms-transform: translateX(52px); transform: translateX(52px)} </style></head><body> <h2>ESP Web Server</h2> %BUTTONPLACEHOLDER%<script>function toggleCheckbox(element) { var xhr = new XMLHttpRequest(); if(element.checked){ xhr.open("GET", "/update?relay="+element.id+"&state=1", true); } else { xhr.open("GET", "/update?relay="+element.id+"&state=0", true); } xhr.send();}</script></body></html>)rawliteral";// Replaces placeholder with button section in your web pageString processor(const String& var){ //Serial.println(var); if(var == "BUTTONPLACEHOLDER"){ String buttons =""; for(int i=1; i<=NUM_RELAYS; i++){ String relayStateValue = relayState(i); buttons+= "<h4>Relay #" + String(i) + " - GPIO " + relayGPIOs[i-1] + "</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"" + String(i) + "\" "+ relayStateValue +"><span class=\"slider\"></span></label>"; } return buttons; } return String();}String relayState(int numRelay){ if(RELAY_NO){ if(digitalRead(relayGPIOs[numRelay-1])){ return ""; } else { return "checked"; } } else { if(digitalRead(relayGPIOs[numRelay-1])){ return "checked"; } else { return ""; } } return "";}void setup(){ // Serial port for debugging purposes Serial.begin(115200); // Set all relays to off when the program starts - if set to Normally Open (NO), the relay is off when you set the relay to HIGH for(int i=1; i<=NUM_RELAYS; i++){ pinMode(relayGPIOs[i-1], OUTPUT); if(RELAY_NO){ digitalWrite(relayGPIOs[i-1], HIGH); } else{ digitalWrite(relayGPIOs[i-1], LOW); } } // Connect to Wi-Fi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } // Print ESP32 Local IP Address Serial.println(WiFi.localIP()); // Route for root / web page server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/html", index_html, processor); }); // Send a GET request to <ESP_IP>/update?relay=<inputMessage>&state=<inputMessage2> server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) { String inputMessage; String inputParam; String inputMessage2; String inputParam2; // GET input1 value on <ESP_IP>/update?relay=<inputMessage> if (request->hasParam(PARAM_INPUT_1) & request->hasParam(PARAM_INPUT_2)) { inputMessage = request->getParam(PARAM_INPUT_1)->value(); inputParam = PARAM_INPUT_1; inputMessage2 = request->getParam(PARAM_INPUT_2)->value(); inputParam2 = PARAM_INPUT_2; if(RELAY_NO){ Serial.print("NO "); digitalWrite(relayGPIOs[inputMessage.toInt()-1], !inputMessage2.toInt()); } else{ Serial.print("NC "); digitalWrite(relayGPIOs[inputMessage.toInt()-1], inputMessage2.toInt()); } } else { inputMessage = "No message sent"; inputParam = "none"; } Serial.println(inputMessage + inputMessage2); request->send(200, "text/plain", "OK"); }); // Start server server.begin();} void loop() {}

View raw code

Define Relay Configuration

Modify the following variable to indicate whether you’re using your relays in normally open (NO) or normally closed (NC) configuration. Set the RELAY_NO variable to true for normally open os set to false for normally closed.

#define RELAY_NO true

Define Number of Relays (Channels)

You can define the number of relays you want to control on the NUM_RELAYS variable. For demonstration purposes, we’re setting it to 5.

#define NUM_RELAYS 5

Define Relays Pin Assignment

In the following array variable you can define the ESP32 GPIOs that will control the relays:

int relayGPIOs[NUM_RELAYS] = {2, 26, 27, 25, 33};

The number of relays set on the NUM_RELAYS variable needs to match the number of GPIOs assigned in the relayGPIOs array.

Network Credentials

Insert your network credentials in the following variables.

const char* ssid = "REPLACE_WITH_YOUR_SSID";const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Wiring 8 Channel Relay to ESP32

For demonstration purposes, we’re controlling 5 relay channels. Wire the ESP32 to the relay module as shown in the next schematic diagram.

Demonstration

After making the necessary changes, upload the code to your ESP32.

Open the Serial Monitor at a baud rate of 115200 and press the ESP32 EN button to get its IP address.

Then, open a browser in your local network and type the ESP32 IP address to get access to the web server.

You should get something as follows with as many buttons as the number of relays you’ve defined in your code.

ESP32 Relay Module - Control AC Appliances (Web Server) | Random Nerd Tutorials (11)

Now, you can use the buttons to control your relays remotely using your smartphone.

Enclosure for Safety

For a final project, make sure you place your relay module and ESP inside an enclosure to avoid any AC pins exposed.

ESP32 Relay Module - Control AC Appliances (Web Server) | Random Nerd Tutorials (12)

Wrapping Up

Using relays with the ESP32 is a great way to control AC household appliances remotely. You can also read our other Guide to control a Relay Module with ESP8266.

Controlling a relay with the ESP32 is as easy controlling any other output, you just need to send HIGH and LOW signals as you would do to control an LED.

You can use our web server examples that control outputs to control relays. You just need to pay attention to the configuration you’re using. In case you’re using a normally open configuration, the relay works with inverted logic. You can use the following web server examples to control your relay:

  • ESP32 Web Server – Arduino IDE
  • ESP32 Web Server using SPIFFS (control outputs)
  • ESP32/ESP8266 MicroPython Web Server – Control Outputs

Learn more about the ESP32 with our resources:

  • Learn ESP32 with Arduino IDE (Video course + eBook)
  • MicroPython Programming with the ESP32 and ESP8266
  • More ESP32 resources…

Thanks for reading.

ESP32 Relay Module - Control AC Appliances (Web Server) | Random Nerd Tutorials (2024)
Top Articles
Latest Posts
Article information

Author: Virgilio Hermann JD

Last Updated:

Views: 6365

Rating: 4 / 5 (41 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Virgilio Hermann JD

Birthday: 1997-12-21

Address: 6946 Schoen Cove, Sipesshire, MO 55944

Phone: +3763365785260

Job: Accounting Engineer

Hobby: Web surfing, Rafting, Dowsing, Stand-up comedy, Ghost hunting, Swimming, Amateur radio

Introduction: My name is Virgilio Hermann JD, I am a fine, gifted, beautiful, encouraging, kind, talented, zealous person who loves writing and wants to share my knowledge and understanding with you.