Yarana Iot Guru
Published © MIT

Mastering Home Illumination: ESP32 + 8-Channel Relay

Control up to 8 lights and appliances using ESP32 via web and manual switches. Smart lighting made simple by YaranaIoT Guru!

BeginnerFull instructions provided8 hours35
Mastering Home Illumination: ESP32 + 8-Channel Relay

Things used in this project

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Code

💻 Code Example

C/C++
/*
  Mastering Home Illumination: ESP32 + 8-Channel Relay
  Control lights from Web or Manual Switch
  Author: YaranaIoT Guru
*/

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

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

WebServer server(80);

int relayPins[8] = {13, 12, 14, 27, 26, 25, 33, 32};
bool relayState[8] = {LOW, LOW, LOW, LOW, 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 8-Relay Control</title><style>";
  html += "body{font-family:Arial;text-align:center;background:#fafafa;}button{padding:10px 20px;margin:5px;font-size:16px;border-radius:8px;}";
  html += "</style></head><body><h2>💡 Smart Home Control - YaranaIoT Guru</h2><hr>";
  for (int i = 0; i < 8; 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 < 8) {
      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 < 8; 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 to WiFi!");
  Serial.println(WiFi.localIP());

  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