# Uncle Magic's Liquid Turntable

*(Repository name: `LiquidTurntable`. Default network name: `liquidturntable`.)*

BPM-synced motorized turntable controller: ESP32-S3-ETH driving a NEMA17 stepper
through a TMC2209 driver, taking tempo from OSC (with local tap-tempo fallback),
and driving an SK9822 (APA102-type) LED ring itself with an in-firmware LED
engine. Successor to the Arduino Mega 2560-based
[MegaMagicTurntable](https://github.com/scoobiekw/MegaMagicTurntable) — same
motor-control behavior, ported to ESP32 for onboard Ethernet, dual-core
headroom, and a web config UI.

This file describes the current design: firmware behavior, pinout, and the
OSC/HTTP API. For the mainboard's electrical design the KiCad schematic is
authoritative — see [Hardware](#hardware) below. How the design got here is in
[CHANGELOG.md](CHANGELOG.md).

## Hardware

Three physical pieces:

- **Main board** — one PCB carrying the ESP32-S3-ETH (Waveshare, onboard
  W5500 Ethernet) and a BigTreeTech TMC2209 stepper driver module. **One chip does everything**, including the LED
  ring (in-firmware LED engine, `src/ledengine.h`). The logic runs directly off 3.3V: the TMC2209's VIO is rated
  3.3–5.5V, so STEP/DIR/ENN/UART wire straight to the ESP32's GPIOs. The only
  level shifters are `U3` and `U5`, two 74AHCT1G125s that lift the ring's data (GPIO18) and clock (GPIO2) from
  3.3V to 5V for the SK9822 ring; `R26` and `R62` (10k to GND) hold their inputs low while
  the ESP32 boots, so the ring stays dark at power-on. Rotary encoders and buttons wire directly to this board too,
  via bare-wire fanout headers — there's no separate Encoder Panel PCB.
- **LED ring** — 178× SK9822-A (APA102-type: data and clock, 27 kHz PWM, so it films without flicker) in an offset/brick matrix on a 203 × 203mm two-layer board. At the full current field (31) full white would be about 9.6A; the firmware holds each LED to 36.6 mA (the maker's field-22 level) and the ring to about 4.5A. Its own KiCad project, part of this repo at [`kicad_led_ring_offset/`](https://github.com/scoobiekw/LiquidTurntable/tree/main/kicad_led_ring_offset) — 0 DRC/0
  ERC violations, routed, with a `jlc_export/` folder ready for fab. Two
  earlier comparison layouts (square grid, true hex — never fully routed,
  superseded by this offset/brick one) remain in the sibling
  [MegaMagicTurntable](https://github.com/scoobiekw/MegaMagicTurntable) repo
  for reference, not part of the build. Two cables join it to the mainboard: data, clock and the ring thermistor on `J2` (JST XH 5-pin:
  DATA, GND, CLK, GND, NTC) to the mainboard's `J-LED-SIG`, and power on `J1`, a JST VH 4-pin
  side-entry header (B4PS-VH, [LCSC C157996](https://www.lcsc.com/product-detail/C157996.html)),
  matching the mainboard's `J5` pin-for-pin (both double up +5V and GND
  across 2 pins each, same pin-number-to-net order) — a straight-through
  4-conductor harness (JST VHR-4N housings with SVH-41T-P1.1 crimps, 16-18 AWG, on both ends) connects
  them directly; no crossed wiring or adapter needed. The LED ring board
  is mounted near the top of the case and does **not** spin with the
  platter. Right-angle was chosen over the mainboard's vertical style
  specifically for the ring board — low-profile, side wire-entry to fit
  that mounting location, where a tall vertical header would have less
  clearance to work with.
- **NEMA17 stepper**, direct-coupled to the load through a flexible shaft
  coupler, no gearbox.

**Source of truth for the mainboard's schematic:**
[`kicad_mainboard/Mainboard.kicad_sch`](https://github.com/scoobiekw/LiquidTurntable/blob/main/kicad_mainboard/Mainboard.kicad_sch)
(rendered as `Mainboard_schematic.pdf`), with this README for pinouts, module
orientation and wiring. There is no separate block diagram or planning
document: the schematic and this README are the whole description.

The schematic is hierarchical. `Mainboard.kicad_sch` is a one-page index with one sheet per
function:

| Sheet | File | Contents |
|---|---|---|
| Power | `power.kicad_sch` | `J-PWR-5V`, `J-PWR-12V`, `F1` (resettable fuse), `D1`, TVS, bulk caps, `Q5` (no 3.3V regulator: the module makes `+3V3`) |
| Controller | `controller.kicad_sch` | ESP32-S3-ETH sockets (`J1-H1`/`J1-H2`), boot-strap pull-up `R23` (ENABLE) |
| Motor | `motor.kicad_sch` | TMC2209 carrier sockets, UART resistor `R9`, motor connector |
| LED | `led.kicad_sch` | `U3`/`U5` 74AHCT1G125 data and clock buffers, `D33` feeding them (`+5V_LED_LOGIC`), ring signal connector `J-LED-SIG` (with the ring NTC input `D34`/`R65`/`R66`/`C16`), ring power connector `J5`, fan header `J-FAN` with its PWM inverter `Q6` |
| Panel IO | `panel_io.kicad_sch` | TCA9555 `U1`, I2C pull-ups, encoder and tap-button headers |
| Test points | `testpoints.kicad_sch` | `TP1` to `TP12`, probe pads on the rails and a few signals (see [Test points](#test-points)) |

On each sheet, parts are joined by wires. `GND` and `+3V3` use power symbols at every pin. The
two other rails (`+12V_MOTOR`, `+5V_LED_RING`) use project rail symbols from
`Mainboard_power.kicad_sym`, which `sym-lib-table` registers. Global labels carry signals between
sheets. They also mark the ESP32-S3-ETH pins, so each header pin's label shows which GPIO goes
where.

### Power rails

Two rails are externally fed (from a single Mean Well RD-85A 5 V / 12 V supply, or any separate 12 V and 5 V supplies, arriving via `J-PWR-5V` and `J-PWR-12V`); the third (`+3V3`) is
made by the ESP32-S3-ETH module from the 5 V rail. The 12 V rail has its own fuse (`F1`). The 5 V rail has a 7.5 A blade fuse in the harness (see the note under the table). Reverse polarity is prevented by the keyed Mini-Fit Jr connector, by `D1` on the motor rail and by `Q5`, a P-channel FET in the 5 V ring line, and the 5 V input has no overvoltage crowbar (removed 2026-10-21; the harness is metered before it meets the board):

| Rail | Feeds | Protection |
|---|---|---|
| `+12V_MOTOR` | TMC2209 VM + NEMA17 + the fan header `J-FAN` (~0.1A) | `F1` fuse + `D1` Schottky; `C8` + `C11` 2×100µF/35V bulk caps at the TMC2209's VM pin; `D5` SMBJ15A TVS across the rail; `R27` 4.7kΩ bleeder across the caps |
| `+5V_LED` | LED ring (`+5V_LED_RING`, held to about 4.5A by the LED engine's limits) and, through `D33`, `+5V_LED_LOGIC`: the two LED buffers and the module's `VSYS` (so all of the 3.3V logic) | 7.5 A inline blade fuse in the harness (see the note under the table); `Q5` reverse-polarity FET, `D32` TVS (SMBJ5.0A) |
| `+3V3` | ESP32-S3-ETH, TMC2209 VIO, TCA9555 — every logic IC on the board except the two 5V LED buffers — plus all 7 encoder headers' pull-up supply pin (see [connectors](#connectors-main-board)) and the ring NTC pull-up `R65` | the module's JW5060 buck limits its own current; `D4` is ESD protection only (PESD3V3S1UL: breakdown 5.2V min, 150W), so it does **not** protect the 3.6V-abs-max parts from a regulator fault |

**The 5 V fuse.** The RD-85A's overload protection is 110 to 150% of total rated power (88 W), which on the 5 V output is roughly 20 A or more, and the current-range figures differ between datasheet copies ([Mean Well RD-85 datasheet](https://meanwellaustralia.com.au/sites/default/files/2025-01/MEAN%20WELL%20RD-85%20DATA%20SHEET.pdf)). That protects the supply, not the wiring, so the 5 V harness has one 7.5 A ATO blade fuse in an inline holder at the supply's +V1 terminal, before the lead splits into the two wires to `J-PWR-5V`. The normal load is about 4.6 A. It blows on a short in the harness, the connectors or either board, and it is why the ring can be ordered at 1 oz copper. It is not the ring's current limit: that is the LED engine (about 4.5 A; see [LED engine](#led-engine)), and the 9.6 A of an unlimited full white is too little over 7.5 A to blow it quickly.

`+3V3` source: **the ESP32-S3-ETH module's own regulator.** On the module (confirmed against
Waveshare's official schematic), USB VBUS reaches `VSYS` through a 1N4148 (`D1` on the module), and `VSYS` feeds a
JoulWatt JW5060 buck (4-18V input, 3A, fixed 3.3V) whose enable pin, `3V3_EN`, is pulled up to `VSYS` by the module's
`R67` (10kΩ). This board feeds `VSYS` (`J1-H1` pin 2) from `+5V_LED_LOGIC` (the 5V input through `D33`, about 4.7V),
leaves `3V3_EN` (pin 4) open so the buck runs, and takes `+3V3` from the module's `3V3` pin (pin 5) for everything else:
the TMC2209's VIO, the TCA9555, the encoder pull-ups and the ring NTC's pull-up.


Using the module's buck instead saves about $2.40 to $3.40 a board and the part with the least stock, and lets the
module's USB-C power the logic for flashing. What changed with it:

- **The logic needs the 5V supply** (or USB). 12V now feeds only the TMC2209's motor side and the fan.
- **With 12V on and 5V off**, the TMC2209 has VM but no VIO. Its datasheet holds the logic in reset with the bridges off
  below the VIO threshold; check it once on the bench.
- **USB and the 5V supply together:** the 5V supply wins (about 4.7V on `VSYS` against USB's 4.3V after the module's
  1N4148), and the 1N4148 keeps our 5V off the USB host.
- **Headroom:** the ESP32 and the W5500 draw about 400-500mA typical with Wi-Fi peaks a few hundred mA higher; the buck
  is rated 3A. The firmware still caps the main board's Wi-Fi transmit power at 15dBm (see [OSC API](#osc-api)).
- A fixed-output regulator still feeds the 3.6V-abs-max logic, as before (no trimpot module).

**Encoder pull-up supply.** All 7 panel-encoder headers (`J-ENC-MAIN`/`HUE`/`SAT`/`VAL`/`EXP1`-`EXP3`)
run their KY-040 modules' onboard CLK/DT/SW pull-up resistors off `+3V3`, not `+5V_LED`. Those
lines wire directly — no divider, no level shifter — into native ESP32-S3 GPIOs or the
`+3V3`-powered TCA9555 expander, all 3.3V-only inputs with an absolute maximum of about 3.6V, so
a 5V pull-up supply would put ~5V on every idle line. KY-040 modules are purely passive
(resistors and switches), so the supply voltage changes nothing about signal behavior. The LED
ring has its own `+5V_LED_RING` branch, so nothing else on the board uses `+5V_LED`.

**ESD protection on the panel headers.** Every signal pin of the panel headers (21 lines: CLK and DT of the seven encoders, SW of the six that have one, plus `TAP_BTN`) has a protection cell between the connector and the board: a
1kΩ series resistor (0402) and a PESD3V3S1UL TVS diode (SOD-882) to GND on the connector side of the
resistor. The TVS clamps a static discharge on the panel wiring before it reaches the resistor, and
the resistor limits what is left into the ESP32-S3 / TCA9555 pin. Each encoder header's `+3V3` pin is
fed through a 100Ω resistor so a shorted panel wire can't pull the 3.3V rail down. The 5V ring supply
has an SMBJ5.0A TVS (`D32`) across `+5V_LED_RING` and GND next to `J5`. The cells sit directly under
each header on the front copper; nets on the connector side of a resistor carry a `_J` suffix
(`ENC_CLK_J`) and the board side keeps the plain name. The pins draw only nanoamps of input current, so the 1kΩ adds no measurable level shift, and with a few pF of pin and trace capacitance it is a time constant of a few ns, far faster than any encoder edge.

### Mains input and power-on

The supply is a single **Mean Well RD-85A** (5 V / 12 V, 88 W) behind one fused, switched
IEC inlet, so there is a single power switch and the DC harness on `J-PWR-5V` and `J-PWR-12V`
is permanent. Notes for that arrangement:

- **Fuse and switch.** Use a **slow-blow (T-type)** fuse in the inlet, about T3.15A
  at 120V or T2A at 230V (the RD-85A draws 2.5A at 115VAC and 1.5A at 230VAC at full load). Its cold-start
  inrush is 50A at 230VAC for a few ms, which nuisance-blows a fast fuse. Steady-state draw is
  ~100–110W at full load. Use a switch rated ≥10A. If the fuse or switch still complains,
  add one NTC inrush limiter in the live line after the switch.
- **12V supply.** The motor rail runs at 12V: at this turntable's speeds the motor needs only
  a few volts, and 12V leaves the TMC2209 (29V limit) a wide margin. `D5` (SMBJ15A) starts to conduct at about 16.7V and
  clamps at about 24.4V at its rated surge current, below the TMC2209, the 35V bulk caps `C8`/`C11`. Use a
  regulated 12V supply; if it is adjustable keep it between 12 and 13V. The fan on `J-FAN` runs straight off this rail.
- **Supply: Mean Well RD-85A.** The chosen supply is a single Mean Well RD-85A (5 V / 12 V, 88 W): 5 V for the ring, 12 V for the rest, shared ground.
  It is rated 8 A and 4 A (usable ranges 10 A and 5 A within 88 W), with no minimum load. Do not buy the RD-85B (24 V). Wiring, the
  5 V trim and the datasheet notes are in [HARDWARE_OVERVIEW.md](../HARDWARE_OVERVIEW.html#the-supply-mean-well-rd-85a). Two separate supplies
  (LRS-75-5 and LRS-35-12) also work and give the ring more current.
- **Never plug or unplug `J-PWR-5V` or `J-PWR-12V` with mains on.** With the supply cable
  permanent, hot-plug spikes (see `D5`) are no longer a concern.
- **Never connect or disconnect the motor (`J3`), the ring cable (`J5`) or a plug-in module with
  power on.** A motor unplugged live makes a voltage spike that can destroy the TMC2209 (BigTreeTech
  says the same about the module), and the ring cable carries up to about 11A. `D5` is not
  sized for this.
- **Rail order.** `+3V3` comes from the 5V rail (through `D33` and the module's buck), so the LED buffers and
  the logic come up together, and `R23` holds the TMC2209 disabled through boot. The 12V rail can arrive at any
  time; without 5V the TMC2209 has no VIO and its logic stays in reset. On USB alone the buffers see about 4.3V,
  below the 74AHCT's 4.5V rating, but the ring has no power then, so it doesn't matter.
- **LED ring at power-on.** `R26` and `R62` (10k to GND, at `U3`'s and `U5`'s inputs) keep
  data and clock low while the ESP32 boots and GPIO18/2 float, so the ring keeps what it shows at power-up
  (SK9822s start dark) until the LED engine's first frame.
- **Quick off-on.** The 12V side (`C8`+`C11`, ~200µF) has almost no load once the motor stops, so it used to
  linger at a few volts. `R27`, a 4.7kΩ bleeder across `C8`/`C11`, ends that tail: τ ≈ 0.9s, so the rail is
  under ~1V within ~2.5s.
  It draws ~2.5mA (~0.03W) at 12V. A 1–2kΩ
  value would drain faster but needs a 1W part; it isn't worth the board space.
  Still wait ~3s before switching back on.
- **Safety.** Bond the earth pin to any metal case or PSU chassis (not needed
  for enclosed Class II bricks), sleeve or shroud all mains terminals, and keep
  mains creepage away from the low-voltage board. The DC rails are already
  fused on the board (`F1`, on the 12 V side; the 5 V side is not fused). If Ethernet is flaky with the supply
  running, suspect common-mode noise from it first.

### Connectors (Main Board)

| Ref | Part | Pins |
|---|---|---|
| `J1-H1` / `J1-H2` | ESP32-S3-ETH socket, real `H1`/`H2` rows (1×20 each) | 17 of `H1`'s 20 wired, 12 of `H2`'s 20 — GND, +3V3, LED_DATA_3V3/LED_CLK_3V3, TMC_UART_RX/TX, ENABLE, DIR, STEP, ENC_CLK/DT/SW, I2C_SDA/SCL, HUE_CLK/DT, SAT_CLK/DT, VAL_CLK/DT, TAP_BTN — see [firmware pinout](#firmware-pinout) for GPIO numbers |
| `J2-MODE` / `J2-MOTOR` | TMC2209 header, real two-row layout (1×08 each) | `J2-MODE`: EN→ENABLE, MS1/MS2/CLK→GND, PDN(×2, both pins)→TMC_UART_RX, STEP, DIR. `J2-MOTOR`: VM→+12V_MOTOR, GND(×2), coils A2/A1/B1/B2, VIO→+3V3 |
| `J3` | NEMA17 motor (JST-XH 4-pin) | Standard stepper order: 1 A+ (`MOTOR_COIL_A1`), 2 A− (`A2`), 3 B+ (`B1`), 4 B− (`B2`). Pins 1+2 are one coil, 3+4 the other. Matches StepperOnline's 17HS08-1004S (black, green, red, blue) and ready-made printer stepper cables; silkscreened A+ A− B+ B− |
| `J5` | LED ring power (JST VH 4-pin, vertical, `B4P-VH`, C160317) | 1-2 `+5V_LED_RING`, 3-4 GND (10A per pin with 16 AWG); straight through to the ring's `J1` (B4PS-VH) with a VHR-4N cable (SVH-41T-P1.1 crimps, 16-18 AWG) |
| `J-LED-SIG` | LED ring signal (JST XH 5-pin, `B5B-XH-A`, C157991) | 1 `LED_DATA_OUT` (5V data from `U3` through 33Ω `R63`), 2 GND, 3 `LED_CLK_OUT` (5V clock from `U5` through `R64`), 4 GND, 5 `NTC_RING_J` (the ring's `TH1`: `D34` ESD clamp and `R65` 10k 1% pull-up to `+3V3` here, then `R66` 1k and `C16` 100nF to GPIO3, `RING_TEMP`); straight through to the ring's `J2` with an XHP-5 cable |
| `J-ENC-MAIN` / `J-ENC-HUE` / `J-ENC-SAT` / `J-ENC-VAL` | Encoder headers (1×05) | Signals present: GND, CLK, DT, SW, `+3V3` — **not physical pin order**, see below. `+3V3` (**required** — these are KY-040 modules; their onboard pull-ups need a supply to produce clean CLK/DT/SW at all. Runs off `+3V3`, not `+5V_LED` — CLK/DT/SW wire straight into native 3.3V-only ESP32-S3 GPIOs with no divider/level-shifter, so a 5V pull-up supply here would put ~5V on a 3.3V-only input) |
| `J-BTN-TAP` | Tap tempo button (1×02) | GND, TAP_BTN |
| `J-FAN` | **4-wire 12V** fan (keyed 1×04, KK254 style); do not fit a 5V fan | 1 GND, 2 +12V (straight from `+12V_MOTOR`, after `F1` and `D1`), 3 tach (`FAN_TACH_J`, through `R59` 4.7k to the expander's `P0_6`), 4 PWM (`FAN_PWM_OUT`, the drain of `Q6`). Standard 4-wire fan pinout. Silkscreened G + T P and *12V FAN* |
| `J-ENC-EXP1`-`J-ENC-EXP3` | Expansion encoder headers (1×05 each) | Signals present: GND, CLK, DT, SW, `+3V3` — **not physical pin order**, see below. Same rationale as the 4 main encoders, but wired through the I2C expander (`U1`), see below (`U1` is itself a `+3V3` part, same overvoltage reasoning applies). `J-ENC-EXP3` has CLK and DT only (no SW channel) |
| `J-PWR-5V` | 5V input (Molex Mini-Fit Jr 2×2, 4-pos) | pins 1 and 3 `+5V` (doubled for the ring's current path), pins 2 and 4 GND — wired ahead of the fuses, to `+5V_LED_PSU` |
| `J-PWR-12V` | 12V input (JST XH 2-pin, `B2B-XH-A`, 3A) | pin 1 `+12V`, pin 2 GND — wired ahead of `F1`, to `+12V_MOTOR_PSU`. A different connector family from `J-PWR-5V` on purpose: a 12V plug cannot go into the 5V header |

No dedicated direction-change button — the speed encoder ramps through
zero and reverses on its own; OSC `/directionChange` covers the rare
remote-only case.

**`J1` is a real socket, not a generic connector.** The
ESP32-S3-ETH is a devkit-style board with a
real double row of header pins, and it is **fully socketed** —
pulled straight from the module's own real pinout (Waveshare's official
schematic),
not a made-up sequential connector, so a real module's female-header rows
actually plug in correctly and unused pins land on genuinely unused real
pins. `J2` (TMC2209) is the same idea at a smaller scale: two real 8-pin
rows (`J2-MODE`, `J2-MOTOR`), verified against
[global.bttwiki.com/TMC2209.html#pinoutfunction](https://global.bttwiki.com/TMC2209.html#pinoutfunction)
— this module has only **2** GND pins (one per row);
`DIAG`/`VREF`/`INDEX`
are separate solder points on the module, not part of either header row,
and aren't brought to this board at all. Each of these connectors'
`Value` property in the schematic documents exactly which pins are wired
and which real pins were left NC, pin by pin.

**Which way up the modules go (checked against the vendors' drawings and
pinout diagrams):**
- **ESP32-S3-ETH: RJ45 side up**, USB-C/RJ45 end at the board's top edge.
  From that side, the VBUS/VSYS/3V3/GPIO43 column (Waveshare pins 40..21 =
  `J1-H1`) is on the **right** (x=54.78) and GPIO20..GPIO33 (pins 1..20 =
  `J1-H2`) on the left (x=37). The module is 72.8 × 21mm and overhangs the
  board edge by ~16mm. The RJ45, magnetics and ESP32-S3 are on the up side;
  the USB-C, W5500 and microSD are underneath. Its far end clears the TMC2209
  module by ~1.4mm.
- **TMC2209:** StepStick orientation **rotated 180° from the usual drawing**: EN and VM at the
  **bottom** (the panel-header edge of the board), EN column on the **right**, VM column on the left. The silkscreen
  labels `EN` and `VM` mark the pin-1 end. Check this against the module's own silkscreen before inserting it; a
  reversed module puts VM on the wrong pin and will destroy it.

The silkscreen marks each one. Plugging the ETH module in RJ45-side-down
still fits the sockets but mirrors every pin, so don't.

**All 7 encoder headers' real physical pin order (verified against the PCB
footprint, not just the schematic label) is `pin1=+3V3, pin2=SW, pin3=DT,
pin4=CLK, pin5=GND`** — the reverse of the "GND, CLK, DT, SW, +3V3" order
the signal list above and each header's `Value` text are written in. That
list is which signals are present, not left-to-right pin order; hand-wire
a panel harness off the real footprint/silkscreen (or a multimeter), not
by reading the prose order.

Panel wiring color code (bare-wire fanout to panel-mounted controls): Main
encoder = blue, Hue = red, Saturation = green, Value = yellow, buttons =
orange, GND = black throughout.

### Test points

Twelve probe points, each silkscreened with what it carries, on copper of its own net (`testpoints.kicad_sch`, `TP1` to `TP12`; not in the BOM or placement files).
The three GND loops take a scope-ground clip; the rest are pads for a probe or a hook. None is under a plug-in module.

| Label | Net | Where |
|---|---|---|
| GND (three loops) | `GND` | top, right of the `J1-H1` socket; top left beside `F1A`; beside `EN` |
| 12V | `+12V_MOTOR` | left, beside `D1` |
| 12V F1 | `+12V_MOTOR_F1` | right of `D1`, after `F1` |
| 3V3 | `+3V3` | right of the ESP32-S3-ETH socket |
| 5V | `+5V_LED_RING` | left, above `J5`, after `Q5` |
| DAT 3V3 | `LED_DATA_3V3` | right of the module: GPIO18, the ring data before `R18` |
| SCL, SDA | `I2C_SCL`, `I2C_SDA` | SCL below DAT 3V3; SDA at the right edge |
| EN | `ENABLE` | beside `R23` (low = TMC2209 on) |
| DAT, CLK | `LED_DATA`, `LED_CLK` | in the LED block right of the module: 3.3 V data and clock at the `U3`/`U5` inputs |

`STEP`, `DIR` and the TMC2209 UART lines run only under the plug-in modules, so they have no pad: probe them on the module's own pins.
`kicad_mainboard/tools/add_test_points.py` places the pads and records why each spot was chosen.

### I2C GPIO expander (`U1`, TCA9555)

`J1` has only 40 header pins, and every non-strapping, non-reserved one of them is spoken for (see
the [firmware pinout](#firmware-pinout)), so the main, hue, value and saturation encoder buttons and the
expansion headers go through a TCA9555PWR I2C GPIO expander (`U1`, TSSOP-24, LCSC C465732; UMW C42420608 is an
alternate; address `0x20`, A0/A1/A2 tied to GND) instead of native GPIOs. The firmware also drives an MCP23017 at the same
address (older boards, the breadboard), whose port A and port B are port 0 and port 1 here. The buttons are on `P0_0` (hue), `P0_3` (main encoder,
so GPIO3 is free for the ring thermistor), `P0_5` (value) and `P1_5` (saturation).
The bus is `I2C_SDA` on GPIO17 and `I2C_SCL` on GPIO16 (neither is a strapping pin). `R21`/`R22` (4.7kΩ) pull the bus up
to `+3V3` and run at 400 kHz; `~INT` is unconnected (no free GPIO on the module's header, and 2 ms polling does its job,
see below); the TCA9555 has no reset pin.

Eight more channels feed three expansion encoder headers: `J-ENC-EXP1` (SW/DT on `P0_1`/`P0_2`, CLK on
`P1_6`), `J-ENC-EXP2` (SW/DT/CLK on `P1_3`/`P1_2`/`P1_4`) and `J-ENC-EXP3` (CLK/DT only, on `P1_1`/`P1_0`).
`P0_6` takes the fan tach. `P0_4`, `P0_7` and `P1_7` are unconnected spares. A task of its own (`expanderTask()` in
`panel.cpp`, core 1, priority 2) reads both input ports in one transaction every 2 ms, about 0.15 ms of bus time each,
and is the bus's only user after `setup()`. It decodes the three expansion encoders from those samples (logged as
EXP1 picks the palette, EXP2 sets the effect speed, EXP3 is only logged) and timestamps fan tach edges; `loop()` runs the four
buttons' logic on the latest sample every 20 ms, as before. Every
channel is an input (the power-on default; the firmware writes it anyway) with the chip's fixed 100kΩ pull-up, so
unplugged channels don't float and a KY-040's `SW` (no pull-up on the module) works. The main button's 30 ms debounce
works on those 20 ms looks. A 2 ms sample follows an expansion encoder up to about 125 clicks a second (one sample per
quadrature step, four per KY-040 click); the old 20 ms read lost steps above about 12. The four main encoders stay on
native GPIO interrupts, which have no such limit.

## Firmware pinout

All defined in [`src/pins.h`](https://github.com/scoobiekw/LiquidTurntable/blob/main/src/pins.h).

| GPIO | Signal | Notes |
|---|---|---|
| 46 | `stepPin` | → TMC2209 STEP (strapping pin, low at reset — see note below) |
| 0 | `enablePin` | → TMC2209 ENN (active-LOW, see `setEnable()`; strapping pin, `R23` holds it high so the driver is off through boot) |
| 48 | `dirPin` | → TMC2209 DIR |
| 9–14 | ETH_PHY_RST/IRQ/CS, SPI SCK/MISO/MOSI | Onboard W5500, fixed by the Waveshare module |
| 21 | `tapBtnPin` | Tap-tempo button (GPIO21 also drives the module's onboard RGB LED, so it carries only this rarely used input) |
| 38/39 | `encoderPinA`/`encoderPinB` | Main (speed) encoder CLK/DT (its button is on the I2C expander, `P0_3`) |
| 1/40 | `hueEncoderPinA`/`hueEncoderPinB` | Hue encoder (its button is on the I2C expander) |
| 3 | `RING_NTC_PIN` | Ring temperature, ADC1_CH2: `J-LED-SIG` pin 5 through `R66` (1kΩ) and `C16` (100nF), pulled up by `R65` (10kΩ 1%) at the connector |
| 43/44 | `satEncoderPinA`/`satEncoderPinB` | Saturation encoder (UART0 pins, boot-log output on GPIO43 — see below; its button is on the I2C expander too, `P1_5`) |
| 41/42 | `valEncoderPinA`/`valEncoderPinB` | Value/brightness encoder (its button is on the I2C expander too) |
| 47/15 | `tmcUartTxPin`/`tmcUartRxPin` | TMC2209 single-wire UART (TX joined to RX through a 1kΩ resistor) |
| 18/2 | LED engine `dataPin`/`clockPin` | LED ring data and clock (SPI3 for the SK9822; RMT on 18 for a WS281x ring), through `U3`/`U5` to `J-LED-SIG`. Settings on the LEDs tab |
| 45 | `fanPwmPin` | Fan PWM (25kHz). Drives the gate of `Q6` through `R57`; `R58` pulls the gate low. Strapping pin, see below |
| 17/16 | `i2cSdaPin`/`i2cSclPin` | I2C bus to the TCA9555 expander (`U1`) — carries the main, hue, value and saturation buttons, the fan tach and the expansion headers' I/O |

**GPIO0/45/46 are strapping pins, used here deliberately as outputs.** Waveshare's H1/H2 header simply
doesn't expose enough non-strapping, non-reserved GPIOs for this design:
GPIO4/5/6/7/8 (the "obvious" choices) don't reach the header at all —
confirmed against Waveshare's real ESP32-S3-ETH schematic, they're wired
only to onboard peripherals (RGB LED mux, microSD, camera power switch).
GPIO33-37 are hard-reserved for octal PSRAM on this `ESP32-S3R8` module
(not just "avoid if possible" — actually unusable). GPIO19/20 drive the
chip's native USB-Serial-JTAG, needed to reflash/monitor over the onboard
USB-C port. GPIO3 (a strap only once the JTAG-source eFuses are burned,
which they aren't on this module) is the ring thermistor's ADC input; `R65` pulls it up at reset, which changes nothing. The
three strapping pins in use (0 ENABLE, 45 fan PWM, 46 STEP) are all
*outputs*, driven by firmware only after boot completes.

**Boot straps.** The ESP32-S3 reads these pins at reset:
- **GPIO0** must be high, or the chip enters download mode. The module has
  only a BOOT button on it, no pull-up, so it relies on the chip's weak
  (~45k) internal pull-up. Even a 100k pull-down on a TMC carrier's pin
  would drag it to about 2.3V, below the 2.5V "high" threshold.
  **`R23` (1k to +3V3) holds ENABLE/GPIO0 firmly high** — which also leaves
  the TMC2209 disabled (ENN is active-low) from power-on until `setup()`
  enables it, so the motor stays unpowered through boot, a crash or a reset.
  Only press the module's BOOT button with the motor stopped: it shorts
  GPIO0 to GND, which would enable the driver.
- **GPIO45** must be low, or VDD_SPI switches to 1.8V and the 3.3V flash and
  PSRAM fail. It carries the fan PWM through the gate of `Q6` (`R57` 1k in
  series, `R58` 10k pull-down), so the strap sees the same low level as an
  unconnected pin.
- **GPIO46** (STEP) is read at reset only for ROM-message printing and the
  boot mode; the TMC2209's STEP input has no pull-up, so it is left low.

The TMC2209 datasheet shows no internal pull on ENN or STEP. Neither BTT's
nor Watterott's docs list carrier-board pulls on EN, STEP or DIR. `R23`
makes boot correct whatever a given carrier has.

GPIO43/44 (saturation encoder CLK/DT) double as U0TXD/U0RXD.
`Serial` goes over native USB (GPIO19/20), not UART0, but the chip's ROM still
prints its boot log on GPIO43 at every reset, briefly driving it as an output.
With the old series resistor (`R28`) gone, that output could at worst be
shorted to GND through a closed encoder contact for a few milliseconds,
which the pin tolerates. GPIO21 drives the DevKit-style onboard RGB LED on
the ESP32-S3-ETH, so the tap button on it is only sampled after boot.

## OSC API

Default listen port `3335` (configurable via the [web UI](#web-config-api)),
over the onboard W5500 **Ethernet and/or Wi-Fi**. Wi-Fi is optional. It connects
as a station (DHCP) alongside Ethernet, trying networks in this order: the one
set on the config page (if any), then the built-in networks from
`wifi_defaults.h` (see below). With neither, Wi-Fi is off. Both links take OSC
on the same port, and the config page, `/log` and `/update` answer on both too.

**Built-in Wi-Fi networks.** `wifi_defaults.h` (up to 4 entries, tried in
order) is gitignored so the passwords stay out of the repo; copy
`wifi_defaults.example.h` to create it. `wifiTask()` gives each network up to
15s and moves on at once when one is rejected (not seen, wrong password). If
none connects it waits 15s and starts again from the first, so the preferred
network wins as soon as it is back. The log shows each attempt, for example
`Wi-Fi: trying "first" (1 of 2)` then `can't connect to "first" (NO_AP_FOUND…)`.
A build without `wifi_defaults.h` simply has no built-in networks.

- **How:** on ESP32, `OscEther` and `OscWiFi` are the same object
  (`ArduinoOSC::Manager<WiFiUDP>`), and its UDP socket listens on every
  interface. So one set of subscriptions hears both links; OSC is pumped
  whenever either link has an address.
- **Latency:** Wi-Fi modem sleep is disabled, since it can add ~100ms+ to
  incoming packets. Ethernet is still the lower-jitter link for tempo sync.
- **Power:** the main board's Wi-Fi transmit power is capped at 15dBm (plenty
  for a room), as a conservative setting for the module's own +3V3 rail (3A buck), which feeds the W5500 and
  the main ESP32.
- **Both links on the same subnet** (for example, one router) works: the
  board just has two addresses. Replies and `/tap` go out whichever
  interface lwIP picks for that subnet.
- **Flash:** the Wi-Fi stack grows the image to ~1.11MB, 84% of the default
  1.25MB app slot, so this project builds with
  `PartitionScheme=app3M_fat9M_16MB` (two 3MB OTA slots; see
  [Building / flashing](#building--flashing)).

### Incoming

Numeric arguments may be float32, int32 or float64; NaN/inf, other types and
argument-less messages are ignored. Max speed in the web UI is limited to
1–20000 steps/sec. A `/directionChange` while moving slows down
along the old direction (at the BPM-ramp rate) to the smooth-motion floor,
then reverses; the driver stays on.

| Address | Arg | Effect |
|---|---|---|
| `/flash`, `/pulse`, `/pulsediv` | any | Ignored (`onFlashGone()`, one log line): the global beat flash is gone; each preset's punch (`punchstyle=flash` for the old look) hits on the beat. |
| `/beat` | int, beat index in the bar (0 = downbeat); no argument also works | One beat, while the failover has chosen an OSC tempo source (see [BPM source failover](#bpm-source-failover)). Anchors the beat clock (`/status` `beatPhase`, `beatInMeasure`) and so keeps punch on the beat. Doesn't change tempo. Ignored while the tap is the tempo source. |
| `/measure` | float, bar position in beats (about 30 a second, wraps to 0 on the downbeat) | Sets the beat phase from the bar position (`positionEvent()` in `beat.h`). It doesn't count beats; `/beat` does. While the failover has chosen an OSC tempo source. |
| `/bpm` | float, 20–500 | Primary BPM source. Takes over immediately. |
| `/composition/tempocontroller/tempo` | float 0.0–1.0 | Backup BPM source, mapped linearly to 20–500 BPM. Only takes over if `/bpm` isn't fresh (see [BPM failover](#bpm-source-failover)), or if it's already the active source. |
| `/scaleEncoder` | float 0.0–1.0, wraps | Emulates the main encoder — each 0.0125 of wrap-aware delta is one detent (40 detents/turn). |
| `/scaleZero` | any | Sets `speedScale` to 0 (stops the motor) and resets the emulated encoder position. |
| `/home` | any | Sets `speedScale` to the stored home speed (the one the main encoder's button recalls; factory 1.0, full tempo speed forward) and resets the emulated encoder position. Sending it again leaves the platter at home. |
| `/directionChange` | any | Toggles motor direction (250ms debounce). |
| `/hue` | float, wraps into [0,1) | |
| `/saturation` | float, clamped [0,1] | |
| `/value` | float, clamped [0,1] | The ring's master brightness, applied by the LED engine after the colour (eased over about 60 ms). |
| `/presetmode` | float or int | `0` selects preset 1 (the user colour); it used to choose colour mode, which is gone, and `1` does nothing (see the [User Guide](../USER_GUIDE.html#presets-and-the-knobs)). `/wledmode`, its old name, also works. |
| `/preset` | float or int, 1 to the highest preset | Selects the preset; rounded and clamped to the LED engine's presets. |
| `/palette` | float or int, 0 to the highest palette | Selects the palette (0 = the preset's own); same rules as `/preset`. |
| `/fxspeed` | float or int, -16 to 16 | The effect speed in EXP2 clicks (x 2^(v/8): a quarter to four times the preset's own, 0 its own); rounded and clamped (`lightSetSpeed()`). Until reboot. |
| `/look` | string | A look in the preset format, its keys alone or a whole line (number and `name=` ignored), run in place of the selected preset's until a preset is picked (`ledLiveLine()`; `lightSetPreset()` calls `ledLiveClear()`). Keys left out take the format's defaults. An unreadable string is logged and ignored. |
| `/colourtemp` (also `/colortemp`) | float or int, kelvin, clamped to 2000–10000 | Colour temperature of the ring: 6500 is neutral, lower is warmer, higher is cooler (`colour::applyTemperature()`). Runtime only, like the colour; the switch-on value is the **Colour temperature** setting. |

### Outgoing

| Address | Arg | When |
|---|---|---|
| `/tap` | `1` | Subnet broadcast to port `3336` on each connected link (Ethernet and/or Wi-Fi; once if both are on the same subnet) on every tap-button press or `/live` Tap, regardless of which BPM source is currently active. |
| `/tapbpm` | float BPM | Same broadcast, whenever a tap (button or `/live`) sets a new tempo, i.e. from the second tap in a 15s window, while no OSC tempo source is fresh. |

## Web config API

Served from `http://<device-ip>/` on port 80 (a separate `WebServer`
instance from the OSC/network stack, but both run in `oscTask()` on core 0).

| Route | Method | Effect |
|---|---|---|
| `/` | GET | Config page, in dark theme with tabs (all inside one form, so one **Save & Reboot** covers every tab): **Status** (a table: BPM, direction, light mode and HSV, name, Ethernet and Wi-Fi addresses and Wi-Fi signal, temperatures, ring limit, fan, firmware build date and running OTA slot), **Network** (hostname, Ethernet, Wi-Fi network name/password, blank = off), **Defaults** (starting BPM, starting colour, colour temperature; the OSC port is on **Network**), **LEDs** (the LED engine: what is running, LED type and wiring, current limits, ring temperature, Art-Net, the preset list), **Motor & fan** (the **Speed limit** in RPM, applied and saved at once through `/maxspeed`, **Reverse motor direction**, plus the live slow-speed floor slider and the fan settings) and **Password** (web UI password). Usage notes sit behind round (i) tips (`TIP()` in `web_theme.h`: a `<details>`, so no script is needed; the menu's script closes an open one on any other click). Without JavaScript every tab simply shows. A field that fails validation on another tab switches to that tab. The tab is kept in the URL fragment (`/#motor`). Every page shares one dark stylesheet (`THEME_CSS` in the sketch). |
| `/save` | POST | Validates and persists the submitted fields to flash (via `Preferences`), then reboots so everything takes effect uniformly. |
| `/fan` | POST | `?en=0\|1&lo=<°C>&hi=<°C>&min=<pct>[&save=1]` — sets the fan-header temperature range (20 ≤ lo < hi ≤ 100), minimum speed (0–100) and control on/off, same-origin checked; `save=1` persists them once the motor is stopped. Replies with the current temperature and fan percentage. |
| `/setmin` | POST | `?v=<full-steps/sec>[&save=1]` — live tuning endpoint for the smooth-motion floor (`smoothMinFullStepsPerSec`). Applies immediately, no reboot; persists to flash only when `save=1` is present (sent on the config page's slider release, not on every drag step, to avoid hammering flash), and then only once the motor is stopped: a flash write holds off the step-timer interrupt, so saving mid-motion would stall the platter for a few ms. Returns the applied value as plain text. POST with a same-origin check, so another web page can't change it through a cached login. |
| `/update` | GET / POST | Firmware upload over Ethernet (see [Updating firmware over the network](#updating-firmware-over-the-network)). Disabled until a web UI password is set. |
| `/log` | GET | The log page (everything the sketch prints to Serial, with uptime stamps). A top bar stays on screen while the log scrolls: **Live** turns the 2-second refresh and the follow-the-end scrolling on and off together (off freezes the page so text can be read and selected), **Clear** empties the log on the unit, **Save .txt** downloads the plain text. It follows the end only while you are already at the end, and leaves the text alone when nothing has changed, so scrolling back and selecting text both work. |
| `/docs/USER_GUIDE.html`, `/docs/HARDWARE_OVERVIEW.html` | GET | The two HTML documents, served by the unit itself (no internet needed), behind the same password. They are the `docs/*.html` pages gzipped into `src/docs_data.h` by `docs/build_docs.py`, with three changes for the unit: always dark, links to repository files that are not on the unit (README, changelog, schematic PDF) shown as plain text, and a **Settings** link in the top bar. `/docs` redirects to the User Guide. Linked from the config and live pages. About 130 KB of flash. |
| `/log.txt` | GET | The last ~12KB of that log as plain text: for saving, copying or `curl`. The log page's Save button links here. |
| `/log/clear` | POST | Empties the log ring buffer (the page's Clear button). Same-origin checked. The first new line says it was cleared. |
| `/live` | GET | Phone-sized live page: BPM and where it's coming from, platter RPM, speed and direction, a warning when the speed cap holds the platter back (the cap is on the platter's speed after the speed setting, not on the tempo), and buttons for Start, Stop, Slower/Faster, Reverse, Tap and Set BPM, plus hue/saturation/brightness and colour-temperature sliders. Polls `/status` every 0.7s. Linked from the config page. |
| `/status` | GET | JSON snapshot: `bpm`, `source` (`osc`/`tempo`/`tap`), `oscBpmAgeS`/`tempoCtlAgeS` (seconds since each OSC tempo source last sent, `null` if never), `beatsPerRev`, `tempoRpm`, `tempoCapped` (the speed cap is holding the platter below the tempo times `speedScale`: `motion::capped()`) and `maxBpm` (the tempo at which the cap bites at 100% speed), `maxRpm` (the speed limit in force: `maxSpeed`, which the live page's Set limit and `/control?a=maxrpm` change until restart), `speedScale`, `homeScale` (the encoder's home speed), `direction`, `running`, `rpm` (signed, as driven now), `hue`/`saturation`/`value`, `colourTempK`, `eth`/`wifi`/`rssi`, `chipTempC`/`chipTempMaxC` (the main ESP32-S3's on-die temperature and its highest value since start, `null` until the first reading; see [Heat](#heat-and-ventilation)), `fanPct` (what the fan header is being told, 0–100), `fanTach` (`turning`, `stopped`, or `none` if no tach edge was ever seen), `uptimeS`. |
| `/control` | POST | `?a=<action>[&v=<value>]`, same-origin checked; replies with `/status`. Actions: `start` (speed 100%), `stop` (like `/scaleZero`), `faster`/`slower` (±5% of speed, never crossing zero), `reverse` (like `/directionChange`, with the same decelerate-then-reverse), `tap` (like the button, including `/tap`), `bpm` `v`=20–500 (sets tempo as the local source; a fresh OSC tempo overrides it on its next message), `hue`/`sat`/`val` `v`=0–1, `ctemp` `v`=2000–10000 (colour temperature, kelvin), `mode` `v`=0 (colour) or 1 (preset mode), `preset` `v`=1 to the highest preset, `palette` `v`=0 to the highest palette. `/status` also reports `lightMode`, `preset`, `palette`, `presetMax` and `paletteMax`. |

**Web UI password.** HTTP Basic auth, user `admin`. While no password is set,
every page is open, so you can set one on first use from the config page
(8+ characters; stored in NVS). Once set, every page above requires it, and
`/save` and `/update` also refuse cross-site form posts. OSC control is not
password-protected; it's a separate UDP port, unchanged.

**Forgot the password, or saved a bad static IP?** Hold the **tap-tempo
button** while powering the board on, and keep holding for 5 seconds. That
clears the password and switches the network back to DHCP; all other
settings are kept. The pages are then open until a new one is set,
and `/log` records the reset.

Persisted fields: static IP / gateway / subnet mask (`0.0.0.0` = DHCP, the
default), hostname, Wi-Fi network name and password, OSC listen port,
starting colour (a colour picker; `#rrggbb`, default white) and the switch-on colour temperature
(2000 to 10000 K, default 6500 = neutral; a warm/cool gain on the ring's RGB, see `colour.h`;
the live value is changed by OSC `/colourtemp` or the phone page),
starting BPM, reverse motor direction, web UI password (the speed limit, the slow-speed floor and the fan settings are
saved without a reboot from their own controls). The LEDs tab's settings live in NVS namespace `led` and the
presets in `/ledpresets.txt` on the FAT partition; they are saved by the same **Save & Reboot**
(`ledFormCheck()` checks them first, so an unreadable preset line stops the whole save).

**`microsteps` is intentionally not here.** It's fixed at `32` in firmware
(a `const`, not loaded from `Preferences`) — see [Design
notes](#tmc2209-configuration) for why 32 + interpolation, not a literal
256, is the right setting for this driver.

## Design notes

### BPM source failover

Three sources, in priority order: `/bpm` (OSC, primary) → tempo-controller
OSC feed (backup) → local tap-tempo button (last resort). State machine
lives in `loop()` plus `bpmIsFresh()`/`tempoControllerIsFresh()`.

The **"ever received" vs. "just booted" ambiguity** is handled explicitly:
`lastBpmReceived == 0` looks identical whether `/bpm` has never arrived or
arrived at `millis()==0`, so `bpmEverReceived`/`tempoControllerEverReceived`
booleans track real arrival separately from the timestamp. Without this, a
freshly-booted board would treat a source as "fresh" before any message had
actually arrived.

**Beats follow the failover.** `/beat` and `/measure` count while the failover has chosen an OSC tempo source, and are ignored while the tap is the tempo source. The gate is `beatSenderChosen` (`state.h`), set by `setBpmSource()` (`tempo.cpp`), the only place `bpmSource` changes. A change of source clears the beat clock (`beatClock`). The gate doesn't check the sender, so two senders can't be told apart: if both send `/beat`, both count.

**Beats keep the tempo alive.** Pulse sends `/bpm` only when the tempo changes, so a steady tempo would time out after `bpmTimeout` (60 s). `beatKeepAlive()` (`osc.cpp`) refreshes `lastBpmReceived` (or `lastTempoControllerReceived`, whichever source the failover chose) on each accepted `/beat` or `/measure`. It doesn't change the BPM value. When the beats stop, the usual timeouts apply.

**Tempo sources set tempo only.** `/bpm`, the tempo controller, the tap
button and `/live`'s BPM field change BPM and nothing else. Starting,
stopping and trimming the platter (`speedScale`) is left to people: the
encoder and its button (short press recalls the home speed, 1 s hold stores the current speed as home, 5 s hold restores the factory home of `speedScale` 1.0), OSC `/scaleEncoder`/`/scaleZero`, and `/live`'s
buttons. The platter boots stopped. This matters because a sender that only
transmits when the tempo changes goes stale between changes (the tempo
controller after 1s, `/bpm` after 60s): if its next message restarted the
platter, a platter someone had stopped would start itself. A stale source
only means the last BPM stays in force until something new arrives.

### Speed ramping and the smooth-motion floor

The speed control law is in [`motion.h`](https://github.com/scoobiekw/LiquidTurntable/blob/main/motion.h) (`motion::step()`), kept free of
Arduino/ESP headers so it is unit-tested on a PC (see [Testing](#testing)). `loop()` calls it
once per pass and drives the result:

1. `rampedSpeed` chases `defaultSpeed` (the BPM-derived target) at a rate fixed to wall-clock
   time (`bpmRampSeconds = 1.5s` to cross the full 0→`maxSpeed` range), so a tempo jump glides
   instead of jerking.
2. `|speedScale|` goes through a deadzone with hysteresis (`kDeadzoneEnter = 0.01`,
   `kDeadzoneExit = 0.02`), so jitter near zero can't toggle the step timer and driver. It acts
   on `|speedScale|` rather than raw steps/sec because the proportional remap below doesn't
   vary linearly with it.
3. The magnitude is `|speedScale|`'s 0–1 range remapped **proportionally** onto
   `[smoothMinSpeed, rampedSpeed]`, not a straight multiply-then-clamp (which would leave a large
   dead zone at low speeds: a multiply near zero collapses toward zero, not toward the floor).
   `smoothMinSpeed` is in full-steps/sec so it stays meaningful whatever the microstepping.
   The floor is a feel setting rather than a fixed threshold. The high floor of the TB6600 era, which hid full-step clicks, is not needed with the TMC2209's interpolation and StealthChop, so the default is 2.0 full steps/s (about 0.6 RPM), tunable live on the Motor & fan tab.
4. The result is **slewed at the same rate**, so no input can jump the platter: a start from
   rest, a big `/scaleEncoder` move, Faster/Slower, a reversal and a stop all glide. A
   direct-coupled platter has far more inertia than the rotor, and an instant jump can stall the
   motor or make it skip. About 0.9s from rest to 10 RPM.
   - **Start:** begins at the smooth-motion floor (at least 1 full-step/s), not at zero.
   - **Reversal:** slows down along the old direction to that floor, flips, then climbs the new
     way. The driver stays on throughout.
   - **Stop:** glides down to the floor (about 1.5s from full speed), then the driver is
     disabled and the platter coasts the last bit.
   - The ramp's time step is capped at 50ms (`kMaxDt`), so a slow `loop()` pass can't turn into one large jump, and a motor parked by a firmware
     upload ramps up from rest again instead of resuming at its old speed.

### TMC2209 configuration

`microsteps = 32` (fixed, not web-configurable) with `intpol(true)` set
separately in `configureTmcDriver()`. These are **two different settings,
easy to conflate**: `driver.microsteps(N)` sets `MRES`, the real step-pulse
resolution the ESP32 has to drive (mapped 1:1 in the TMCStepper library,
`N==256 → MRES=0`, `N==32 → MRES=3`, etc.). `intpol` is independent of
`MRES` and has the driver *internally* interpolate whatever resolution it's
given up to a smooth 256-level current waveform on its own (Trinamic calls
this MicroPlyer). `microsteps=32` + `intpol=true` already delivers the same
256-level StealthChop smoothness `microsteps=256` would, at 1/8th the
step-pulse rate demanded of the ESP32 — so 256 is strictly worse here, not
"more precise." `maxSpeed`'s physical-limit default (1813.3 steps/sec = 17
RPM) is derived against 32 microsteps specifically; if `microsteps` is ever
changed by hand, `maxSpeed`'s default needs recomputing too
(`motorFullStepsPerRev * microsteps * RPM / 60`).

`TMC_RMS_CURRENT_MA = 800` — genuine headroom below the motor's ~1A rating,
not right at it. Motor current is set **only** by this constant:
`configureTmcDriver()` clears `GCONF.I_scale_analog` (its power-up default
takes the reference from the VREF pin, i.e. the carrier's trimpot, and would
ignore the UART value), and the boot log confirms it. The trimpot position
doesn't matter.

`pdn_disable(true)` + `mstep_reg_select(true)` are required alongside the
above — without them, PDN_UART falls back to expecting an analog
current-sense input and MS1/MS2-pin microstep selection instead of actually
taking the UART-written register values.

`checkTmcHealth()` runs every 5s from `loop()`: detects UART connection
loss, a driver-side logic-supply reset (re-applies config if so — the
driver's registers don't survive that), and overtemperature/short-to-ground
faults from `DRV_STATUS`. Logs only on state transitions.

### Dual-core split

Tasks and cores:

| Task | Core | Job |
|---|---|---|
| `loop()` | 1 | Speed control (`motion::step()`), encoders and buttons, TMC2209 health checks, the serial `wifi` command. Watched by the loop watchdog (below). |
| `oscTask()` | 0 | OSC message pumping, the config web server, `checkTapBroadcast()`, the Wi-Fi setup access point. |
| `ledTask` | 0 | The LED engine: renders and sends a frame about every 10 ms; its RMT/SPI interrupts are on core 0. |
| `wifiTask()` | 0 | Walks the Wi-Fi candidate list and reconnects; see [OSC API](#osc-api). |
| `mdnsTask()` | any | Runs once after the first link gets an address: checks whether the hostname is taken and announces the final name, then deletes itself. |
| Arduino event task | any | Runs `onNetEvent()` (link up/down, Wi-Fi events). |
| Step timer ISR | n/a | Toggles the STEP pin; hardware-timer driven (`hw_timer_t`). |

A burst of incoming OSC (e.g. automation from a show-control system) therefore can't stall the
motor/encoder bookkeeping in `loop()`. Stepping itself is immune either way, but the
ramping/deadzone math and encoder debouncing in `loop()` are not.

**Loop supervision.** The step timer is an interrupt, so it keeps pulsing even if `loop()` hangs, and
the core's own task watchdog watches only core 0's idle task. Two layers cover it. `loop()` bumps a
heartbeat counter on every pass and `loopMonitorTask()` (core 0) restarts the chip if it stops for
**3s**: it switches the driver off and stops the step timer itself first, and leaves a marker in RTC
memory. The backstop is `enableLoopWDT()` at the end of `setup()`, the ESP-IDF task watchdog on
`loop()`: configured 5s, but on the bench it reset about **12s** after a hang (two trials). In both
cases `R23` holds the motor driver disabled until `setup()` has run again. The slowest legitimate pass
is well under a second. The next boot's log starts with `Reset reason: LOOP STALL`
(the monitor) or `Reset reason: TASK WATCHDOG` (the backstop), which is the only trace of the event
(the log is empty after a reset);
every boot now logs its reset reason (power-on, brown-out, crash, firmware update, ...). To test it,
define `WDT_TEST_HANG_MS` (say 20000) at the top of the sketch: `loop()` then spins forever after
that uptime. Remove the define afterwards. (To see the IDF backstop on its own, comment out the
`xTaskCreatePinnedToCore(loopMonitorTask, ...)` line in `setup()`.) Two names are shared between tasks (the Wi-Fi network being
tried, and the announced mDNS name); they live in fixed buffers copied under a lock
(`setSharedName()` / `sharedName()`), not in Arduino `String`s, which another task could free
mid-read.

**Logging.** `Log` is written from every task. Each task assembles its own line and the whole
line, uptime prefix included, goes out in one piece when the newline arrives, so messages from
different tasks can no longer interleave mid-line (they did: `BPM (OSC): BPM Source: OSC /bpm130.00`).
A task that stops mid-line just holds its text until its next newline, and nothing ever waits on
another task, so a forgotten `println()` cannot block anyone.

Shared state touched from both cores (`BPM`, `speedScale`, `bpmSource`,
`hue`/`saturation`/`hsvValue`, `direction`) is guarded with a `portMUX_TYPE`
spinlock (`stateMux`) at each write site. `loop()` reads `speedScale` and
`direction` once per pass, as one snapshot taken under the same lock.

### LED engine

The ESP32-S3-ETH draws the ring itself ([`src/ledengine.cpp`](https://github.com/scoobiekw/LiquidTurntable/blob/main/src/ledengine.cpp); the arithmetic is in
`ledout.h`, `ledfx.h`, `ledpreset.h`, `palstore.h` and `artnet.h`, PC-tested). A task on core 0 renders a frame about every
10 ms from the shared state (preset, palette, user colour, hue shift and saturation, brightness, colour temperature,
platter speed; each preset's punch hits on the beat),
applies the **per-LED limit** (36.6 mA by default: full white at the SK9822 maker's field-22 level, so single
colours keep the full 18 mA of field 31) and the **ring limit** (4.5 A), and sends it: SK9822 frames over SPI3
with DMA (GPIO18 data, GPIO2 clock, 2 MHz, RBG order, current field 31), or WS281x over RMT for a single-wire ring.
Art-Net / E1.31 input (two universes, or one with eight outer pairs sharing an address; see the drawing in the User Guide,
`docs/diagrams/artnet-single-pairs.svg`) can take the ring over. The `/leditor` page has a preset editor and a palette
editor (the ten built-in palettes 2-11 edited, 12-19 your own via **Save as new**, 1-16 colours each, kept in `/ledpalettes.txt`; reset
to factory per palette or all built-in ones, delete for your own); both keep
their contents in the browser's localStorage so a visit to the live page doesn't lose them. Settings are on the **LEDs** tab; the README's
[LED engine](README.md#led-engine-the-standard-led-driver) section has the details.

**Presets and the knobs.** The ring always runs a preset; colour mode is gone (2026-11-15). The VAL knob steps
`lightPreset` through 1..`lightPresetTop()` and EXP1 `lightPalette` through 0..`lightPaletteTop()`, both wrapping
(`presetmode::stepWrap`); a press of the VAL button toggles `valKnobPreset`, making the knob the master brightness
and back. EXP2 is the effect speed. HUE and SAT are always the hue shift and saturation scale that
`ledfx::adjustColours()` applies to every frame the presets draw ([`src/ledfx.h`](https://github.com/scoobiekw/LiquidTurntable/blob/main/src/ledfx.h)). Palette 1 is the
user colour (`userRgb`, from the live page's picker, starting as the starting colour), which preset 1 shows. The tops
come from the engine's preset list. The engine reads the state every frame, so there is nothing to send or coalesce.
None of it is remembered across a restart.

**Wi-Fi setup without Ethernet.** If no link has an address a minute after boot, or after the TAP hold at
power-up, the unit starts a setup access point `LiquidTurntable-XXXX` (password `turntable`) with a captive
portal to `/wifi`; a serial `wifi <name> [password]` command does the same from a computer
([`src/netsetup.cpp`](https://github.com/scoobiekw/LiquidTurntable/blob/main/src/netsetup.cpp), decisions in `setupap.h`, PC-tested).

## Building / flashing

```bash
arduino-cli compile --fqbn esp32:esp32:esp32s3:PSRAM=opi,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,CDCOnBoot=cdc,USBMode=hwcdc LiquidTurntable.ino
arduino-cli upload -p <port> --fqbn esp32:esp32:esp32s3:PSRAM=opi,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,CDCOnBoot=cdc,USBMode=hwcdc LiquidTurntable.ino
```

`PSRAM=opi,FlashSize=16M` matches the ESP32-S3-ETH's octal PSRAM and 16MB
flash. **`PartitionScheme=app3M_fat9M_16MB` gives each of the two OTA app slots
3MB** instead of the default 1.25MB (the Wi-Fi-capable image is ~1.11MB). Arduino
IDE: Tools → Partition Scheme → "16M Flash (3MB APP/9.9MB FATFS)". The partition
table is only written by a USB flash, never by `/update`; at boot the log reports
the running slot's size and warns if the image was built with a smaller scheme.
`sketch.yaml` sets this whole FQBN as the default, so a plain
`arduino-cli compile .` in this folder picks it up. **`CDCOnBoot=cdc,USBMode=hwcdc` is required, not optional:** the
core's default (`CDCOnBoot` disabled) maps `Serial` to UART0 on
GPIO43/44, which on this board are `satEncoderPinA` and `satEncoderPinB`.
With CDC on boot, `Serial` runs over the native USB-Serial-JTAG port
(GPIO19/20) instead. In the Arduino IDE, the equivalent is Tools → USB CDC
On Boot → Enabled, and Tools → USB Mode → Hardware CDC and JTAG.

**The usual build is [`tools/build.ps1`](https://github.com/scoobiekw/LiquidTurntable/blob/main/tools/build.ps1)** (Windows PowerShell). It compiles into a
staging folder and, only if that succeeds, moves the previous build's firmware to
`build/archive/<date>_<commit>/` (the newest 10 are kept, `-Keep` changes that) and puts the new one
in `build/`. `-Upload` (with `-Port`, default `COM3`) then flashes those same files over USB:

```powershell
powershell -ExecutionPolicy Bypass -File toolsuild.ps1 -Upload
```

`build/` holds `liquidTurntable_YYYY_MM_DD_HHMM_firmware.bin` (the distributable: a copy of the app image,
named with the build's date and time; it is what `/update` takes), `LiquidTurntable.ino.bin` (the app, for `/update`), `.merged.bin` (bootloader,
partitions and app in one image, flashed at 0x0), the bootloader and partition images, the `.elf`
and `.map` (the `.elf` decodes a crash's backtrace) and `build_info.txt`: the commit it was built
from, with `+changes` if the tree had uncommitted changes. arduino-cli 1.5.2-rc.1 also copies every
build's binaries to `build/esp32.esp32.esp32s3/` unasked; the script removes that copy.

**A release candidate is published** with `-Publish` (a plain build never is): the distributable goes to the web server (`tools/publish_firmware.py`, the docs upload's login in `tools/publish.local.json`; folder `firmware_remote` there, by default `firmware/liquidturntable` beside the docs) as `archive/liquidTurntable_YYYY_MM_DD_HHMM_firmware.bin`, `archive/index.html` lists the archive, newest first, and `latest.json` names it for the unit's Status tab and `/update` page to compare with their own build (the browser fetches it; `.htaccess` there lets other origins read that one file), and `latest.html` starts the newest build's download (from HTTPS: a download started from the unit's plain-HTTP page is blocked by Chrome). The unit's `/update` page links to both (https://kennedy-williams.net/unclemagic/firmware/liquidturntable/). The build's name and commit are compiled in (`src/fw_version.h`, written by the script, git-ignored) and shown on `/update`. `-Publish` builds only a clean commit that is on GitHub, and refuses anything else before compiling; a failed upload doesn't stop the flash.

Libraries: `ArduinoOSC` (`ArduinoOSCETH.h`; on ESP32 its `OscEther` also
serves Wi-Fi), `TMCStepper`, plus the ESP32 core's own
`ETH`/`WiFi`/`WebServer`/`Preferences`/`Update`.


### Building in WSL

`tools/build.ps1` compiles in WSL (Ubuntu) when arduino-cli is set up there, and with the Windows arduino-cli otherwise (`-Windows` forces that; `-Distro` picks another WSL distribution). Flashing always uses the Windows arduino-cli. Set it up once, from this folder (about 7.3 GB, nearly all of it the ESP32 core; the same arduino-cli, core and library versions as CI):

```powershell
wsl -d Ubuntu -- bash tools/setup_wsl_build.sh
```

Why: every `#include` makes the compiler probe about 400 ESP32 include folders. A failed lookup costs about 90 us on Windows and 3.5 us in WSL, and arduino-cli redoes its library scan (a preprocessor run per file, one after another) whenever a file's `#include` lines change. Measured: that rescan took about 11 minutes on Windows (Defender exclusions made no difference) and 61 s in WSL; an ordinary build 60 s on Windows, 26 s in WSL. The binaries differ only in the source paths compiled into log and assert messages.
### First boot

A new (or factory-reset) unit uses **DHCP**: it asks your router for an address on Ethernet and,
once configured, on Wi-Fi. Find it by any of:

- **`http://liquidturntable.local/`**: the board announces itself over mDNS under its hostname
  `liquidturntable` on every link that has an address. Works on Windows 10+, macOS, iOS and Linux
  (with Avahi); Android support varies by version.
- **The router's client list**, looking for `liquidturntable`.
- **The USB log**: connect the ESP32-S3-ETH's USB-C port (the board must also be externally
  powered, see [Powering the board while flashing](#powering-the-board-while-flashing)) and
  watch the serial monitor at 115200 baud. "ETH got IP: …" and "mDNS: http://liquidturntable.local/"
  are printed once the link is up.

**Several turntables on one network.** The name is `liquidturntable` by default and can be changed
on the config page (Network tab, "Hostname"; letters, digits and hyphens, saved and applied after the
reboot). At start-up each unit asks the network whether its name is already taken (an mDNS lookup,
made under a temporary chip-unique name so it can't hear itself). If it is, the unit quietly uses
`liquidturntable-1`, then `-2`, and so on up to `-9`, and the log says so
(`mDNS: "liquidturntable.local" is already used by 10.1.10.20`). The config page and `/live` show the
name actually in use. Names are first come, first served, so which unit gets which number depends
on power-up order: to keep names fixed, give each turntable its own hostname on its config page. A
short random delay before the lookup stops two units that power up together from both finding the
name free. The configured name is also sent as the DHCP and Wi-Fi hostname.

Then set a web UI password on the config page, and a static address there if you want one (or
reserve an address for `liquidturntable` in the router, which keeps DHCP's convenience). OSC senders
need the board's IP address, or the `.local` name where the sender supports mDNS. A wrong static
address that makes the board unreachable is cleared by holding the tap-tempo button for 5s at
power-up, which returns the network to DHCP (see [Web config API](#web-config-api)).

### Updating firmware over the network

After the first USB flash, routine updates go over Ethernet or Wi-Fi, with the board
running on its normal supply and no USB cable:

1. Set a web UI password on the config page (once).
2. Build: `tools/build.ps1`, or
   `arduino-cli compile --fqbn esp32:esp32:esp32s3:PSRAM=opi,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,CDCOnBoot=cdc,USBMode=hwcdc --output-dir build LiquidTurntable.ino`
3. Upload `build/LiquidTurntable.ino.bin` (**not** the `.merged.bin`),
   either from the browser at `http://<device-ip>/update` or from a script:
   `curl -u admin:<password> -F "firmware=@build/LiquidTurntable.ino.bin" http://<device-ip>/update`

During the upload the motor stops and the driver is disabled. If the upload
fails, or stalls for 60s, normal operation resumes on the old firmware.
On success the board reboots into the new image.

**Rollback.** A new image stays "unconfirmed" until it has run 30 seconds
with Ethernet or Wi-Fi up; then it's marked good. If it crashes or reboots before
that, the bootloader returns to the previous firmware automatically. If it
runs but never gets an IP on that first boot (say, the cable was
unplugged), it keeps running that session but reverts at the next reboot.
That's on purpose: a build that breaks networking can't be fixed over the
network. `/log` reports both "unconfirmed" and "was rolled back" at boot.
(Proving this once on the bench is on the [open items](#open-items) list.)

**What still needs USB:** the first flash, recovery from a build that breaks
networking *and* got confirmed, and any partition-table change. The table
can't change over OTA; the app slots are 3MB and the image is about 1.1MB, so
there is plenty of room.

### Powering the board while flashing

The ESP32-S3-ETH's own USB-C port **powers the logic**: the ESP32, Ethernet, the expander, the
encoders and the TMC2209's VIO, through the module's own 1N4148 and regulator, so flashing, the web pages and the
panel work from USB alone. The motor needs the 12V supply and the ring the 5V supply. A 12V adapter on `J-PWR-12V` alone does
not power the logic.

**The LED buffers' supply.** `U3`/`U5` run from `+5V_LED_LOGIC`, fed from `+5V_LED_PSU` through `D33` (an SS34
Schottky), so they see about 4.8V from a 5.1V supply (the 74AHCT works from 4.5V) and a reversed supply is
blocked. Keep the 5V supply at 5.1V: the SK9822's limit is 5.3V. Not yet tested on hardware.

### LED engine setup

- Nothing to flash: the LED engine is part of this firmware and set up for the SK9822 ring as delivered.
- On the **LEDs** tab check: LED type SK9822, data GPIO 18, clock GPIO 2, colour order RBG, SK9822 current 31,
  mA per LED 54 (at field 31), per-LED limit 36.6 mA, ring limit 4500 mA. Saved with the rest of the settings.
- The 22 built-in presets are written to `/ledpresets.txt` on first boot; edit them on the same tab.
- Ring heat is the main thermal load; see [Heat](#heat-and-ventilation).

## Testing

The speed control law (`motion.h`) has PC-side unit tests in
[`tests/test_motion.cpp`](https://github.com/scoobiekw/LiquidTurntable/blob/main/tests/test_motion.cpp): start from rest, tempo changes, stop, resuming
during a stop, reversal, a parked motor, slow passes, deadzone hysteresis, the floor and the cap,
plus a 400,000-step randomized run that checks the invariants (never above `maxSpeed`, no step
larger than the ramp allows, a reversal or stop only near the floor), and `colour.h` (HSV/RGB
conversion, the starting-colour hex handling and the colour-temperature gains) in
[`tests/test_colour.cpp`](https://github.com/scoobiekw/LiquidTurntable/blob/main/tests/test_colour.cpp), and the encoder decoder (`src/quadrature.h`: the
same answer as the original code for every pin-state pair, a full click, bounce, and the
whole-detent bookkeeping) in [`tests/test_quadrature.cpp`](https://github.com/scoobiekw/LiquidTurntable/blob/main/tests/test_quadrature.cpp). Run `tests/run_tests.sh`
(g++ or clang++) or `tests\run_tests.bat` (Visual Studio Build Tools); no hardware is needed. Run
them after any change to `motion.h`, `colour.h` or `src/quadrature.h`. Everything else (network, web UI, TMC2209, the ring) can only
be checked on the board.

**Continuous integration** (`.github/workflows/ci.yml`, on every push and pull request) runs two
independent jobs: *Unit tests and documents* (`tests/run_tests.sh` with g++, and
`python docs/build_docs.py --check`, which fails if an HTML page (or `src/docs_data.h`, the copy
embedded in the firmware) is out of date with its
Markdown), and *Firmware compiles* (the pinned ESP32 core 3.3.11, ArduinoOSC 0.6.0 and TMCStepper
0.7.3, built without `wifi_defaults.h`, so it also proves a fresh clone builds). The firmware job
takes a while on a cold cache. `.gitattributes` keeps `*.sh` on LF and `*.bat` on CRLF whatever
the checkout machine's Git settings.

## Board notes

- **Mainboard PCB:** 100×100mm, two layers (sized for JLCPCB's cheaper price tier), four M3
  mounting holes at the corners. **1oz copper** (JLCPCB's default).
  The ring current is held to about 4.5A by the LED engine and the 5V side has a 7.5A harness fuse.
- **Routing:** the placement, pin map and routing were done together with a
  purpose-built grid router and simulated-annealing placement (one-off scripts, not in the repo;
  `kicad_mainboard/tools/route_sockets.py` and `microroute.py` are the older Freerouting-based
  tools). The panel strip along the bottom edge (the seven encoder headers, `J-BTN-TAP`, their
  protection cells and the lines to the processor and expander) is in the order MAIN, VAL, TAP, EXP3,
  EXP2, SAT, EXP1, HUE from left to right.
  `kicad-cli pcb drc --schematic-parity --refill-zones`: 0 violations, 0 unconnected items,
  0 parity issues.
- **Measured dimensions:** ESP32-S3-ETH `H1`/`H2` row spacing 17.78mm, TMC2209 rows 15.24mm. All were taken from the modules, not estimated.
- **LED ring current path** (about 4.5A in use, 9.6A at most): copper pour on every leg, not traces. A full B.Cu
  ground plane carries the return, and F.Cu pours (about 12–18mm wide) carry
  `+5V_LED_PSU` and `+5V_LED_RING` from `J-PWR-5V` through `Q5` (the reverse-polarity FET) to `J5`. The fuse-side pour is at least 7.6mm wide where it reaches `Q5`. All the +5V legs stay on F.Cu, so the ring current never crosses a via,
  and the high-current pads use solid zone connections. IPC-2221 (external layer, 1oz): the narrowest point on the path,
  6.5mm, carries about 9.2A at a 10°C rise and 12.5A at 20°C, both above the 7.5A fuse. The motor's
  0.8–1.6A uses ordinary traces (0.6mm near `J3`).
- **Power-path check (simulation, 1oz):** about 2.8mΩ of copper from `J-PWR-5V` to `J5` and 2.4mΩ for the ground
  return, about 13mV and 11mV at the 4.5A ring limit; the 12V motor path about 50mΩ, 0.1V at 2A. `+3V3` now comes out of the module at the
  socket, next to its main loads.
- **Silkscreen:** reference designators are visible except on crowded parts (`R9`, `R21`, `R22`, `R26`, `R27`, `C8`, `C9`, `C11`, `D5`, `U3`, `J-LED-SIG` and the TMC2209 mode/motor sockets). The encoder, tap and expansion headers
  show short names (MAIN, HUE, SAT, VAL, EXP1–3, TAP) under each header, with a letter beside
  each pin (V=+3V3, S=SW, D=DT, C=CLK, G=GND; `x` for `J-ENC-EXP3`'s unconnected SW pin; G and T
  on `J-BTN-TAP`) and a legend line above the row.
  Hand-wired connectors have pin labels outside their housings; the motor connector `J3` has its labels (A+, A−, B+, B−) inside the housing outline, beside each pin, with pin 1 (A+) at the bottom.

## Heat and ventilation

Estimated heat inside the enclosure (these figures were made for an earlier 14 × 17 × 2" interior, 1/2" birch box; the current box is 6 mm birch, about 13.3 × 10.7 × 2.7 in inside, and has not been re-estimated), none of it measured yet:

| Source | Heat |
|---|---|
| Stepper motor (0.8 A RMS per coil) | about 3–4.5 W |
| TMC2209 | about 0.6 W |
| 3.3V electronics plus the module's regulator and `D33` | about 2.2 W |
| `D1` | about 0.3 W |
| LED ring | about 3.9 W per amp of ring current (78% of the electrical power) |

A closed box of that size sheds only about 0.9 W per kelvin, and the ring board about 0.56 W per
kelvin of its own. At a 110 °F (43 °C) room, a sealed enclosure therefore holds an average ring
current of about 2 A (about a third of full white) with the ring board near 75 °C; generous vents raise that to
about 3 A. High brightness for hours needs forced air: 6 to 15 CFM through the box is enough, which
one slow 120 mm fan provides almost silently. These are first-pass estimates (about ±50%); measure
before relying on them.

- **Measure:** the Status tab, `/status` and the log (every 5 minutes, plus a warning above 80 °C)
  report the main ESP32-S3's on-die temperature. That is the module's own temperature, a few
  degrees above the air next to it; it does not see the ring board or the motor. Run the real
  ring brightness for two hours with a thermocouple on the back of the ring and an IR thermometer on
  the acrylic, and compare.
- **Limit first:** keep the LED engine's ring limit at 4500 mA and the per-LED limit at 36.6 mA (LEDs tab), about 4.5 A of ring current.
- **Layout:** a 120 mm fan fits best in the bottom panel (the 2" interior only takes 40 mm fans on a
  side wall), with filtered intake low and exhaust slots high on the far wall, so air sweeps under
  the ring board. An aluminium heat plate under the ring board (1/8 in 6061-T6, black anodised, on a 0.5 mm thermal pad, screwed, not
  glued; `enclosure/ring_plate.dxf`, made from the board by `tools/gen_ring_plate.py`), in the airflow, lowers the board temperature at a
  given airflow and stops the board flexing at its connector. It is earthed; see `enclosure/MOTOR_MOUNT.md`, "Ring heat plate" and "Earthing".
- **Fan header `J-FAN` (bottom-left corner of the board):** a keyed 4-pin header for a **4-wire 12 V** fan, powered
  straight from `+12V_MOTOR` (after `F1` and `D1`), so the
  fan runs whenever the 12 V supply is on, whether or not the ring supply is. **A 5 V fan on this header would be damaged.** GPIO45
  drives `Q6` (2N7002) through `R57` (1k), with `R58` (10k) holding the gate low; `Q6` pulls the fan's PWM input
  low, so the signal is inverted. With the pin floating (reset, crash, firmware stopped, no firmware) the FET is off, the fan's own
  pull-up holds PWM high, and **the fan runs at full speed**. The tach (an open-collector output, 2 pulses per revolution) goes through
  `R59` (4.7k, which limits the current to about 0.4 mA if a fan pulls the tach up to 5 V, or about 1.8 mA at 12 V; use a fan with a true open-collector tach) to the expander's `P0_6`, which has the
  expander's internal pull-up. The firmware reads it with the buttons (every ~20 ms), which is too slow to measure speed but
  enough to tell a turning fan from a stopped one: the Status tab shows *tach turning / STOPPED / not detected*, `/status` has
  `fanTach`, and the log warns if a fan that was turning stops.
- **Fan choice:** the header takes a **4-wire, 12 V, PWM** fan, at most 0.5 A (the converter's limit). Candidates checked
  (specs from the makers' pages and retailer listings, 2026-10-05): ARCTIC P12 PWM PST (120x25, 12 V, 0.1 A, 200 to 1800 rpm, 56 CFM,
  0 rpm below 5% PWM, quoted 0.3 sone; about 6 to 10 USD, cheaper in packs) and Noctua NF-P12 redux-1700 PWM (120x25, 12 V, 0.08 A,
  550 rpm at 20% PWM, 25.1 dB(A) max; about 16 USD). Keep the minimum speed at 20% or more: a fan that stops at very low PWM would be
  reported as a stall by the tach check. Not suitable: fixed-speed two-wire fans (no PWM, no tach) and 5 V fans (wrong voltage). Test the
  fail-safe once: with the firmware stopped (for example holding the board in reset) the fan must run at full speed, which relies on
  the fan's own pull-up on its PWM input.
- **Fan control in firmware:** the fan follows the smoothed chip temperature, from a minimum speed (25% by
  default) at or below a *low* temperature (60 °C) to full speed at or above a *high* one (78 °C). It speeds up in
  steps of up to 10 points per 2 seconds and slows down 2 points at a time, so the pitch does not hunt. The Motor tab has a
  **Fan** box (live, no reboot) for the two temperatures, the minimum and an on/off tick (off = full speed);
  `POST /fan` does the same for scripts. The chip runs a few degrees hotter than the air around it, so set the range from a
  reading with a thermometer in the enclosure. These defaults are guesses until measured.

## Open items

Nothing here is a known defect. These are things that can only be settled with parts in hand, or
choices left open on purpose. How the design got here is in [CHANGELOG.md](CHANGELOG.md).

**Bench checks** (can't be settled from the design files):

- **The firmware has run on a bare ESP32-S3-ETH only**: it boots, joins Wi-Fi, serves
  the web pages and the log, and the unit's own copy of the documents. The motor driver, motor,
  LED ring, panel encoders and expander have not been exercised, and the speed control has only
  passed the PC-side tests. The first power-up of a full board should confirm, in order: the boot
  log and the board's address (see [First boot](#first-boot)); the TMC2209 UART lines in the log
  ("microsteps confirmed", "current reference is UART"; on a bare module the log correctly says
  "TMC2209 UART: no response"); that the platter starts, speeds up and stops smoothly (about 1.5s
  from rest to full speed or back; change `bpmRampSeconds` for a different feel); and the
  encoders.
- **Boot strapping.** `R23` pins GPIO0 high at reset (and the fan gate pull-down `R58` keeps GPIO45 low) whatever the TMC
  carrier has. A few power cycles with the TMC module socketed is still a cheap sanity check.
- **Wi-Fi setup network.** Unplug Ethernet, hold TAP through power-up, join `LiquidTurntable-XXXX` from a phone and
  check the setup page appears and a saved network is joined after the restart.
- **Motor coil pairs and direction.** `J3` is in the standard order: pins 1+2 are one coil
  (A+ black, A− green), 3+4 the other (B+ red, B− blue), as on StepperOnline's 17HS08-1004S. For
  another motor, confirm its pairs with a multimeter (each coil reads a few ohms across its two
  wires). If the platter turns the wrong way, tick **Reverse motor direction** on the config page
  (saved; flips DIR for every move). Swapping the two wires of one coil does the same in
  hardware.
- **Encoder step size.** The encoder ISRs count every quadrature edge, and
  `encoderCountsPerDetent = 4` suits a typical KY-040 (4 edges per click). If one click moves
  the speed by 0.02 or 0.04 instead of 0.01, set it to 2 or 1.
- **OTA rollback.** Prove it once on the bench: upload a build that deliberately crashes in
  `setup()` and confirm the board comes back on the old firmware.
- **mDNS.** `http://liquidturntable.local/` resolves from a Windows 11 PC on the same network.
  The name-conflict rename was tested against a name owned by that PC (the board chose `-1`);
  confirm it with two real turntables. Check your phones too (Android support varies).

**Before ordering the boards:**

- Order **both boards at 1oz copper** (the default; the 5 V harness fuse and the LED engine's 4.5 A limit make that safe).
- **Ring board** (`kicad_led_ring_offset/jlc_export/`): 360 SMD parts plus two THT parts (the connectors `J1`, `J2`), about $18 of components. The LED is OPSCO's SK9822-A
  (`C5378730`, 27 kHz PWM, about 18.7k at JLCPCB). Check its pinout (pin 1 SDI, 2 CKI, 3 GND, 4 VDD, 5 CKO,
  6 SDO) if you ever substitute it, and re-check `J1` (C157996), `J2` (C157991) and `TH1` (C13564) stock at upload. Details in the
  [Hardware Overview](../HARDWARE_OVERVIEW.html#6-the-led-ring-board).
- In JLCPCB's placement preview, check the orientation of `C11` (+ pad is the lower one, next to `C8`) and `U1` (TSSOP-24; its CPL rotation is set from JLCPCB's usual TSSOP drawing, not looked up).
- **Connector split and buffer feed first article.** Check the Mini-Fit 2x2 (`J-PWR-5V`, C20539147) and JST XH 2-pin (`J-PWR-12V`, C158012) footprints against the real parts, and that the XH body clears `MH1` and `F1A`. Check `D33` (SS34) orientation in the placement preview (cathode toward the top of the board, to the lane on `y = 2.4`). With power on, `+5V_LED_LOGIC` (at `C10`/`C15`) should read about 4.7-4.8 V and `+3V3` 3.3 V.
- **`Q5` (reverse-polarity FET) first article.** Q5 is now the Siliup SP30P03NK (C41355006; 4.5 mΩ typ, 6 mΩ max at 4.5 V gate drive, so up to about 0.3 W at the ring's 7.3 A full-white maximum); its datasheet pinout (S S S G / D x4 + tab) matches the footprint, but check the land pattern against its PDFN5X6 drawing and its orientation in JLCPCB's placement preview (pin 1 is the first source pad). The AON6403 it replaced (4.3 mΩ max, about 0.5 W) is a drop-in if the heat matters more than the 20 cents. On the first board, apply a reversed 5 V from a current-limited bench supply (1 A) to `J-PWR-5V` pins 1 and 3 with the ring off and confirm nothing conducts, then check `Q5` stays cool at full white. It does not protect against 12 V on a 5 V pin.
- **Module power first article.** With only USB on the module, the logic should boot (web pages, encoders); with only 12V, the board should stay dark and the TMC2209 disabled; with only 5V, everything but the motor. Run `kicad_mainboard/tools/bom_cost.py` before ordering.
- `F1` is a soldered resettable fuse, so the board needs no blade fuse. If you add an inline 5 V fuse holder to the harness, use a standard or low-profile ATO holder; a mini fuse needs a different layout.
- Optionally give the board a visual pass in the KiCad GUI around the high-current pours.

**Left open on purpose:**

- **Ableton Link** compiles against this core but is on hold: Link is GPLv2+ unless Ableton
  grants a proprietary licence, which would make the whole firmware GPL.
- **The expansion encoders:** EXP1 picks the palette and EXP2 the effect speed; EXP3 has no function yet.

## Repo layout

```
LiquidTurntable.ino                Firmware sketch: setup() and loop() only
src/                               Firmware modules (each .cpp has a short header comment saying what it owns):
  state.h / state.cpp                The globals shared between modules (comments say who writes what); pins.h has every pin
  motor.cpp                          Step-timer ISR, ENN, TMC2209 bring-up and health checks
  panel.cpp / quadrature.h           Encoders (one shared ISR), main encoder button (on the expander), TCA9555 expander; quadrature.h is PC-tested
  tempo.cpp / osc.cpp                BPM bookkeeping and tap tempo / OSC handlers, /tap broadcast, the core-0 task
  net.cpp                            Ethernet, Wi-Fi, mDNS naming
  web.cpp / ota.cpp / config.cpp     Web pages and /control, firmware update and boot status, persisted settings
  lighting.cpp / monitor.cpp         Presets, palette, user colour, effect speed; fan, chip temperature, loop() stall monitor
  ledengine.cpp / leddriver.cpp      LED engine (render task, presets, Art-Net, the LEDs tab) and its RMT/SPI drivers
  netsetup.cpp / setupap.h           Wi-Fi setup access point (/wifi, captive portal) and the serial `wifi` command
docs/USER_GUIDE.html               End user guide (default format; built from the .md)
docs/HARDWARE_OVERVIEW.html        Hardware overview (default format; built from the .md)
docs/*.md, docs/diagrams/*.svg     Editable sources of the documents and their diagrams
docs/index.html                    Documentation index page (hand-written)
docs/BREADBOARD_GUIDE.html         Breadboard prototyping guide, generated by docs/breadboard/build_breadboard_guide.py
docs/files/                        Copies of every file the docs link to, incl. the diagrams (made by docs/sync_files.py; never edit)
docs/sync_files.py                 Refreshes docs/files/, writes an index.html into each docs folder, checks docs/ links stay inside docs/
docs/screenshots/*.png             Web UI screenshots used in the user guide
tools/capture_screenshots.py       Takes those screenshots from a running unit (headless Chrome or Edge, asks for the password)
enclosure/                         Draft motor mount plate and box layout (OpenSCAD, STL, DXF, renders, notes); not built yet
  tinkercad/                         STL and SVG files of the case and mount for Tinkercad; export_stl.py regenerates and checks them
docs/build_docs.py                 Rebuilds the HTML from the Markdown, and src/docs_data.h (stdlib only)
tools/gen_led_map.py               Generates src/led_map.h (angle and radius of every ring LED) from the ring board
tools/gen_artnet_pairs.py          Draws docs/diagrams/artnet-single-pairs.svg (one-universe pairs) from led_map.h and artnet.h
tools/gen_ring_plate.py            Makes enclosure/ring_plate.dxf (the ring's aluminium heat plate) from the ring board
src/docs_data.h                    Generated: the HTML documents, gzipped, served by the unit at /docs/
motion.h                           Platter speed control law (PC-testable, no Arduino headers)
colour.h                           HSV/RGB/colour-temperature conversions (PC-testable)
tests/                             Unit tests for motion.h, colour.h and src/quadrature.h (run_tests.sh / run_tests.bat)
.github/workflows/ci.yml           CI: unit tests, docs up to date, firmware compiles
.gitattributes                     Line endings for the scripts
wifi_defaults.example.h            Template for the gitignored wifi_defaults.h (built-in Wi-Fi networks)
CHANGELOG.md                       Dated history of design and firmware changes
kicad_mainboard/
  Mainboard.kicad_sch              Main board schematic — source of truth (root index sheet)
  power/controller/motor/led/panel_io/testpoints.kicad_sch
                                   The six function sheets (see Hardware above)
  Mainboard_power.kicad_sym        Project rail power symbols (+12V_MOTOR, +5V_LED_RING)
  sym-lib-table                    Registers Mainboard_power.kicad_sym
  Mainboard_schematic.pdf          Rendered PDF export
  Mainboard.kicad_pcb              PCB layout — routed, 0 DRC violations
  Mainboard_render_top.png         Top-down render of the routed board
  Mainboard_render_bottom.png      Bottom-side render (B.Cu) -- mirrored left-right, standard
                                    convention for viewing through the board from underneath
  erc_report.rpt                   Latest ERC run (0 errors)
  fp-lib-table                     Registers the project-local footprints in lib.pretty/ (FuseClip_T508VS,
                                    CP_Elec_6.3x7.7_TrimmedCrtYd, PowerPAK_SO-8L_Single_GSD)
  lib.pretty/                      Project-local footprints (see fp-lib-table)
  tools/build_jlc_assembly.py      Generates SMD-only + full-assembly BOM/CPL + cost rollup (re-run after
                                    any layout change; reads placements live from the board)
  tools/route_sockets.py           Freerouting round trip that keeps existing copper fixed and keeps new
                                    routing off the high-current pours -- see its docstring
  tools/microroute.py              Small two-layer grid router for connections Freerouting can't finish
  tools/add_test_points.py         Adds the twelve test points to the schematic (testpoints.kicad_sch) and the PCB
  tools/bom_cost.py                Prices the BOM from LCSC (writes jlc_export/mainboard_bom_cost.csv)
  tools/check_cpl_rotation.py      Checks CPL rotations against JLCPCB's own footprints
  drc_report.rpt                   Latest DRC run with schematic parity (0 violations)
  jlc_export/                      Gerbers, drill, and BOM/CPL in two variants -- SMD-only and full
                                    (SMD+THT) assembly, for cost comparison; see its README + ASSEMBLY_COMPARE.md
kicad_led_ring_offset/
  LEDRing.kicad_sch                LED ring schematic — 178x SK9822-A, offset/brick matrix
  LEDRing.kicad_pcb                PCB layout — routed, 0 DRC violations
  LEDRing_schematic.pdf            Rendered PDF export
  LEDRing_pcb.pdf                  Rendered PDF export
  erc_report.rpt / drc_report.rpt  Latest ERC/DRC runs (0 errors)
  jlc_export/                      Gerbers, drill, CPL, BOM -- ready to order from JLCPCB
```

The ring board lives here so this repo holds every part of the physical build. Two earlier
comparison layouts (a plain square grid and a true-hexagonal-packing variant, neither fully
routed) stay in the sibling [MegaMagicTurntable](https://github.com/scoobiekw/MegaMagicTurntable)
repo as design history; this offset/brick layout is the one with real JLCPCB order files.
