main.ino

Arduino (C++) · 236 lines

/**
 * @file    esp32c3_led_captive_portal.ino
 * @brief   WiFi Captive Portal for LED control — ESP32-C3 Super Mini
 *
 * Creates an open WiFi Access Point and a captive portal page that lets
 * any connected device turn the on-board LED ON or OFF via a simple
 * web interface.
 *
 * Target board : ESP32-C3 Super Mini (USB-C, WiFi + BT 5.0)
 * Arduino core : esp32 by Espressif >= 2.0.14
 *
 * IMPORTANT — Arduino IDE board settings:
 *   Board            : ESP32C3 Dev Module
 *   USB CDC On Boot  : Enabled   <-- required for Serial over USB-C
 *   Flash Mode       : QIO 80MHz
 *   Flash Size       : 4MB (32Mb)
 *   Partition Scheme : Default 4MB with spiffs
 *   Upload Speed     : 921600
 */

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

// =======================
// LED CONFIGURATION
// =======================
/**
 * ESP32-C3 Super Mini on-board blue LED is wired to GPIO 8.
 * The LED is ACTIVE LOW:
 *   digitalWrite(LED_PIN, LOW)  --> LED ON
 *   digitalWrite(LED_PIN, HIGH) --> LED OFF
 *
 * If you have an external LED on a different pin, change LED_PIN
 * and set ACTIVE_LOW to false.
 */
#define LED_PIN     8
#define ACTIVE_LOW  true   // true for on-board LED; false for most external LEDs

// Resolve the physical signal level from the logical state
inline int ledLevel(bool on) {
  return (ACTIVE_LOW ? !on : on) ? HIGH : LOW;
}

bool ledState = false;   // false = OFF, true = ON

// =======================
// WIFI ACCESS POINT CONFIG
// =======================
const char* AP_SSID = "ESP32-C3-LED";   // 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;
WebServer  server(80);

// =======================
// LED HELPERS
// =======================

/** Apply the current ledState to the physical GPIO. */
void updateLed() {
  digitalWrite(LED_PIN, ledLevel(ledState));
}

// =======================
// HTML PAGE
// =======================

/** Build and return the full control page as a String. */
String htmlPage(bool currentLedState) {
  String html =
    "<!DOCTYPE html>"
    "<html lang='en'><head>"
    "<meta charset='UTF-8'>"
    "<meta name='viewport' content='width=device-width,initial-scale=1.0'>"
    "<title>ESP32-C3 LED Control</title>"
    "<style>"
      "body{font-family:sans-serif;max-width:480px;margin:30px auto;padding:0 16px;}"
      "h2{color:#333;}"
      ".card{background:#f5f5f5;border-radius:8px;padding:16px;margin-bottom:16px;}"
      ".led-on {color:#27ae60;font-weight:bold;}"
      ".led-off{color:#c0392b;font-weight:bold;}"
      ".btn{display:inline-block;padding:12px 28px;margin:6px 4px;"
           "font-size:16px;border:none;border-radius:6px;cursor:pointer;"
           "text-decoration:none;}"
      ".btn-on {background:#27ae60;color:#fff;}"
      ".btn-off{background:#c0392b;color:#fff;}"
      ".btn:hover{opacity:.85;}"
      "footer{margin-top:24px;font-size:13px;color:#888;}"
    "</style>"
    "</head><body>";

  html += "<h2>&#128161; ESP32-C3 LED Control</h2>";

  // Status card
  html += "<div class='card'>LED is currently:&nbsp;";
  if (currentLedState) {
    html += "<span class='led-on'>ON</span>";
  } else {
    html += "<span class='led-off'>OFF</span>";
  }
  html += "</div>";

  // ON button
  html += "<form action='/set' method='GET' style='display:inline;'>"
          "<input type='hidden' name='state' value='on'>"
          "<button class='btn btn-on' type='submit'>Turn ON</button>"
          "</form>";

  // OFF button
  html += "<form action='/set' method='GET' style='display:inline;'>"
          "<input type='hidden' name='state' value='off'>"
          "<button class='btn btn-off' type='submit'>Turn OFF</button>"
          "</form>";

  html += "<footer>"
          "<hr>"
          "<p>&#128246; Connect to WiFi: <b>ESP32-C3-LED</b> (open, no password).</p>"
          "<p>This page opens automatically as a captive portal.</p>"
          "</footer>"
          "</body></html>";

  return html;
}

// =======================
// CAPTIVE PORTAL REDIRECT
// =======================

/** Send a 302 redirect to the root control page. */
void redirectToRoot() {
  String url = "http://";
  url += apIP.toString();
  url += "/";
  server.sendHeader("Location", url, true);
  server.send(302, "text/plain", "");
}

// =======================
// HTTP HANDLERS
// =======================

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

void handleSetLed() {
  if (server.hasArg("state")) {
    String val = server.arg("state");
    if (val == "on")  { ledState = true;  }
    if (val == "off") { ledState = false; }
    updateLed();
  }
  // Respond with updated page (avoids browser re-submit on refresh)
  server.send(200, "text/html", htmlPage(ledState));
}

void handleNotFound() {
  // Any unknown URL -> redirect to control page (captive portal behaviour)
  redirectToRoot();
}

// ------------------------------------------------------------------
// Captive-portal detection endpoints used by different OS / devices:
//   Android  : GET /generate_204  (expects HTTP 204)
//   iOS/macOS: GET /hotspot-detect.html
//   Windows  : GET /ncsi.txt
//   Linux    : GET /connectivity-check.html  (and variants)
// We serve the control page for all of them so the user lands there
// directly instead of seeing a "no internet" warning.
// ------------------------------------------------------------------
void handleGenerate204()      { handleRoot(); }
void handleHotspotDetect()    { handleRoot(); }
void handleNCsi()             { handleRoot(); }
void handleConnectivityCheck(){ handleRoot(); }

// =======================
// SETUP
// =======================
void setup() {
  // USB-CDC serial — needs "USB CDC On Boot: Enabled" in Arduino IDE
  Serial.begin(115200);
  delay(500);   // Allow USB CDC enumeration before first print

  Serial.println("\n=== ESP32-C3 Super Mini — LED Captive Portal ===");

  // ---- LED ----
  pinMode(LED_PIN, OUTPUT);
  ledState = false;
  updateLed();
  Serial.printf("LED pin: GPIO %d  |  active-%s\n",
                LED_PIN, ACTIVE_LOW ? "LOW" : "HIGH");

  // ---- WiFi AP (open, no password) ----
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, netMsk);
  WiFi.softAP(AP_SSID);

  Serial.printf("WiFi AP started  SSID: %s\n", AP_SSID);
  Serial.printf("AP IP address  : %s\n", WiFi.softAPIP().toString().c_str());

  // ---- DNS — wildcard redirect to AP IP ----
  dnsServer.start(DNS_PORT, "*", apIP);

  // ---- Web server routes ----
  server.on("/",                       handleRoot);
  server.on("/set",                    handleSetLed);

  // Captive-portal detection paths
  server.on("/generate_204",           handleGenerate204);    // Android
  server.on("/hotspot-detect.html",    handleHotspotDetect);  // iOS / macOS
  server.on("/ncsi.txt",               handleNCsi);           // Windows
  server.on("/connectivity-check",     handleConnectivityCheck); // Linux / Firefox

  server.onNotFound(handleNotFound);
  server.begin();

  Serial.println("HTTP server started on port 80.");
  Serial.println("DNS captive portal active — all domains -> 192.168.4.1");
  Serial.println("================================================\n");
}

// =======================
// LOOP
// =======================
void loop() {
  dnsServer.processNextRequest();
  server.handleClient();
}