# main.ino

- Project: [esp32-WS2812B-8x8-matrix](https://flashesp.com/explore/oc6qoqqV4K0N3mqQLkgcT.md) by Mikrobot.pl
- Board: ESP32 Dev Module
- Language: Arduino (C++)
- Web page: https://flashesp.com/explore/oc6qoqqV4K0N3mqQLkgcT/files/0sZgEILKbcV5Y1mRHOa8T

```cpp
#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>
#include <FastLED.h>

// -------------------- Wi-Fi Captive Portal settings --------------------
static const char* AP_SSID = "LED-Matrix-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);

// -------------------- LED Matrix settings (WS2812B / NeoPixel) --------------------
#define LED_PIN       5
#define LED_TYPE      WS2812B
#define COLOR_ORDER   GRB

static const uint16_t MATRIX_W = 8;
static const uint16_t MATRIX_H = 8;
static const uint16_t NUM_LEDS = MATRIX_W * MATRIX_H;

CRGB leds[NUM_LEDS];

// Power safety: limit max brightness to reduce current draw.
// You can change this in the portal too, but this is a hard cap.
static const uint8_t BRIGHTNESS_CAP = 160;

// If your matrix wiring is "serpentine/zigzag", set true.
// If it's straight rows (left->right every row), set false.
static const bool SERPENTINE_LAYOUT = true;

// -------------------- UI state --------------------
uint8_t gBrightness = 80;     // 0..255
uint8_t gMode = 0;            // 0=Solid, 1=Rainbow, 2=Plasma, 3=Chase
uint8_t gHue = 0;             // 0..255 (for solid color)
bool gPower = true;           // on/off

unsigned long lastAnimMs = 0;

// -------------------- Helpers --------------------
String htmlEscape(const String& s) {
  String out;
  out.reserve(s.length() + 16);
  for (size_t i = 0; i < s.length(); i++) {
    char c = s[i];
    switch (c) {
      case '&': out += "&amp;"; break;
      case '<': out += "&lt;";  break;
      case '>': out += "&gt;";  break;
      case '"': out += "&quot;";break;
      case '\'':out += "&#39;"; break;
      default:  out += c;       break;
    }
  }
  return out;
}

// Map x,y to LED index for an 8x8 matrix
uint16_t XY(uint16_t x, uint16_t y) {
  if (x >= MATRIX_W || y >= MATRIX_H) return 0;

  if (!SERPENTINE_LAYOUT) {
    // Progressive rows
    return (y * MATRIX_W) + x;
  }

  // Serpentine: even rows left->right, odd rows right->left
  if (y & 0x01) {
    return (y * MATRIX_W) + (MATRIX_W - 1 - x);
  } else {
    return (y * MATRIX_W) + x;
  }
}

void fillSolidHue(uint8_t hue) {
  fill_solid(leds, NUM_LEDS, CHSV(hue, 255, 255));
}

void animRainbow() {
  // Simple moving rainbow
  static uint8_t baseHue = 0;
  for (uint16_t y = 0; y < MATRIX_H; y++) {
    for (uint16_t x = 0; x < MATRIX_W; x++) {
      leds[XY(x, y)] = CHSV(baseHue + x * 8 + y * 8, 255, 255);
    }
  }
  baseHue++;
}

void animPlasma() {
  // Lightweight plasma using sin8/cos8
  static uint8_t t = 0;
  for (uint16_t y = 0; y < MATRIX_H; y++) {
    for (uint16_t x = 0; x < MATRIX_W; x++) {
      uint8_t v = sin8(x * 24 + t) + cos8(y * 24 + t);
      leds[XY(x, y)] = CHSV(v, 255, 255);
    }
  }
  t++;
}

void animChase() {
  // A simple chasing pixel across the matrix
  static uint16_t idx = 0;
  fadeToBlackBy(leds, NUM_LEDS, 40);
  leds[idx % NUM_LEDS] = CHSV(gHue, 255, 255);
  idx++;
}

// Apply power and brightness safely
void applyOutput() {
  uint8_t b = gPower ? gBrightness : 0;
  if (b > BRIGHTNESS_CAP) b = BRIGHTNESS_CAP;
  FastLED.setBrightness(b);
  FastLED.show();
}

// -------------------- Web handlers --------------------
void handleRoot() {
  String page =
    "<!doctype html><html><head>"
    "<meta charset='utf-8'/>"
    "<meta name='viewport' content='width=device-width,initial-scale=1'/>"
    "<title>LED Matrix Portal</title>"
    "<style>"
    "body{font-family:system-ui,Arial,sans-serif;margin:16px;}"
    ".card{max-width:760px;padding:16px;border:1px solid #ddd;border-radius:12px;}"
    ".row{display:flex;gap:12px;flex-wrap:wrap;align-items:center;}"
    "label{display:block;font-size:14px;margin-bottom:6px;}"
    "input,select,button{font-size:16px;padding:10px;border-radius:10px;border:1px solid #ccc;}"
    "button{cursor:pointer;}"
    ".pill{display:inline-block;padding:6px 10px;border-radius:999px;border:1px solid #ccc;}"
    "</style>"
    "</head><body>"
    "<div class='card'>"
    "<h2>ESP32 LED Matrix Captive Portal</h2>"
    "<div class='row'>"
    "<div class='pill'>SSID: <b>" + String(AP_SSID) + "</b></div>"
    "<div class='pill'>IP: <b>" + apIP.toString() + "</b></div>"
    "</div>"

    "<h3>Controls</h3>"
    "<div class='row'>"
    "  <div>"
    "    <label>Power</label>"
    "    <select id='power'>"
    "      <option value='1'>ON</option>"
    "      <option value='0'>OFF</option>"
    "    </select>"
    "  </div>"
    "  <div>"
    "    <label>Mode</label>"
    "    <select id='mode'>"
    "      <option value='0'>Solid</option>"
    "      <option value='1'>Rainbow</option>"
    "      <option value='2'>Plasma</option>"
    "      <option value='3'>Chase</option>"
    "    </select>"
    "  </div>"
    "  <div>"
    "    <label>Brightness</label>"
    "    <input id='bri' type='range' min='0' max='255'/>"
    "  </div>"
    "  <div>"
    "    <label>Color (Solid/Chase Hue)</label>"
    "    <input id='hue' type='range' min='0' max='255'/>"
    "  </div>"
    "</div>"

    "<div class='row' style='margin-top:12px;'>"
    "  <button onclick='apply()'>Apply</button>"
    "  <button onclick='loadState()'>Refresh</button>"
    "</div>"

    "<p style='margin-top:12px;'>"
    "Tip: If the portal does not open automatically, go to "
    "<b>http://" + apIP.toString() + "/</b>"
    "</p>"

    "</div>"

    "<script>"
    "async function loadState(){"
    "  const r = await fetch('/state');"
    "  const s = await r.json();"
    "  document.getElementById('power').value = s.power ? '1' : '0';"
    "  document.getElementById('mode').value = String(s.mode);"
    "  document.getElementById('bri').value = String(s.brightness);"
    "  document.getElementById('hue').value = String(s.hue);"
    "}"
    "async function apply(){"
    "  const power = document.getElementById('power').value;"
    "  const mode = document.getElementById('mode').value;"
    "  const bri = document.getElementById('bri').value;"
    "  const hue = document.getElementById('hue').value;"
    "  const url = `/set?power=${power}&mode=${mode}&bri=${bri}&hue=${hue}`;"
    "  await fetch(url);"
    "  await loadState();"
    "}"
    "loadState();"
    "</script>"

    "</body></html>";

  webServer.send(200, "text/html", page);
}

void handleState() {
  String json = "{";
  json += "\"power\":" + String(gPower ? "true" : "false") + ",";
  json += "\"mode\":" + String(gMode) + ",";
  json += "\"brightness\":" + String(gBrightness) + ",";
  json += "\"hue\":" + String(gHue);
  json += "}";
  webServer.send(200, "application/json", json);
}

void handleSet() {
  if (webServer.hasArg("power")) gPower = (webServer.arg("power").toInt() != 0);
  if (webServer.hasArg("mode"))  gMode = (uint8_t)constrain(webServer.arg("mode").toInt(), 0, 3);
  if (webServer.hasArg("bri"))   gBrightness = (uint8_t)constrain(webServer.arg("bri").toInt(), 0, 255);
  if (webServer.hasArg("hue"))   gHue = (uint8_t)constrain(webServer.arg("hue").toInt(), 0, 255);

  // Apply immediately
  if (gMode == 0) fillSolidHue(gHue);
  applyOutput();

  webServer.send(200, "text/plain", "OK");
}

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 the ESP32 AP IP
  dnsServer.start(DNS_PORT, "*", apIP);

  webServer.on("/", handleRoot);
  webServer.on("/state", handleState);
  webServer.on("/set", handleSet);
  webServer.onNotFound(handleNotFound);

  webServer.begin();
}

// -------------------- Arduino entry points --------------------
void setup() {
  Serial.begin(115200);
  delay(200);

  // LED init
  FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS);
  FastLED.clear(true);
  FastLED.setBrightness(min(gBrightness, BRIGHTNESS_CAP));

  // Boot animation: quick flash
  fillSolidHue(96);
  applyOutput();
  delay(150);
  FastLED.clear(true);
  applyOutput();

  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();

  // Animation loop (non-blocking)
  unsigned long now = millis();
  if (now - lastAnimMs >= 25) { // ~40 FPS
    lastAnimMs = now;

    if (!gPower) {
      FastLED.clear(false);
      applyOutput();
      return;
    }

    switch (gMode) {
      case 0: // Solid
        fillSolidHue(gHue);
        break;
      case 1: // Rainbow
        animRainbow();
        break;
      case 2: // Plasma
        animPlasma();
        break;
      case 3: // Chase
        animChase();
        break;
      default:
        fillSolidHue(gHue);
        break;
    }

    applyOutput();
  }
}
```
