Beginner / 2–3 hours

Put a matrix controller in your browser

We've made the display respond to code and to a sensor. Now let's give it a control panel you can open on your phone.

PixelWing will join your Wi-Fi network and host a small web page. The browser sends a color whenever you move one of three sliders, and the board updates the matrix without reloading the page. This is a simple local HTTP controller: responsive enough for choosing colors, rather than a guaranteed timing system for streaming video.

Get onto the network

PixelWing ESP32-S3 does not include an antenna; buy and fit a compatible external antenna before starting. Use a 2.4 GHz Wi-Fi network with ordinary password access; a captive-portal network needs additional handling. Your phone or computer must be on the same local network, and that network must allow devices to talk to one another. Guest networks often isolate clients.

Create settings.toml at the root of CIRCUITPY, alongside code.py. Put your own network details in it:

WIFI_SSID = "your-network-name"
WIFI_PASSWORD = "your-network-password"

These are the custom setting names our program reads. Keep this file out of public repositories and screenshots. CircuitPython documents settings.toml environment variables, including how os.getenv() reads them.

Install the adafruit_httpserver folder and its dependencies from the bundle matching your firmware, along with the basic matrix libraries. wifi, socketpool, and os are built-in modules on the target firmware.

The complete controller

Replace code.py with this program. The HTML lives inside a Python string, so there isn't a second web file to copy:

import os
import time
import board
import neopixel
import socketpool
import wifi
from adafruit_httpserver import Server, Request, Response, POST

pixels = neopixel.NeoPixel(
    board.NEOPIXEL, 50, brightness=0.05,
    auto_write=False, pixel_order=neopixel.GRB
)
pixels.fill((0, 0, 0))
pixels.show()

PAGE = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PixelWing color control</title>
<style>
body { font: 1.2rem system-ui; max-width: 32rem; margin: 2rem auto;
       padding: 1rem; background: #202124; color: white; }
label { display: block; margin-top: 1.5rem; }
input { width: 100%; min-height: 44px; }
button { padding: .8rem 1.2rem; margin-top: 1rem; font: inherit; }
</style>
</head>
<body>
<h1>PixelWing color control</h1>
<p>Move a slider to change the matrix.</p>
<label for="r">Red</label>
<input id="r" type="range" min="0" max="255" value="0">
<label for="g">Green</label>
<input id="g" type="range" min="0" max="255" value="0">
<label for="b">Blue</label>
<input id="b" type="range" min="0" max="255" value="0">
<button id="off" type="button">Turn off</button>
<p id="status" role="status">Ready</p>
<script>
const sliders = ['r', 'g', 'b'].map(id => document.getElementById(id));
const status = document.getElementById('status');
let pending = null;
let busy = false;
function queueColor() {
  pending = sliders.map(slider => slider.value).join(',');
}
sliders.forEach(slider => slider.addEventListener('input', queueColor));
document.getElementById('off').addEventListener('click', () => {
  sliders.forEach(slider => { slider.value = 0; });
  queueColor();
});
setInterval(async () => {
  if (busy || pending === null) return;
  const color = pending;
  pending = null;
  busy = true;
  try {
    const response = await fetch('/color', {
      method: 'POST',
      headers: {'Content-Type': 'text/plain'},
      body: color,
      signal: AbortSignal.timeout(3000)
    });
    if (!response.ok) throw new Error('Request failed');
    status.textContent = 'Color: ' + color;
  } catch (error) {
    status.textContent = 'Connection lost. Move a slider to retry.';
  } finally {
    busy = false;
  }
}, 100);
</script>
</body>
</html>"""

ssid = os.getenv("WIFI_SSID")
password = os.getenv("WIFI_PASSWORD")
if not ssid or not password:
    raise ValueError("Set WIFI_SSID and WIFI_PASSWORD in settings.toml")

print("Connecting to Wi-Fi...")
wifi.radio.connect(ssid, password)
pool = socketpool.SocketPool(wifi.radio)
server = Server(pool, debug=False)

@server.route("/")
def home(request: Request):
    return Response(request, PAGE, content_type="text/html")

@server.route("/color", POST)
def set_color(request: Request):
    try:
        parts = request.body.decode("utf-8").split(",")
        if len(parts) != 3:
            raise ValueError("Expected three channels")
        color = tuple(int(part) for part in parts)
        if any(channel < 0 or channel > 255 for channel in color):
            raise ValueError("Channel out of range")
    except (ValueError, UnicodeError):
        return Response(request, "Use r,g,b values from 0 to 255", status=(400, "Bad Request"))

    pixels.fill(color)
    pixels.show()
    return Response(request, "OK", content_type="text/plain")

address = str(wifi.radio.ipv4_address)
server.start(address, port=80)
print("Open http://" + address + "/ in your browser")

while True:
    server.poll()
    time.sleep(0.01)

Try it

Open the serial console and wait for the printed address, such as http://192.168.1.123/. Use the address your board actually prints, including http://. Open it on a device on the same network. Move red up first, then add some green. The matrix should follow your choices. Turn off should return all three sliders to zero and clear the LEDs.

The browser starts with zeroed sliders. Reloading the page doesn't read the current LED color back from the board; move a slider or press Turn off to send a new state. The display keeps its last color if the browser disconnects.

How the pieces fit

A route connects a URL to a Python function. Opening / returns the web page. The page's JavaScript sends a POST request to /color containing three comma-separated numbers. Python checks the channel count and range before updating the LEDs. Invalid input gets HTTP status 400 instead of reaching the display.

The browser keeps only the newest unsent color and allows one request at a time. That prevents a quick slider movement from building a long queue of stale colors. The 100-millisecond timer offers up to roughly ten updates a second, with actual speed depending on the network and board. If a request times out, moving a slider sends another update.

server.poll() gives the server a chance to handle requests. Keep the main loop short: a long sleep or blocking animation would make the controls feel sluggish. Adafruit's HTTPServer examples demonstrate starting and polling a server; its API reference documents requests, responses, and routes.

This example gives devices on your local network access to the controller without a login. Use it on a trusted network and keep it local; it isn't configured for public internet access. Two open controllers can both send colors, and the most recent request wins.

When the page won't connect

You've now got the pieces for a connected indicator: a display, a way to read the world, and a way to tell the board what you want. Try turning the browser controls into a choice between a sensor view and an animation. Give each mode one drawing function and let your main loop decide which one runs.

That's where this little matrix gets interesting. The hardware is already together. What it has to say is up to you.

Back to the PixelWing introduction.