Yarana Iot Guru
Published © MIT

Ultimate Home Lighting Control: ESP32 + 4-Channel Relay

Smartly control 4 lights or home appliances using ESP32 with both web and manual control options — brought to you by YaranaIoT Guru

BeginnerFull instructions provided8 hours27
Ultimate Home Lighting Control: ESP32 + 4-Channel Relay

Things used in this project

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Code

💻 Code Example

C/C++
/*
  Ultimate Home Lighting Control: ESP32 + 4-Channel Relay
  Author: YaranaIoT Guru
*/

#include <WiFi.h>
#include <WebServer.h>

const char* ssid = "YourWiFiName";
const char* password = "YourWiFiPassword";

WebServer server(80);

int relayPins[4] = {13, 12, 14, 27};
bool relayState[4] = {LOW, LOW, LOW, LOW};

String buildHTML() {
  String html = "<html><head><meta charset='UTF-8'><meta name='viewport' content='width=device-width, initial-scale=1'>";
  html += "<title>ESP32 4-Relay Control</title><style>";
  html += "body{font-family:Arial;text-align:center;background:#f4f4f4;}button{padding:10px 20px;margin:5px;font-size:16px;border-radius:8px;}";
  html += "h2{color:#333;}hr{margin:20px 0;}";
  html += "</style></head><body><h2>💡 Ultimate Home Lighting Control</h2><hr>";
  for (int i = 0; i < 4; i++) {
    html += "<p>Relay " + String(i + 1) + ": ";
    html += relayState[i] ? "<b style='color:green;'>ON</b>" : "<b style='color:red;'>OFF</b>";
    html += "</p><a href='/toggle?ch=" + String(i) + "'><button>Toggle</button></a><hr>";
  }
  html += "<p><small>By YaranaIoT Guru</small></p></body></html>";
  return html;
}

void handleRoot() {
  server.send(200, "text/html", buildHTML());
}

void handleToggle() {
  if (server.hasArg("ch")) {
    int ch = server.arg("ch").toInt();
    if (ch >= 0 && ch < 4) {
      relayState[ch] = !relayState[ch];
      digitalWrite(relayPins[ch], relayState[ch]);
    }
  }
  server.sendHeader("Location", "/");
  server.send(303);
}

void setup() {
  Serial.begin(115200);
  for (int i = 0; i < 4; i++) {
    pinMode(relayPins[i], OUTPUT);
    digitalWrite(relayPins[i], LOW);
  }

  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println("\nConnected! IP: " + WiFi.localIP().toString());

  server.on("/", handleRoot);
  server.on("/toggle", handleToggle);
  server.begin();
  Serial.println("Server started!");
}

void loop() {
  server.handleClient();
}

Credits

Yarana Iot Guru
35 projects • 2 followers
Yarana Iot Guru Yarana IoT Guru: Arduino, ESP32, GSM, NodeMCU & more. Projects, Tutorials & App Development. Innovate with us!
Thanks to YaranaIoT Guru.

Comments