main.ino
Arduino (C++) · 261 lines
/*
* Wemos D1 Mini (ESP8266) - WiFi LED Blink Captive Portal
* ------------------------------------------------------------
* Creates an open WiFi Access Point and a captive portal.
* When a device connects, a control page lets you START / STOP
* blinking the on-board LED and adjust the blink speed with a slider.
*
* Board: Wemos D1 Mini (clone) / any ESP8266 with LED_BUILTIN
* IDE: Arduino IDE with the ESP8266 board package
* Select: Tools > Board > "LOLIN(WEMOS) D1 R2 & mini"
*
* NOTE: On the Wemos D1 Mini the on-board blue LED is wired to GPIO2 (D4)
* and is ACTIVE LOW -> writing LOW turns it ON, HIGH turns it OFF.
* The blink is non-blocking (millis-based) so the captive portal
* stays responsive at all times.
*/
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
// =======================
// LED CONFIGURATION
// =======================
// LED_BUILTIN is GPIO2 (D4) on the Wemos D1 Mini. Change this if your
// clone uses a different pin for the on-board LED.
#define LED_PIN LED_BUILTIN
bool blinking = false; // is the LED currently blinking?
bool ledIsOn = false; // current physical LED state (true = lit)
unsigned long blinkInterval = 500; // toggle interval in ms (half period)
unsigned long lastToggle = 0; // millis() of the last toggle
// Allowed blink interval range for the speed slider (milliseconds)
const unsigned long MIN_INTERVAL = 50;
const unsigned long MAX_INTERVAL = 2000;
// =======================
// WIFI ACCESS POINT CONFIG
// =======================
const char* ap_ssid = "Wemos-LED-Blink"; // open AP (no password)
IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);
// =======================
// DNS / CAPTIVE PORTAL
// =======================
const byte DNS_PORT = 53;
DNSServer dnsServer;
ESP8266WebServer server(80);
// =======================
// LED HELPERS (active LOW)
// =======================
void writeLed(bool on) {
ledIsOn = on;
digitalWrite(LED_PIN, on ? LOW : HIGH); // inverted logic on this board
}
void startBlink() {
blinking = true;
lastToggle = millis();
writeLed(true); // start lit so the change is visible immediately
}
void stopBlink() {
blinking = false;
writeLed(false); // make sure the LED ends up OFF
}
// =======================
// STATUS AS JSON
// =======================
String statusJson() {
String j = "{\"blinking\":";
j += blinking ? "true" : "false";
j += ",\"interval\":";
j += String(blinkInterval);
j += "}";
return j;
}
// =======================
// HTML PAGE
// =======================
String htmlPage() {
String state = blinking ? "ON" : "OFF";
String html;
html.reserve(3000);
html += "<!DOCTYPE html><html lang='en'><head>";
html += "<meta charset='UTF-8'>";
html += "<meta name='viewport' content='width=device-width, initial-scale=1.0'>";
html += "<title>Wemos D1 Mini - LED Blink</title>";
html += "<style>";
html += "*{box-sizing:border-box;}";
html += "body{font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;margin:0;padding:24px;background:#0f172a;color:#e2e8f0;}";
html += ".card{max-width:420px;margin:0 auto;background:#1e293b;border-radius:16px;padding:24px;box-shadow:0 10px 30px rgba(0,0,0,.4);}";
html += "h1{font-size:20px;margin:0 0 4px;}";
html += ".sub{font-size:13px;color:#94a3b8;margin:0 0 20px;}";
html += ".status{display:flex;align-items:center;gap:10px;background:#0f172a;border:1px solid #334155;border-radius:12px;padding:14px 16px;margin-bottom:20px;}";
html += ".dot{width:14px;height:14px;border-radius:50%;background:#475569;flex:0 0 auto;}";
html += ".dot.on{background:#22c55e;box-shadow:0 0 10px #22c55e;}";
html += ".btns{display:flex;gap:10px;margin-bottom:22px;}";
html += "button{flex:1;padding:14px;font-size:16px;font-weight:600;border:0;border-radius:12px;cursor:pointer;color:#fff;}";
html += ".start{background:#16a34a;}";
html += ".stop{background:#dc2626;}";
html += "button:active{transform:translateY(1px);}";
html += "label{display:block;font-size:14px;margin-bottom:10px;color:#cbd5e1;}";
html += "input[type=range]{width:100%;accent-color:#22c55e;}";
html += ".val{font-variant-numeric:tabular-nums;font-weight:700;color:#fff;}";
html += "hr{border:0;border-top:1px solid #334155;margin:22px 0 14px;}";
html += ".note{font-size:12px;color:#64748b;line-height:1.5;}";
html += "</style></head><body>";
html += "<div class='card'>";
html += "<h1>Wemos D1 Mini — LED Blink</h1>";
html += "<p class='sub'>WiFi captive portal control panel</p>";
html += "<div class='status'>";
html += "<span id='dot' class='dot" + String(blinking ? " on" : "") + "'></span>";
html += "<div>Blinking: <b id='state'>" + state + "</b><br>";
html += "Interval: <span class='val' id='ival'>" + String(blinkInterval) + "</span> ms</div>";
html += "</div>";
html += "<div class='btns'>";
html += "<button class='start' onclick=\"setBlink('on')\">Start</button>";
html += "<button class='stop' onclick=\"setBlink('off')\">Stop</button>";
html += "</div>";
html += "<label>Blink speed (interval): <span class='val' id='slabel'>" + String(blinkInterval) + "</span> ms</label>";
html += "<input type='range' id='speed' min='" + String(MIN_INTERVAL) + "' max='" + String(MAX_INTERVAL) + "' step='10' value='" + String(blinkInterval) + "'";
html += " oninput=\"document.getElementById('slabel').textContent=this.value\"";
html += " onchange=\"setSpeed(this.value)\">";
html += "<hr>";
html += "<p class='note'>Connect to WiFi <b>";
html += ap_ssid;
html += "</b> (open network). Lower interval = faster blinking. ";
html += "The on-board LED uses inverted (active-low) logic on this board.</p>";
html += "</div>";
// ---- JavaScript ----
html += "<script>";
html += "function apply(d){";
html += "document.getElementById('state').textContent=d.blinking?'ON':'OFF';";
html += "document.getElementById('ival').textContent=d.interval;";
html += "document.getElementById('slabel').textContent=d.interval;";
html += "document.getElementById('speed').value=d.interval;";
html += "document.getElementById('dot').className='dot'+(d.blinking?' on':'');";
html += "}";
html += "function setBlink(s){fetch('/set?blink='+s).then(r=>r.json()).then(apply).catch(()=>{});}";
html += "function setSpeed(v){fetch('/set?interval='+v).then(r=>r.json()).then(apply).catch(()=>{});}";
html += "</script>";
html += "</body></html>";
return html;
}
// =======================
// CAPTIVE PORTAL REDIRECT
// =======================
void redirectToRoot() {
String url = "http://" + apIP.toString() + "/";
server.sendHeader("Location", url, true);
server.send(302, "text/plain", "");
}
// =======================
// HTTP HANDLERS
// =======================
void handleRoot() {
server.send(200, "text/html", htmlPage());
}
void handleSet() {
// Start / stop blinking
if (server.hasArg("blink")) {
String b = server.arg("blink");
if (b == "on") startBlink();
else if (b == "off") stopBlink();
}
// Adjust blink interval (clamped to the allowed range)
if (server.hasArg("interval")) {
long v = server.arg("interval").toInt();
if (v < (long)MIN_INTERVAL) v = MIN_INTERVAL;
if (v > (long)MAX_INTERVAL) v = MAX_INTERVAL;
blinkInterval = (unsigned long)v;
}
server.send(200, "application/json", statusJson());
}
void handleNotFound() {
// Redirect any unknown path to the main page (captive portal behavior)
redirectToRoot();
}
// =======================
// SETUP
// =======================
void setup() {
Serial.begin(115200);
delay(100);
// Initialize LED (OFF, not blinking)
pinMode(LED_PIN, OUTPUT);
stopBlink();
// Start WiFi in AP mode (open network)
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, netMsk);
WiFi.softAP(ap_ssid);
Serial.println();
Serial.print("AP started. SSID: ");
Serial.println(ap_ssid);
Serial.print("AP IP address: ");
Serial.println(WiFi.softAPIP());
// Start DNS server -> redirect all domains to our AP
dnsServer.start(DNS_PORT, "*", apIP);
// Main routes
server.on("/", handleRoot);
server.on("/set", handleSet);
// Captive portal detection endpoints (serve the page so the popup appears)
server.on("/generate_204", handleRoot); // Android
server.on("/gen_204", handleRoot); // Android (older)
server.on("/hotspot-detect.html", handleRoot); // iOS / macOS
server.on("/library/test/success.html", handleRoot); // iOS
server.on("/ncsi.txt", handleRoot); // Windows
server.on("/connecttest.txt", handleRoot); // Windows 10/11
server.on("/fwlink", handleRoot); // Windows
server.on("/canonical.html", handleRoot); // Firefox / Ubuntu
server.onNotFound(handleNotFound);
server.begin();
Serial.println("Web server + DNS captive portal started.");
}
// =======================
// LOOP (non-blocking blink)
// =======================
void loop() {
dnsServer.processNextRequest();
server.handleClient();
if (blinking) {
unsigned long now = millis();
if (now - lastToggle >= blinkInterval) {
lastToggle = now;
writeLed(!ledIsOn); // toggle the LED
}
}
}