
in this tutorial we will build 4 channel relay module webserver control with esp32.
A 4-channel relay module is an electronic device designed to control up to four separate electrical circuits using a low-voltage microcontroller or digital signal.
Component You Need:
Features of 4 Channel Relay Module:
The features of a 4-channel relay module can vary depending on the specific model and manufacturer, but here are some common features you might find:
Number of Channels:
- The module typically provides four independent relay channels, allowing you to control four separate electrical circuits.
Input Voltage:
- The relay module is designed to be controlled by a low-voltage input, often 5V or 3.3V. This input voltage is usually provided by a microcontroller or a digital signal source.
Output Voltage:
- The relay contacts can handle higher voltages, commonly up to 250V AC or 30V DC. This allows you to control devices with higher operating voltages.
Current Rating:
- Each relay has a specified maximum current it can switch. Common current ratings are 10A or 30A, indicating the maximum current that can flow through the relay contacts.
Control Pins:
- The module has input pins (such as IN1, IN2, IN3, IN4) for each relay channel. These pins connect to the control signals from a microcontroller or another digital device.
Common Ground and Power Pins:
- There are typically common ground (GND) and power (VCC) pins for the control circuit. The VCC pin is used to power the module.
LED Indicators:
- Many relay modules include LED indicators for each channel, providing a visual indication of the relay's state (whether it's energized or not).
Opto-Isolation:
- Some relay modules feature opto-isolation, where the input and output circuits are electrically isolated. This helps protect the controlling device from potential voltage spikes or noise in the controlled circuit.
High-Level Trigger/Low-Level Trigger:
- The module may support high-level trigger or low-level trigger inputs, allowing compatibility with different microcontroller systems.
Screw Terminals:
- Some relay modules have screw terminals for easy and secure connection of wires to the relay contacts.
Compact Design:
- Relay modules are typically designed to be compact, making them suitable for integration into various electronic projects and applications.
When using a 4-channel relay module, it's essential to refer to the datasheet provided by the manufacturer for detailed specifications, usage guidelines, and safety considerations. This will ensure proper and safe integration into your projects.
Shematics

Program:
// 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 4
// Assign each GPIO to a relay
int relayGPIOs[NUM_RELAYS] = {5, 18, 19, 21};
// Replace with your network credentials
const char* ssid = "ssid";
const char* password = "password";
const char* PARAM_INPUT_1 = "relay";
const char* PARAM_INPUT_VOICE = "command";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
//The Html Code
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><i class="fa fa-plug"></i> ESP32 4-Channel Relay Control</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
<style>
body {
font-family: 'Arial', sans-serif;
background-color: #f4f4f4;
text-align: center;
margin: 20px;
}
h2 {
color: #333;
}
.relayButton {
padding: 15px;
font-size: 18px;
margin: 10px;
cursor: pointer;
width: 200px;
border: 2px solid #3498db;
background-color: #3498db;
color: white;
border-radius: 8px;
outline: none;
transition: background-color 0.3s ease;
}
.relayButton:hover {
background-color: #2980b9;
}
.on {
background-color: #27ae60;
border: 2px solid #27ae60;
}
.toggleButton {
padding: 15px;
font-size: 18px;
margin: 10px;
cursor: pointer;
width: 200px;
border: 2px solid #e74c3c;
background-color: #e74c3c;
color: white;
border-radius: 8px;
outline: none;
transition: background-color 0.3s ease;
}
.toggleButton:hover {
background-color: #c0392b;
}
.fa {
margin-right: 5px;
}
.voiceButton {
padding: 15px;
font-size: 18px;
margin: 10px;
cursor: pointer;
width: 200px;
border: 2px solid #9b59b6;
background-color: #9b59b6;
color: white;
border-radius: 8px;
outline: none;
transition: background-color 0.3s ease;
}
.voiceButton:hover {
background-color: #8e44ad;
}
</style>
<script>
function toggleRelay(relayNumber) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
updateButton(relayNumber, xhr.responseText);
}
};
xhr.open("GET", "/toggle?relay=" + relayNumber, true);
xhr.send();
}
function updateButton(relayNumber, state) {
var button = document.getElementById("relay" + relayNumber);
button.innerHTML = "<i class='fa fa-lightbulb'></i> Relay " + relayNumber + ": " + (state === "1" ? "On" : "Off");
button.classList.toggle("on", state === "1");
}
function toggleAllRelays() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var newState = xhr.responseText === "1" ? "On" : "Off";
for (var i = 1; i <= 4; i++) {
updateButton(i, xhr.responseText);
}
var toggleButton = document.getElementById("toggleButton");
toggleButton.innerHTML = "<i class='fa fa-lightbulb'></i> Toggle All: " + newState;
toggleButton.classList.toggle("on", xhr.responseText === "1");
}
};
xhr.open("GET", "/toggleAll", true);
xhr.send();
}
</script>
</head>
<body>
<h2><i class="fa fa-plug"></i> ESP32 4-Channel Relay Control</h2>
<div>
<button id="relay1" class="relayButton" onclick="toggleRelay(1)"><i class="fa fa-lightbulb"></i> Relay 1 : Off</button>
<button id="relay2" class="relayButton" onclick="toggleRelay(2)"><i class="fa fa-lightbulb"></i> Relay 2 : Off</button>
<br>
<button id="relay3" class="relayButton" onclick="toggleRelay(3)"><i class="fa fa-lightbulb"></i> Relay 3 : Off</button>
<button id="relay4" class="relayButton" onclick="toggleRelay(4)"><i class="fa fa-lightbulb"></i> Relay 4 : Off</button>
</div>
<button id="toggleButton" class="toggleButton" onclick="toggleAllRelays()"><i class="fa fa-lightbulb"></i> Toggle All: Off</button>
</body>
</html>
)rawliteral";
// Replaces placeholder with button section in your web page
String processor(const String& var){
//Serial.println(var);
if(var == "BUTTONPLACEHOLDER"){
String buttons ="";
for(int i=1; i<=NUM_RELAYS; i++){
buttons+= "<button id='relay" + String(i) + "' class='relayButton' onclick='toggleRelay(" + String(i) + ")'><i class='fa fa-lightbulb'></i> Relay " + String(i) + ": Off</button>";
}
return buttons;
}
return String();
}
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>/toggle?relay=<relayNumber>
server.on("/toggle", HTTP_GET, [] (AsyncWebServerRequest *request) {
String inputMessage;
// GET relay number on <ESP_IP>/toggle?relay=<relayNumber>
if (request->hasParam(PARAM_INPUT_1)) {
inputMessage = request->getParam(PARAM_INPUT_1)->value();
if(RELAY_NO){
Serial.print("NO ");
digitalWrite(relayGPIOs[inputMessage.toInt()-1], !digitalRead(relayGPIOs[inputMessage.toInt()-1]));
request->send(200, "text/plain", digitalRead(relayGPIOs[inputMessage.toInt()-1]) ? "1" : "0");
}
else{
Serial.print("NC ");
digitalWrite(relayGPIOs[inputMessage.toInt()-1], !digitalRead(relayGPIOs[inputMessage.toInt()-1]));
request->send(200, "text/plain", digitalRead(relayGPIOs[inputMessage.toInt()-1]) ? "1" : "0");
}
}
else {
inputMessage = "No relay number sent";
request->send(200, "text/plain", "0");
}
Serial.println(inputMessage);
});
server.on("/toggleAll", HTTP_GET, [] (AsyncWebServerRequest *request) {
// Get the state of the first relay (you can choose any relay to represent the state)
int relayState = digitalRead(relayGPIOs[0]);
// Toggle all relays to the opposite state
for (int i = 0; i < NUM_RELAYS; i++) {
digitalWrite(relayGPIOs[i], !relayState);
}
request->send(200, "text/plain", String(!relayState));
});
;
server.begin();
}
void loop() {}
Result:
When you enter the IP address obtained from the ESP32 into a browser such as Google Chrome or Opera, you get this page.

Each button on this page has a specific role:
For Relay 1, 2, 3, 4: Allows turning on or off lights, sockets, or any connected device (with a power supply of 220VAC or 30VDC).
For Toggle All: Allows turning off or on all devices connected to the 4 relays.

44 Comment(s)
Merci
C\'est bien, c\'est vraiment, la notion de IOT (internet of things), commander des objets à distance via internet (web service)...
Il reste une chose, il faut, protéger la page web par un mot de passe complexe, pour eviter les attaques......
I visited multiple web sites however the audio quality for audio songs present at this web site is really marvelous.
These are truly enormous ideas in concerning blogging. You have touched some good points here. Any way keep up wrinting.
I am sure this piece of writing has touched all the internet people, its really really good piece of writing on building up new web site.
If some one wishes expert view about blogging afterward i recommend him/her to pay a visit this web site, Keep up the pleasant job.
You\'ve made some decent points there. I checked on the web to learn more about the issue and found most people will go along with your views on this site.
I think the admin of this web site is in fact working hard for his web site, as here every material is quality based information.
Ahaa, its good discussion concerning this article at this place at this webpage, I have read all that, so at this time me also commenting at this place.
Hi, I do think this is a great site. I stumbledupon it ;) I may come back yet again since I book marked it. Money and freedom is the best way to change, may you be rich and continue to guide others.
Everything is very open with a precise description of the issues. It was truly informative. Your website is extremely helpful. Thanks for sharing!
Great article. I will be experiencing a few of these issues as well..
What\'s Taking place i\'m new to this, I stumbled upon this I have discovered It absolutely useful and it has aided me out loads. I hope to give a contribution & assist other users like its helped me. Great job.
Whoa! This blog looks exactly like my old one! It\'s on a completely different subject but it has pretty much the same page layout and design. Great choice of colors!
Hello, Neat post. There is an issue together with your site in internet explorer, might check this? IE still is the marketplace leader and a good component to other folks will leave out your great writing due to this problem.
I always was concerned in this topic and still am, thank you for putting up.
Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! By the way, how can we communicate?
I will right away clutch your rss feed as I can’t in finding your e-mail subscription hyperlink or newsletter service. Do you have any? Please allow me know so that I may just subscribe. Thanks.
Ahaa, its pleasant discussion concerning this paragraph here at this weblog, I have read all that, so at this time me also commenting at this place.
There\'s certainly a lot to learn about this subject. I love all of the points you made.
I\'ll right away take hold of your rss as I can\'t to find your e-mail subscription link or newsletter service. Do you\'ve any? Kindly let me understand in order that I could subscribe. Thanks.
I like it when folks come together and share views. Great site, stick with it!
This seems which includes a fairly great function, nicely finished
I conceive this web site has some really fantastic info for everyone :D.
Whoa! This blog looks just like my old one! It\'s on a completely different topic but it has pretty much the same page layout and design. Superb choice of colors!
Beyond just irrigation, the PM Kusum Yojana 2026 offers a unique opportunity for farmers to generate extra income. By selling surplus solar power back to the electricity grid, rural landowners can create a steady financial stream. This scheme is a game-changer for economic stability. Make sure to register online soon to avail of the available subsidies.
I will right away seize your rss feed as I can not to find your e-mail subscription link or newsletter service. Do you have any? Please allow me recognise so that I may subscribe. Thanks.
Ahaa, its fastidious discussion about this paragraph at this place at this web site, I have read all that, so at this time me also commenting at this place.
I love it when folks get together and share ideas. Great blog, continue the good work!
Wow, this paragraph is good, my sister is analyzing these things, therefore I am going to let know her.
Ahaa, its nice dialogue on the topic of this piece of writing at this place at this webpage, I have read all that, so at this time me also commenting at this place.
I will right away seize your rss feed as I can\'t find your e-mail subscription hyperlink or e-newsletter service. Do you\'ve any? Kindly allow me understand in order that I may subscribe. Thanks.
I will right away grab your rss as I can not in finding your e-mail subscription link or newsletter service. Do you have any? Kindly permit me realize in order that I may subscribe. Thanks.
Wow! This blog looks exactly like my old one! It\'s on a entirely different subject but it has pretty much the same page layout and design. Great choice of colors!
I am sure this post has touched all the internet visitors, its really really nice piece of writing on building up new webpage.
This website provides clear and valuable information that’s easy to understand. Visitors looking for reliable details should definitely explore this site for helpful insights.
Amazing! This blog looks just like my old one! It\'s on a completely different subject but it has pretty much the same page layout and design. Great choice of colors!
I needed to thank you for this good read!! I absolutely enjoyed every little bit of it. I have got you saved as a favorite to look at new things you
I am sure this post has touched all the internet viewers, its really really pleasant post on building up new blog.
I am sure this piece of writing has touched all the internet visitors, its really really good piece of writing on building up new webpage.
These are genuinely fantastic ideas in on the topic of blogging. You have touched some fastidious factors here. Any way keep up wrinting.
I am sure this article has touched all the internet viewers, its really really good piece of writing on building up new webpage.
Wow, this article is fastidious, my sister is analyzing these kinds of things, so I am going to let know her.
Leave a Comment