main.ino
Arduino (C++) · 158 lines
#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>
// -------------------- Wi-Fi Captive Portal settings --------------------
static const char* AP_SSID = "Relay-Portal";
static const char* AP_PASS = ""; // empty = open network (no login)
static const byte DNS_PORT = 53;
DNSServer dnsServer;
WebServer webServer(80);
IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);
// -------------------- Relay settings (Mikrobot 1-channel, High Level) --------------------
// This relay module is set to High Level trigger mode: the coil energizes
// when the IN pin is HIGH, and de-energizes when IN is LOW.
// RELAY_ON = HIGH -> COM-NO contact closed (relay energized)
// RELAY_OFF = LOW -> COM-NO contact open (relay de-energized)
// An ESP32 GPIO already defaults to LOW on reset/boot, so the relay is
// inherently off at power-on in this mode — the explicit digitalWrite()
// in setup() below just makes that state unambiguous.
//
// GPIO26 was chosen because it is NOT one of the ESP32 strapping pins
// (avoid GPIO0, GPIO2, GPIO12, GPIO15 for this purpose).
const byte RELAY_PIN = 26;
const int RELAY_ON = HIGH;
const int RELAY_OFF = LOW;
bool relayIsOn = false; // logical state shared with the web UI
// -------------------- Helpers --------------------
void setRelay(bool on) {
relayIsOn = on;
digitalWrite(RELAY_PIN, on ? RELAY_ON : RELAY_OFF);
}
// -------------------- Web handlers --------------------
void handleRoot() {
String state = relayIsOn ? "ON" : "OFF";
String btnLabel = relayIsOn ? "Turn OFF" : "Turn ON";
String page =
"<!doctype html><html><head>"
"<meta charset='utf-8'/>"
"<meta name='viewport' content='width=device-width,initial-scale=1'/>"
"<title>ESP32 Relay Controller</title>"
"<style>"
"body{font-family:system-ui,Arial,sans-serif;margin:16px;}"
".card{max-width:720px;padding:16px;border:1px solid #ddd;border-radius:12px;}"
".row{display:flex;gap:12px;flex-wrap:wrap;}"
".pill{display:inline-block;padding:6px 10px;border-radius:999px;border:1px solid #ccc;}"
".big{font-size:44px;font-weight:800;margin:10px 0;}"
"button{font-size:20px;padding:14px 28px;border-radius:12px;border:1px solid #ccc;cursor:pointer;}"
"</style>"
"</head><body>"
"<div class='card'>"
"<h2>ESP32 Single-Channel Relay Controller</h2>"
"<div class='row'>"
"<div class='pill'>SSID: <b>" + String(AP_SSID) + "</b></div>"
"<div class='pill'>IP: <b>" + apIP.toString() + "</b></div>"
"</div>"
"<p>Relay state:</p>"
"<div class='big' id='state'>" + state + "</div>"
"<button id='toggleBtn' onclick='toggleRelay()'>" + btnLabel + "</button>"
"<p style='margin-top:12px;'>If the portal did not open automatically, go to "
"<b>http://" + apIP.toString() + "/</b></p>"
"</div>"
"<script>"
"async function refresh(){"
" try{"
" const r = await fetch('/data');"
" const j = await r.json();"
" document.getElementById('state').textContent = j.relay;"
" document.getElementById('toggleBtn').textContent = (j.relay === 'ON') ? 'Turn OFF' : 'Turn ON';"
" }catch(e){"
" console.error(e);"
" }"
"}"
"async function toggleRelay(){"
" try{ await fetch('/toggle'); await refresh(); }catch(e){ console.error(e); }"
"}"
"setInterval(refresh, 1000);"
"refresh();"
"</script>"
"</body></html>";
webServer.send(200, "text/html", page);
}
void sendStateJson() {
String json = "{";
json += "\"relay\":\"" + String(relayIsOn ? "ON" : "OFF") + "\",";
json += "\"trigger_level\":\"HIGH\",";
json += "\"uptime_ms\":" + String(millis());
json += "}";
webServer.send(200, "application/json", json);
}
void handleData() { sendStateJson(); }
void handleOn() { setRelay(true); sendStateJson(); }
void handleOff() { setRelay(false); sendStateJson(); }
void handleToggle() { setRelay(!relayIsOn); sendStateJson(); }
void handleNotFound() {
// Captive portal behavior: redirect any unknown path to "/"
webServer.sendHeader("Location", String("http://") + apIP.toString() + "/", true);
webServer.send(302, "text/plain", "");
}
void setupCaptivePortal() {
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, netMsk);
if (strlen(AP_PASS) == 0) WiFi.softAP(AP_SSID);
else WiFi.softAP(AP_SSID, AP_PASS);
// DNS wildcard: resolve all hostnames to our AP IP
dnsServer.start(DNS_PORT, "*", apIP);
webServer.on("/", handleRoot);
webServer.on("/data", handleData);
webServer.on("/on", handleOn);
webServer.on("/off", handleOff);
webServer.on("/toggle", handleToggle);
webServer.onNotFound(handleNotFound);
webServer.begin();
}
// -------------------- Arduino entry points --------------------
void setup() {
// STEP 1, ALWAYS FIRST: set the relay pin as output and force the OFF
// state (LOW, since this module is set to High Level mode) before
// anything else runs. An ESP32 GPIO already defaults to LOW at boot,
// so this line mainly makes the safe state explicit rather than
// relying on the reset default.
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, RELAY_OFF);
relayIsOn = false;
Serial.begin(115200);
delay(200);
setupCaptivePortal();
Serial.println("Captive portal started.");
Serial.print("Connect to AP: ");
Serial.println(AP_SSID);
Serial.print("Open: http://");
Serial.println(apIP);
}
void loop() {
dnsServer.processNextRequest();
webServer.handleClient();
}