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.
Leave a Comment