main.ino
Arduino (C++) · 428 lines
/**
* @file esp32s3_rgb_captive_portal.ino
* @brief WiFi Captive Portal with HSV colour-wheel RGB control — ESP32-S3 (N16R8)
*
* The control page renders an interactive HSV colour wheel on an HTML5 Canvas.
* Tap or drag anywhere on the wheel to pick a colour — no separate R/G/B sliders.
* A single brightness slider adjusts intensity. All updates happen in real time
* via Fetch API without reloading the page.
*
* Target board : ESP32-S3-N16R8 Dev Board (dual USB-C)
* Arduino core : esp32 by Espressif >= 2.0.14
* Extra library: Adafruit NeoPixel >= 1.12.0
*
* IMPORTANT — Arduino IDE board settings:
* Board : ESP32S3 Dev Module
* USB CDC On Boot : Enabled
* USB Mode : Hardware CDC and JTAG
* PSRAM : OPI PSRAM
* Flash Size : 16MB (128Mb)
* Partition Scheme : 16M Flash (3MB APP/9.9MB FATFS)
* Flash Mode : QIO 80MHz
* Upload Speed : 921600
*/
#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>
#include <Adafruit_NeoPixel.h>
// ============================================================
// RGB LED — WS2812B
// ============================================================
#define RGB_PIN 48 // on-board WS2812B; try 38 if it doesn't respond
#define RGB_COUNT 1
Adafruit_NeoPixel strip(RGB_COUNT, RGB_PIN, NEO_GRB + NEO_KHZ800);
struct LedState {
bool on = false;
uint8_t r = 255;
uint8_t g = 255;
uint8_t b = 255;
uint8_t brightness = 128;
} led;
void applyLed() {
if (led.on) {
strip.setPixelColor(0, strip.Color(
(uint16_t)led.r * led.brightness / 255,
(uint16_t)led.g * led.brightness / 255,
(uint16_t)led.b * led.brightness / 255
));
} else {
strip.setPixelColor(0, 0);
}
strip.show();
}
// ============================================================
// WiFi AP
// ============================================================
const char* AP_SSID = "ESP32-S3-RGB";
IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);
// ============================================================
// DNS / Web Server
// ============================================================
const byte DNS_PORT = 53;
DNSServer dnsServer;
WebServer server(80);
// ============================================================
// Embedded page — HSV colour wheel + brightness slider
// ============================================================
static const char INDEX_HTML[] = R"html(
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>ESP32-S3 RGB Control</title>
<style>
:root{
--bg:#0d0d0d;--card:#1c1c1c;--text:#f0f0f0;
--muted:#666;--accent:#7c3aed;--r:14px;
}
*{box-sizing:border-box;margin:0;padding:0;}
body{
background:var(--bg);color:var(--text);
font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;
min-height:100vh;display:flex;flex-direction:column;
align-items:center;justify-content:center;padding:16px;
}
.card{
background:var(--card);border-radius:var(--r);
padding:24px 20px;width:100%;max-width:360px;
box-shadow:0 12px 40px rgba(0,0,0,.5);
}
h1{font-size:1.2rem;text-align:center;margin-bottom:16px;letter-spacing:.02em;}
/* ── Glow preview ── */
.prev-wrap{display:flex;justify-content:center;margin-bottom:14px;}
#preview{
width:80px;height:80px;border-radius:50%;
background:#111;border:3px solid #2a2a2a;
transition:background .1s,box-shadow .1s;
}
/* ── Colour wheel ── */
.wheel-wrap{display:flex;justify-content:center;margin-bottom:18px;}
#wheel{
border-radius:50%;
/* CSS size — scales the 280×280 canvas to fit the card */
width:min(280px,100%);height:min(280px,100%);
cursor:crosshair;touch-action:none;
}
/* ── Brightness slider ── */
.sg{margin-bottom:18px;}
.lbl{display:flex;justify-content:space-between;font-size:12px;color:var(--muted);margin-bottom:6px;}
.lbl b{color:var(--text);}
input[type=range]{
-webkit-appearance:none;width:100%;height:8px;border-radius:4px;outline:none;cursor:pointer;
background:linear-gradient(to right,#111,#fff);
}
input[type=range]::-webkit-slider-thumb{
-webkit-appearance:none;width:22px;height:22px;border-radius:50%;
background:#fff;box-shadow:0 2px 8px rgba(0,0,0,.5);
}
/* ── Toggle ── */
.tog{display:flex;justify-content:center;margin-top:4px;}
#toggleBtn{
width:170px;height:52px;border:none;border-radius:26px;
font-size:1rem;font-weight:700;cursor:pointer;
background:#2a2a2a;color:#666;
transition:background .2s,color .2s,box-shadow .2s,transform .1s;
}
#toggleBtn.on{background:var(--accent);color:#fff;box-shadow:0 4px 24px rgba(124,58,237,.55);}
#toggleBtn:active{transform:scale(.96);}
.status{text-align:center;font-size:11px;color:var(--muted);margin-top:14px;min-height:16px;}
footer{margin-top:16px;font-size:12px;color:var(--muted);text-align:center;}
</style>
</head>
<body>
<div class="card">
<h1>🏭 ESP32-S3 RGB Control</h1>
<div class="prev-wrap"><div id="preview"></div></div>
<div class="wheel-wrap">
<canvas id="wheel" width="280" height="280"></canvas>
</div>
<div class="sg">
<div class="lbl"><span>Brightness</span><b id="vBri">128</b></div>
<input type="range" id="slBri" min="0" max="255" value="128">
</div>
<div class="tog">
<button id="toggleBtn">Turn ON</button>
</div>
<div class="status" id="status">Connecting…</div>
</div>
<footer>📶 Connect to <b>ESP32-S3-RGB</b> · 192.168.4.1</footer>
<script>
// ── State ──────────────────────────────────────────────────────────────────
let hue = 0; // 0–360 (angle on wheel)
let sat = 0; // 0–1 (distance from centre)
let bri = 128; // 0–255
let isOn = false;
// ── HSV ↔ RGB helpers ───────────────────────────────────────────────────────
function hsvToRgb(h, s, v) {
const c = v * s, x = c * (1 - Math.abs(h/60 % 2 - 1)), m = v - c;
let r=0,g=0,b=0;
if (h<60) {r=c;g=x;}
else if (h<120) {r=x;g=c;}
else if (h<180) {g=c;b=x;}
else if (h<240) {g=x;b=c;}
else if (h<300) {r=x;b=c;}
else {r=c;b=x;}
return [Math.round((r+m)*255), Math.round((g+m)*255), Math.round((b+m)*255)];
}
function rgbToHsv(r,g,b) {
r/=255;g/=255;b/=255;
const mx=Math.max(r,g,b), mn=Math.min(r,g,b), d=mx-mn;
let h=0, s=mx?d/mx:0;
if (d) {
if (mx===r) h=((g-b)/d+6)%6;
else if (mx===g) h=(b-r)/d+2;
else h=(r-g)/d+4;
h*=60;
}
return [h, s, mx];
}
function baseRgb() { return hsvToRgb(hue, sat, 1); }
// ── Colour wheel — draw once to offscreen canvas ───────────────────────────
const canvas = document.getElementById('wheel');
const ctx = canvas.getContext('2d');
const SZ = canvas.width; // 280
const CX = SZ/2, CY = SZ/2, MAX_R = SZ/2 - 6;
const off = document.createElement('canvas');
off.width = off.height = SZ;
(function buildWheel() {
const oc = off.getContext('2d');
const id = oc.createImageData(SZ, SZ);
const d = id.data;
for (let y=0; y<SZ; y++) {
for (let x=0; x<SZ; x++) {
const dx=x-CX, dy=y-CY, dist=Math.hypot(dx,dy);
if (dist <= MAX_R) {
const h = ((Math.atan2(dy,dx)*180/Math.PI)+360)%360;
const s = dist/MAX_R;
const [r,g,b] = hsvToRgb(h, s, 1);
const i = (y*SZ+x)*4;
d[i]=r; d[i+1]=g; d[i+2]=b; d[i+3]=255;
}
}
}
oc.putImageData(id, 0, 0);
})();
// ── Render wheel + indicator circle ────────────────────────────────────────
function render() {
ctx.clearRect(0, 0, SZ, SZ);
ctx.drawImage(off, 0, 0);
const a = hue * Math.PI / 180;
const ix = CX + sat * MAX_R * Math.cos(a);
const iy = CY + sat * MAX_R * Math.sin(a);
const [r,g,b] = baseRgb();
// drop shadow for visibility over any hue
ctx.shadowBlur = 8;
ctx.shadowColor = 'rgba(0,0,0,0.7)';
ctx.beginPath();
ctx.arc(ix, iy, 15, 0, 2*Math.PI);
ctx.fillStyle = '#fff';
ctx.fill();
ctx.shadowBlur = 0;
// coloured fill
ctx.beginPath();
ctx.arc(ix, iy, 11, 0, 2*Math.PI);
ctx.fillStyle = `rgb(${r},${g},${b})`;
ctx.fill();
}
// ── Preview glow ────────────────────────────────────────────────────────────
function refreshPreview() {
const [r,g,b] = baseRgb();
const k = bri/255;
const col = `rgb(${Math.round(r*k)},${Math.round(g*k)},${Math.round(b*k)})`;
const el = document.getElementById('preview');
if (isOn) {
el.style.background = col;
el.style.boxShadow = `0 0 36px 10px ${col}`;
} else {
el.style.background = '#111';
el.style.boxShadow = 'none';
}
}
// ── Send to ESP32 ────────────────────────────────────────────────────────────
let t = null;
function sendUpdate() {
const [r,g,b] = baseRgb();
fetch(`/api/set?on=${isOn?1:0}&r=${r}&g=${g}&b=${b}&bri=${bri}`)
.then(x=>x.json())
.then(()=>{ document.getElementById('status').textContent='Updated \u2713'; })
.catch(()=>{ document.getElementById('status').textContent='Error\u2026'; });
}
function debSend() { clearTimeout(t); t=setTimeout(sendUpdate,80); }
// ── Wheel interaction ────────────────────────────────────────────────────────
function getPos(e) {
const rc=canvas.getBoundingClientRect();
const src=e.touches?e.touches[0]:e;
return {
x: (src.clientX-rc.left) * (SZ/rc.width),
y: (src.clientY-rc.top) * (SZ/rc.height)
};
}
function handlePick(e) {
e.preventDefault();
const {x,y} = getPos(e);
const dx=x-CX, dy=y-CY;
hue = ((Math.atan2(dy,dx)*180/Math.PI)+360)%360;
sat = Math.min(Math.hypot(dx,dy)/MAX_R, 1);
render();
refreshPreview();
debSend();
}
let drag = false;
canvas.addEventListener('mousedown', e=>{ drag=true; handlePick(e); });
canvas.addEventListener('mousemove', e=>{ if(drag) handlePick(e); });
window.addEventListener('mouseup', ()=>{ drag=false; });
canvas.addEventListener('touchstart', e=>handlePick(e), {passive:false});
canvas.addEventListener('touchmove', e=>handlePick(e), {passive:false});
// ── Brightness slider ────────────────────────────────────────────────────────
document.getElementById('slBri').addEventListener('input', function(){
bri=+this.value;
document.getElementById('vBri').textContent=bri;
refreshPreview();
debSend();
});
// ── Toggle ───────────────────────────────────────────────────────────────────
const btn = document.getElementById('toggleBtn');
btn.addEventListener('click', ()=>{
isOn=!isOn;
btn.textContent=isOn?'Turn OFF':'Turn ON';
btn.classList.toggle('on',isOn);
refreshPreview();
sendUpdate();
});
// ── Init ─────────────────────────────────────────────────────────────────────
render(); // show wheel with default indicator immediately
fetch('/api/status')
.then(r=>r.json())
.then(d=>{
isOn=d.on; bri=d.brightness;
document.getElementById('slBri').value=bri;
document.getElementById('vBri').textContent=bri;
[hue,sat]=rgbToHsv(d.r,d.g,d.b);
btn.textContent=isOn?'Turn OFF':'Turn ON';
btn.classList.toggle('on',isOn);
render(); refreshPreview();
document.getElementById('status').textContent='Ready';
})
.catch(()=>{ document.getElementById('status').textContent='Could not reach device'; });
</script>
</body>
</html>
)html";
// ============================================================
// JSON helper
// ============================================================
String buildStatusJson() {
return "{\"on\":" + String(led.on ? "true" : "false")
+ ",\"r\":" + String(led.r)
+ ",\"g\":" + String(led.g)
+ ",\"b\":" + String(led.b)
+ ",\"brightness\":" + String(led.brightness) + "}";
}
// ============================================================
// HTTP Handlers
// ============================================================
void handleRoot() { server.send(200, "text/html; charset=utf-8", INDEX_HTML); }
void handleStatus() { server.send(200, "application/json", buildStatusJson()); }
void handleSet() {
if (server.hasArg("on")) led.on = (server.arg("on") == "1");
if (server.hasArg("r")) led.r = constrain(server.arg("r").toInt(), 0, 255);
if (server.hasArg("g")) led.g = constrain(server.arg("g").toInt(), 0, 255);
if (server.hasArg("b")) led.b = constrain(server.arg("b").toInt(), 0, 255);
if (server.hasArg("bri")) led.brightness = constrain(server.arg("bri").toInt(), 0, 255);
applyLed();
server.send(200, "application/json", buildStatusJson());
}
void redirectToRoot() {
server.sendHeader("Location", "http://" + apIP.toString() + "/", true);
server.send(302, "text/plain", "");
}
void handleNotFound() { redirectToRoot(); }
void handleGenerate204() { handleRoot(); }
void handleHotspotDetect() { handleRoot(); }
void handleNCsi() { handleRoot(); }
void handleConnectivityCheck() { handleRoot(); }
// ============================================================
// SETUP
// ============================================================
void setup() {
Serial.begin(115200);
delay(500);
Serial.println("\n=== ESP32-S3 RGB Captive Portal ===");
strip.begin();
strip.setBrightness(255);
applyLed();
Serial.printf("WS2812B: GPIO %d\n", RGB_PIN);
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, netMsk);
WiFi.softAP(AP_SSID);
Serial.printf("AP: %s | IP: %s\n", AP_SSID, WiFi.softAPIP().toString().c_str());
dnsServer.start(DNS_PORT, "*", apIP);
server.on("/", handleRoot);
server.on("/api/status", handleStatus);
server.on("/api/set", handleSet);
server.on("/generate_204", handleGenerate204);
server.on("/hotspot-detect.html", handleHotspotDetect);
server.on("/ncsi.txt", handleNCsi);
server.on("/connectivity-check", handleConnectivityCheck);
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server + DNS captive portal started.");
Serial.println("===================================\n");
}
// ============================================================
// LOOP
// ============================================================
void loop() {
dnsServer.processNextRequest();
server.handleClient();
}