Active desk wing · GT3 RS replica · electronics plan v3.3 · two servos inside the necks

Wing Electronics Plan

The circuit for the v2.0 replica. Two micro linear servos, one standing on edge in a bay inside each neck head behind a red cover, push the upper element the way the real car’s hydraulic cylinders do. Each one is fed through a magnetic connector in its neck’s foot. This page covers where the power goes, which pin does what, how long the battery lasts, what the code does, and the order to build and test it.

Jump to the firmware files (copy them straight into the Wokwi simulator).

What changed for the replica (v3.0, 20 Oct)
The short version

Three parts

Base: power and brain18650 cell, USB-C charger, power button, ESP32-C3, 5 V boost, airbrake button, knob and the 13-LED light bar, all in the plinth under the engine lid.
Each neck: 3 or 4 wires5 V, ground and signal (plus the wing ID on the left) run from the magnetic connector in the foot, up the channel inside the neck, to the servo in its red pod.
Wing: no electronicsThe two servo rods push levers on the upper element, which hangs from a pin in each neck head, so the wing has no wires at all.
PortsTwo USB-C sockets in the plinth’s front wall: the charger’s (charging only) and the ESP32’s (uploading code and reading its log).
Figure 1

Where the power goes

18650 cell Molicel P28A 3.0–4.2 V B+/B− TP4056 USB-C charger + protection USB-C 5 V in (charging) OUT+ Power button latching VBAT · 3.5–4.2 V (switched) 1N5819 ESP32-C3 · 5V pin makes its own 3.3 V 3V3 → knob, ID pull-up Light bar (13 LEDs) Button ring LED 100k + 100k → GPIO0 ~0.6 A MT3608 boost set to 5.0 V first V5 · 5.0 V 1000 µF 16 V Left dock connector → left servo (~0.2 A moving) Right dock connector → right servo (~0.2 A moving) Every ground joins at the TP4056’s OUT− pad. The cell’s B− goes to the charger and nowhere else.
The battery only ever touches the charger. After the power button, one rail feeds everything that is happy at battery voltage. The boost board makes a separate 5 V rail for the two servos, which are the only parts that need it. The ESP32 drives them straight from its 3.3 V pins, so there is no level shifter and no second regulator.
Figure 2

Which pin talks to what

ESP32-C3 SuperMini GPIO0 ADC GND GPIO3 GPIO4 ADC GPIO6 GPIO1 ADC 3V3 GPIO10 GPIO5 VBAT ÷ 2 from the divider 1k 3.3 V pulses left dock 5V SIG GND ID V5 GND left neck Left linear servo in the neck head · 1.5 g DRS 1759 · brake 1244 µs 10k ID GND 1.65 V = GT3 RS · 3.3 V = no neck 10k 3V3 1k right dock 5V SIG GND — V5 GND right neck Right linear servo turned round: pulses mirrored DRS 1241 · brake 1756 µs 0.06–2.15 V = DRS to airbrake 4.7k middle end Knob 10k linear pot GND 330 Ω DIN Light bar × 13 input, internal pull-up Airbrake button GND GND
Everything talks to the ESP32 at 3.3 V directly; the servos accept 3.3 V pulses even though they run from 5 V. Each servo signal has a 1k resistor in series, so a pin can’t be hurt if the magnets touch the wrong pad for a moment while a neck goes on. Only the left neck carries the ID resistor: with it and the base’s 10k pull-up, the pin reads about 1.65 V. With the left neck off it reads the full 3.3 V and both servos stop. The right dock’s fourth pin is spare.
Base to necks

Magnetic connector pinout

PinSignalBase side (lid)Neck side (foot)Peak current
15VV5 railServo red~0.2 A while moving (estimate)
2SIG1k from GPIO3 (left) or GPIO6 (right)Servo signal (white or yellow)< 1 mA
3GNDCommon groundServo black or brown; the ID resistor (left)~0.2 A
4IDLeft: GPIO4 + 10k pull-up to 3V3. Right: not connectedLeft: 10k to GND. Right: nothing< 1 mA

The two docks use the same keyed 4-pin magnetic pogo connector (the magnets only attach one way round), rated at 1 A or more per pin. In each dock the flat-pad half sits flush in the lid’s connector pocket and the spring-pin half sits in the neck’s foot. The four wires run up the channel inside the neck to the servo, whose own lead is cut short and soldered on. Magnets only make the contact: two M3 screws into the plinth’s dock pillars hold each neck. Lift necks off with the power off; with a neck off, the pads in the lid are live while the power is on.

Firmware reference

Pin map

PinConnects toModeNotes
GPIO0Battery divider midpointAnalog inADC1. Reads 1.75–2.1 V for a 3.5–4.2 V cell.
GPIO1Knob middle pinAnalog inADC1. 3V3 → 4.7k → knob → GND keeps it under 2.25 V, inside the ADC’s range.
GPIO31k → left dock pin 2 → left servoPWM out, 50 Hz1759 µs at DRS, 1244 µs at the airbrake, until calibrated (master dimensions v2.0).
GPIO4Wing ID (left dock pin 4)Analog inADC1. 10k pull-up to 3V3 plus 100 nF to GND.
GPIO5Airbrake button → GNDInput, pull-upLOW while the button is pressed in. Its red ring LED goes from 3V3 to this pin. Debounced in code.
GPIO61k → right dock pin 2 → right servoPWM out, 50 Hz1241 µs at DRS, 1756 µs at the airbrake: mirrored, because this servo is turned round.
GPIO10330 Ω → light bar DINData out13 LEDs. 3.3 V data is enough while they run from the battery rail.
5VVBAT through the 1N5819Power inThe board’s regulator makes 3.3 V from it.
3V3Knob (through 4.7k), ID pull-upPower outUnder 1 mA in total.
AvoidGPIO2, GPIO8, GPIO9Boot pins. GPIO8 is the onboard LED, GPIO9 the BOOT button.
SpareGPIO7, GPIO20, GPIO21Free for later additions, such as endplate LEDs.
Battery life

Power budget

PartDraw from the battery
ESP32-C3, Wi-Fi off~20 mA
Knob (10k + 4.7k across 3.3 V)~0.2 mA
13-LED light bar at 15% (each LED uses ~1 mA even when dark)13–30 mA
Power-button ring LED5–10 mA
MT3608 boost, idling2–4 mA
Two servos, holding still10–20 mA (estimate)
Total, switched on~50–85 mA

About 35–55 hours of switched-on time per charge from the 2800 mAh cell. A full charge takes about 3 hours.

While the wing moves, the two servos together pull up to about 0.4 A at 5 V. That’s roughly 0.6 A from the battery through the boost, for a third of a second per move. The cell, the charger’s protection (trips at about 3 A) and 26 AWG wire all handle that easily.

The servos’ currents are estimates: they’re too small to come with a datasheet. Stage 7 measures them.

Read before soldering

Rules that prevent damage

  1. 1
    All grounds go to the charger’s OUT−, never to B−. B− is the raw battery, and wiring to it skips the protection.
  2. 2
    Set the boost to 5.0 V before connecting anything to its output. MT3608 boards ship set to random voltages, sometimes over 20 V, and the servos take 6 V at most. Power it with nothing attached, turn the small screw on the blue trimmer until the multimeter reads 5.0 V, and only then wire the docks.
  3. 3
    Measure before you connect. Check each rail’s voltage and polarity with the multimeter every time before plugging a board in.
  4. 4
    Treat the cell with respect. Always keep it in its holder, never let metal touch both ends, and never carry it loose in a pocket or bag.
  5. 5
    Charge with the power button off, and lift the necks off with the power off.
  6. 6
    Plugging into the laptop is safe. The diode stops the ESP32’s USB 5 V flowing back into the battery. Press the power button on too if you want the servos and the light bar to work while plugged in.
  7. 7
    The airbrake button’s LED goes to 3V3, never to 5 V or the battery rail. Its other end is on GPIO5, so anything above 3.3 V there would reach the pin.
  8. 8
    Don’t push the upper element by hand. The servos hold it through tiny plastic gears that strip easily. Move it with the knob, and calibrate with the knob too.
What the code does

Firmware behaviour

Power on Light-bar self-test 1.5 s, wing holds Wing check + battery read ID, 2 s green bar Running knob → −4° to 30° button in → airbrake Low battery amber blink, keeps going Test + calibrate 4 ends: L/R × DRS/brake No wing servos off, centre LED blue Critical park in DRS, LEDs off, sleep <3.5 V <3.3 V button held in at power-up ID reads 3.3 V necks docked
Every change of state prints a line to the USB log. The ID is checked again every 2 seconds, so docking the necks while the base is on is picked up without a restart. Doing it with the power off is still the rule.

The firmware compiles for the ESP32-C3 and runs in Wokwi, a free browser-based ESP32 simulator. Wokwi has no linear servos, but two hobby servos there take the same pulses and swing opposite ways, so the timing and state logic can be checked before any parts arrive.

Build order

Build and test, one part at a time

Each stage adds one part and has its own small test, so if a stage fails the problem is in the last thing you added. Stages 1–4 run from the laptop’s USB with no battery involved.

0 of 11 stages done

  1. Stage 0

    Set up and first soldering

    Install Arduino IDE 2, the ESP32 board package and the libraries. Board: “ESP32C3 Dev Module”, with “USB CDC On Boot” enabled. Solder header pins onto the ESP32 as practice joints, the normal way: long ends down, black plastic strips underneath. Leave the strips on: the base is drawn for that 11 mm stack, so the ESP32’s USB-C meets its opening.

    Pass: the ESP32 appears as a COM port when plugged in.

  2. Stage 1

    Blink and log

    Upload a sketch that blinks the onboard LED and prints to the Serial Monitor.

    Pass: the LED blinks and text appears in the monitor.

  3. Stage 2

    Light bar

    Cut 13 LEDs (217 mm) from the strip, cutting across the copper pads, and solder 3 wires to the input end (the arrows point away from it). Then cut it again after the 2nd and the 11th LED, and join the three pieces with three 2 cm wires across each cut (+5V to +5V, Do to Din, GND to GND): a strip can’t bend sideways, so the two end pieces tilt down with the lid. On the bench, power them from the ESP32’s 5V pin (USB) and upload the full firmware.

    Pass: all 13 LEDs grow from the centre in red, green and blue, then the battery gauge shows cyan (USB power).

  4. Stage 3

    Airbrake button

    Find the button’s C and NO pins with the continuity beep (they connect while it’s pressed in), and its two LED pins (marked + and −). Solder C to GND and NO to GPIO5, LED+ to 3V3, and a short jumper from LED− to NO, so the ring lights while the button is in. Never take the LED to 5 V: it would put 5 V on GPIO5.

    Pass: the log prints ON and OFF exactly once per press, and the ring lights while the button is in.

  5. Stage 4

    Knob

    Wire 3V3 → 4.7k → one outer leg of the potentiometer, the other outer leg → GND, and the middle leg → GPIO1. Type s with the knob fully left, then fully right.

    Pass: the status line reads roughly 60 mV and 2150 mV at the two ends. Put your two readings into KNOB_MIN_MV and KNOB_MAX_MV.

  6. Stage 5

    Battery side, on its own

    With the ESP32 disconnected: cell in holder → charger → power button. Measure the rail with the button on and off, then charge over USB-C. Add the diode and the divider and measure again.

    Pass: 3.5–4.2 V on the rail when on, 0 V when off, the charge LED changes when full, and the divider reads half the rail.

  7. Stage 6

    5 V rail, still nothing attached

    Connect the MT3608 input to the battery rail. With no load, turn its trimmer until the output reads 5.0 V. Add the 1000 µF capacitor (stripe to ground) and measure again.

    Pass: 4.9–5.1 V on V5, steady for a minute.

  8. Stage 7

    Servos on the bench

    Set REQUIRE_WING_ID = false in config.h. Wire GPIO3 → 1k → the left servo’s signal wire and GPIO6 → 1k → the right one’s, with V5 and GND to their red and black wires. Turn the knob slowly end to end. Put the multimeter in series with V5 to measure the current, still and moving.

    Pass: both sliders move smoothly about 4 mm in opposite directions, the ESP32 never resets, and the currents are noted in the log book.

  9. Stage 8

    Dock connectors and wing ID

    Put a magnetic connector in each neck’s path, wired as in the pinout table, with the 10k ID resistor on the left neck’s side. Set REQUIRE_WING_ID back to true.

    Pass: with the left neck docked the log reads about 1.65 V and “GT3 RS replica”; undocked, it reads about 3.3 V and “no wing”, and both servos stop.

  10. Stage 9

    Everything on battery, then calibrate

    Mount the servos in the necks’ bays and screw the covers on, fit the push rods and the wing, and run test-and-calibrate mode for all four ends with the printed angle gauge.

    Pass: every light-bar state appears, the knob sweeps the upper element smoothly from −4° to 30°, the airbrake button snaps it to the airbrake, and both ends of the upper element sit at the same angle.

  11. Stage 10

    Permanent build

    Snap the perfboard’s front row of holes off (score along the row on both sides and bend), so the ESP32 can reach the front wall. Move the circuit onto it, with the ESP32’s sockets in the 2nd and 8th hole columns from the left, and the off-board wires on straight header pins with 1-pin Dupont plugs cut from the jumper wires (solder the silicone wire to the stub and heat-shrink it). Slide the board into its guides from the back until it touches the front wall; slide the charger into its own guides the same way. Stick the three LED-strip pieces in the diffuser’s channel (LEDs facing out), glue the diffuser behind the notch, and fit the controls in the side walls. Run the wires through the clips. Then the lid: four side screws and the four neck screws.

    Pass: both USB-C cables plug in fully from outside, and stage 9’s checks still pass with the lid screwed down.

“Buy this” checked 20 Oct 2026 · backups 13 Oct · prices in CAD before tax

Shopping list

Everything for one complete replica build, with a backup for each part in case the first one sells out. Rows marked new are new for the replica. Nothing has been ordered. Recheck stock on the day you order: several items show only a few left.

PartBuy thisBackupWhy
Electronics
MicrocontrollerESP32-C3 SuperMini, 4-pack
$30.99 · Prime
Seeed XIAO ESP32-C3
$31.06 · ships from Amazon US, ~2 weeks
The brain; spares for testing
Linear servos new1.5 g micro linear servos, 2 pcs (21.2 × 15.0 × 6.0 mm, 3.7–6 V)
$26.99 · arrives tomorrow, 10 left
1.5 g micro linear servos, a left and a right
$28.99 · arrives tomorrow, 10 left
One per neck. The pods are drawn for 21.4 × 15.2 × 6: measure one before printing them
KnobB10K potentiometers + black aluminium knobs, 20 sets
$14.99 · Prime
JZK B10K potentiometers with knobs, 10
$12.05 · Prime
16 mm body, M7 bushing (7 mm hole in the plinth’s right wall)
Airbrake button newuxcell 12 mm latching, raised head, red 3–6 V LED ring
$13.99 · arrives tomorrow
16 mm latching, red 3–6 V LED (choose “Red, 3-6VDC”)
$13.39 · Oct 29 – Nov 5. Needs the hole widened to 16.4 mm (switch_hole_d)
Airbrake, left wall, replacing the guarded switch: flush, and its ring lights while the airbrake is on
Power button16 mm latching, 3–6 V power-symbol LED, blue
$9.39 · not Prime: Nov 2–12
Gebildet 16 mm latching, 2 pcs
$11.99 · Prime, but a 12 V ring: barely lights at battery voltage
On/off, right wall. Every Prime option has a 12 V ring
Light barBTF-LIGHTING WS2812B, 1 m, 60/m
$16.19 · arrives tomorrow
WS2812B, 5 m, 60/m, black
$25.99 · Prime
Cut 13 LEDs (217 mm) for the slot across the back. The black 1 m strip from the last list now ships Nov 11–19
ChargerTP4056 USB-C with protection, 3 pcs
$9.50 · Prime
TP4056 USB-C, 10 pcs
$12.99 · Prime
18650 holderSingle 18650 holders with leads, 5 pcs
$10.98 · Prime
18650 holders, 10 pcs
$9.99 · Prime
5 V boostDAOKI MT3608 boost, 5 pcs
$10.29 · Prime
Eiechip MT3608 boost
$18.69 · Prime
Set it to 5.0 V before connecting anything
Magnetic connectorMagnetic pogo pins, 4-pin, 2.54 mm, straight, 2 pairs
$18.99 · Prime; this link is the 4-pin version
Same, right-angle, 4-pin, 2 pairs
$15.99 · Prime
One pair in each neck’s foot. The lid pockets are drawn 14 × 6 × 2.5: measure one before printing
DiodesDiode kit with 1N5819
$10.00 · Prime
Chanzon 1N5819, 100 pcs
$8.59 · third-party seller, slow
1000 µF capacitors1000 µF 16 V
$12.99 · Prime: Oct 28
Electrolytic capacitor kit
$18.99 · Prime
Steadies the 5 V rail when both servos start
Ceramic capacitors24-value monolithic kit (has 100 nF)
$17.99 · Prime
BOJACK 15-value, 600 pcs
$21.99 · Prime
ID input
Resistors25-value 1/4 W kit
$12.99 · Prime
BOJACK 25-value, 1000 pcs
$19.99 · Prime
Covers 330 Ω, 1k, 4.7k, 10k, 100k
Perfboard + headersMiuzei 71-pc prototype kit (boards, male and female headers, terminals)
$28.49 · Prime
BOJACK boards + Glarks headers (B091PZQ4W7, B076GZXW3Z)
$21.99 + $18.94 · Prime
The permanent board, with sockets
BreadboardDEYUE 3 × 830 + jumper wires
$24.99 · Prime
ELEGOO 3 × 830 + jumper wires (B01EV6LJ7G, B0BTT48V7P)
$12.99 + $15.99 · Prime
Bench tests
Hookup wireBOJACK 26 AWG silicone
$22.99 · Prime
BOJACK 28 AWG silicone
$22.99 · Prime
Four wires fit each neck’s 3 mm channel
Heat shrinkASHINER 580 pcs
$14.99 · Prime
Ginsco 730 pcs
$13.99 · Prime
Mechanical
2 mm carbon rodMECCANIXITY 2 × 400 mm, 5 pcs
$18.69 · Prime
None in stock that clearly says 2 mm: the old backup’s listing now says both 1.5 and 2 mmMain-element spar, 352 mm
1.5 mm steel rod new304 stainless round rod, 1.5 × 400 mm, 10 pcs
$10.99 · Oct 23, only 1 left. One line of the listing says 1 mm: measure it when it arrives
uxcell 1.5 × 350 mm stainless rod, 10 pcs
$14.99 · Oct 22, 2 left. Too short for one piece: use two that meet in the middle
The upper element’s hinge pin, 356 mm through both endplates
1 mm music wire newSpring steel piano wire, 1 mm, 1 m
$11.99 · arrives tomorrow
Yibuy piano wire, 1 mm, 1 m
$12.99 · arrives tomorrow, 6 left
The two push rods (27 mm each, with a bend at each end). It’s hard: cut it at the root of the side cutters
ScrewsM2/M3 socket cap kit, 420 pcs
$17.99 · Prime
M2–M5 kit, 1415 pcs
$27.99 · Prime
M3 for the neck docks and the 4 lid side screws (M3 × 8), M2 for the pods. The iron kit’s inserts cover the 8 needed
Glue newGorilla Super Glue Gel
$9.34 · arrives tomorrow
Gorilla Epoxy, clear, gap filling
$9.97 · arrives tomorrow
Neck halves, and every plan B joint. Epoxy is better where a gap needs filling
Tools
Iron + heat-set insertsPreciva soldering iron + M3 inserts kit
$35.99 · Prime
80 W iron + HANGLIFE M3 inserts (B097XX76V4, B0CS6VZYL8)
$25.98 + $10.99 · Prime
The inserts go in the four dock pillars
SolderTOWOT 63/37 rosin core
$12.99 · Prime
TOWOT 60/40, 0.8 mm
$11.67 · Prime
Digital calipersDigital caliper, 150 mm
$11.99 · Prime
Kynup digital caliper
$34.99 · Prime
Measure the real parts before printing
Multimeter (skip if owned)AstroAI 2000
$21.99 · Prime
TESMEN TM-510
$23.99 · Prime
Not on Amazon
Battery cells × 2Molicel P28A 18650, flat top
Planet of the Vapes Canada · C$13.95 each (13 Oct)
Clear Sky Vapes (Ottawa)
C$16.99 each (13 Oct)

Totals: Amazon about $459, of which about $243 is tools, kits and glue you keep (skip the multimeter if you have one: −$22). Two cells about $28 plus shipping. With the library printing (about $67 for plan B: 450 g in about 22 two-hour jobs, fit coupons and angle gauge included; about $60 for plan A), the whole replica lands near $554 before tax, about $52 less than the centre-pod version, mostly because the $100 PQ12 is gone.

Arriving later: the 1.5 mm steel rod (Oct 23), the 1000 µF capacitors (Oct 28) and the power button (Nov 2–12, not Prime). They’re needed at build stages 9, 6 and 5, so they won’t hold anything up. Everything else arrives within a day or two.

Removed for the replica: the PQ12-R actuator, the BSS138 level shifter, the HT7550 regulators and the 4 mm carbon rod. Removed earlier: the MG90S servo and pull-pull parts, the VL53L0X hand sensor, the 3 mm carbon rod and the pre-wired battery pack.

Firmware v2 · two servos · compiled clean for the ESP32-C3

Firmware files

These are the four files for a Wokwi simulator project. Open wokwi.com/projects/new/esp32-c3 and replace sketch.ino and diagram.json with the copies below. Add config.h and libraries.txt with the small arrow next to the file tabs (New file…), then press play. For the real board, use the same two code files in the Arduino IDE, with the #define SIMULATION line in config.h commented out.

sketch.inoThe firmware. Identical to active_wing/active_wing.ino.706 lines
// ============================================================================
//  Active desk wing v2 (1:5 GT3 RS replica): firmware for the ESP32-C3 SuperMini
//
//  Board:     "ESP32C3 Dev Module"   (Tools > USB CDC On Boot: Enabled)
//  Libraries: ESP32Servo (Kevin Harrington), Adafruit NeoPixel
//  Settings:  config.h
//
//  What it does
//    Knob                                        -> upper element angle: fully left = DRS (-4 deg, slot open),
//                                                   fully right = airbrake (30 deg), anything between
//    Airbrake button pressed in (it latches)     -> airbrake, whatever the knob says; its red ring lights
//    Button held in while powering up            -> test + calibrate mode (the knob trims each end of each side)
//    Button pressed three times within 2 s       -> demo loop on/off (turning the knob stops it)
//                                                   (in test mode: change which side you are trimming)
//    Battery below 3.5 V -> amber warning; below 3.3 V -> park the wing in DRS and sleep
//
//  The two micro linear servos stand in bays inside the neck heads, behind red covers. They always move
//  together: the firmware tracks one position (0 = DRS, 1 = airbrake) and turns it into each servo's own
//  pulse, so each side has its own calibrated ends. The right servo is turned round, so its pulses run
//  the other way.
//
//  Serial monitor at 115200 baud. Type h for the command list.
// ============================================================================

#include <Preferences.h>
#include <ESP32Servo.h>
#include <Adafruit_NeoPixel.h>
#include "esp_sleep.h"
#include "config.h"

// ---------------------------------------------------------------------------
// Types and state (declared before any function so the Arduino IDE's
// automatic prototypes can see them)
// ---------------------------------------------------------------------------
enum class Mode { SelfTest, Gauge, Run, Test, Critical };
enum class Wing { None, GT3RS, Unknown };

struct Rgb { uint8_t r, g, b; };
const Rgb RED    = {255, 15, 8};
const Rgb GREEN  = {25, 255, 60};
const Rgb BLUE   = {25, 75, 255};
const Rgb WHITE  = {230, 235, 255};
const Rgb AMBER  = {255, 128, 0};
const Rgb VIOLET = {165, 45, 255};
const Rgb CYAN   = {0, 215, 255};

constexpr int LEFT = 0, RIGHT = 1;
const char* const SIDE_NAME[2] = {"left", "right"};
const int SERVO_PIN[2]  = {PIN_SERVO_L, PIN_SERVO_R};
const int DEF_DRS[2]    = {SERVO_L_DRS_US, SERVO_R_DRS_US};
const int DEF_BRAKE[2]  = {SERVO_L_BRAKE_US, SERVO_R_BRAKE_US};
const char* const KEY_DRS[2]   = {"l_drs", "r_drs"};
const char* const KEY_BRAKE[2] = {"l_brk", "r_brk"};
constexpr int LED_MID = LED_COUNT / 2;

Servo servo[2];
Adafruit_NeoPixel leds(LED_COUNT, PIN_LEDS, NEO_GRB + NEO_KHZ800);
Preferences prefs;

struct State {
  Mode mode = Mode::SelfTest;
  uint32_t modeAt = 0;

  // airbrake button (latching: pressed in = ON)
  bool switchOn = false, switchRaw = false;
  uint32_t switchChangedAt = 0;
  uint32_t flips[3] = {0, 0, 0};

  // knob: 0 = fully left (DRS), 1 = fully right (airbrake)
  int knobMv = 0;
  float knob = 0;        // smoothed
  float knobSet = 0;     // what the wing follows: moves in KNOB_STEP steps so the servos don't hunt
  bool knobReady = false;

  // demo
  bool demo = false;
  uint32_t demoAt = 0;
  float demoKnob = 0;    // knob position when the demo started

  // battery
  float vbat = 0, battCal = 1.0f;
  bool onUsb = false, lowBat = false;
  int lowCount = 0, clearCount = 0, critCount = 0;

  // wing
  Wing wing = Wing::None;
  int idMv = 0;

  // servos: each side's two ends, and one shared position from 0 (DRS) to 1 (airbrake)
  int drs[2] = {SERVO_L_DRS_US, SERVO_R_DRS_US};
  int brake[2] = {SERVO_L_BRAKE_US, SERVO_R_BRAKE_US};
  int sent[2] = {0, 0};
  bool attached = false;
  float pos = 0, target = 0;
  float moveFrom = 0, moveTo = 0;
  uint32_t moveStart = 0, moveDur = 0;
  bool moving = false;

  // test / calibrate: the knob trims the selected end of the selected side, relative to where it was
  // when you picked them
  int calSide = LEFT;
  bool calBrake = false, calStarted = false, calDirty = false;
  float calRef = 0;
  int calBase = 0;
  uint32_t calChangedAt = 0, calPrintAt = 0, savedAt = 0;

  // timers
  uint32_t lastTick = 0, nextBatt = 0, nextId = 0, nextStatus = 0;
} S;

// serial command buffer
char cmdBuf[24];
int cmdLen = 0;
uint32_t cmdLastAt = 0;

// ---------------------------------------------------------------------------
// Small helpers
// ---------------------------------------------------------------------------
const char* modeName(Mode m) {
  switch (m) {
    case Mode::SelfTest: return "self-test";
    case Mode::Gauge:    return "battery gauge";
    case Mode::Run:      return "running";
    case Mode::Test:     return "test + calibrate";
    case Mode::Critical: return "critical battery";
  }
  return "?";
}

const char* wingName(Wing w) {
  switch (w) {
    case Wing::None:    return "no wing";
    case Wing::GT3RS:   return "GT3 RS replica";
    case Wing::Unknown: return "unknown wing";
  }
  return "?";
}

void setMode(Mode m, uint32_t now) {
  S.mode = m;
  S.modeAt = now;
  Serial.printf("[mode] %s\n", modeName(m));
}

float readMv(int pin, int samples) {
  uint32_t sum = 0;
  for (int i = 0; i < samples; i++) sum += analogReadMilliVolts(pin);
  return (float)sum / samples;
}

bool wingReady() {
  return !REQUIRE_WING_ID || S.wing == Wing::GT3RS;
}

// +1 if this side's pulse rises toward the airbrake, -1 if it falls (from the defaults, so a calibration
// can never flip it)
int moreFlap(int side) {
  return DEF_BRAKE[side] >= DEF_DRS[side] ? 1 : -1;
}

int pulseAt(int side, float pos) {
  return (int)lroundf(S.drs[side] + (S.brake[side] - S.drs[side]) * pos);
}

// ---------------------------------------------------------------------------
// Calibration storage (flash, survives power-off)
// ---------------------------------------------------------------------------
// Each end may only be trimmed CAL_WINDOW_US either side of its default, so a slip of the
// knob can't drive the linkage far past the upper element's real travel.
int calClamp(int us, int side, bool brake) {
  int def = brake ? DEF_BRAKE[side] : DEF_DRS[side];
  return constrain(us, max(SERVO_PULSE_MIN_US, def - CAL_WINDOW_US), min(SERVO_PULSE_MAX_US, def + CAL_WINDOW_US));
}

void printCalibration(const char* what) {
  Serial.printf("[cal] %s: left DRS %d / airbrake %d us, right DRS %d / airbrake %d us\n", what,
                S.drs[LEFT], S.brake[LEFT], S.drs[RIGHT], S.brake[RIGHT]);
}

void loadCalibration() {
  for (int i = 0; i < 2; i++) {
    S.drs[i]   = calClamp(prefs.getInt(KEY_DRS[i], DEF_DRS[i]), i, false);
    S.brake[i] = calClamp(prefs.getInt(KEY_BRAKE[i], DEF_BRAKE[i]), i, true);
  }
  S.battCal = constrain(prefs.getFloat("batt_cal", 1.0f), 0.8f, 1.2f);
  printCalibration("loaded");
  Serial.printf("[cal] battery x%.3f\n", S.battCal);
}

void saveCalibration(uint32_t now) {
  for (int i = 0; i < 2; i++) {
    prefs.putInt(KEY_DRS[i], S.drs[i]);
    prefs.putInt(KEY_BRAKE[i], S.brake[i]);
  }
  S.savedAt = now;
  printCalibration("saved");
}

void resetCalibration() {
  for (int i = 0; i < 2; i++) {
    S.drs[i] = DEF_DRS[i];
    S.brake[i] = DEF_BRAKE[i];
    prefs.remove(KEY_DRS[i]);
    prefs.remove(KEY_BRAKE[i]);
  }
  printCalibration("reset to defaults");
}

int& calPulse() {
  return S.calBrake ? S.brake[S.calSide] : S.drs[S.calSide];
}

// Start trimming from the selected end's current value: the knob's position right now means "no change".
void calRebase() {
  S.calRef = S.knob;
  S.calBase = calPulse();
}

void calSelectSide(int side) {
  S.calSide = side;
  S.calStarted = false;      // testLogic rebases and announces it
}

// ---------------------------------------------------------------------------
// Inputs
// ---------------------------------------------------------------------------
void updateSwitch(uint32_t now) {
  bool raw = digitalRead(PIN_SWITCH) == LOW;
  if (raw != S.switchRaw) {
    S.switchRaw = raw;
    S.switchChangedAt = now;
  }
  if (raw == S.switchOn || now - S.switchChangedAt < SWITCH_DEBOUNCE_MS) return;

  S.switchOn = raw;
  Serial.printf("[button] %s\n", raw ? "ON" : "OFF");
  if (S.mode != Mode::Run && S.mode != Mode::Test) return;

  // three presses within the window: demo on/off (running) or the other side (test mode). The button latches,
  // so its presses alternate ON and OFF: every change counts.
  S.flips[0] = S.flips[1];
  S.flips[1] = S.flips[2];
  S.flips[2] = now;
  if (S.flips[0] != 0 && now - S.flips[0] <= DEMO_FLIPS_WINDOW_MS) {
    S.flips[0] = S.flips[1] = S.flips[2] = 0;
    if (S.mode == Mode::Test) {
      calSelectSide(1 - S.calSide);
      return;
    }
    S.demo = !S.demo;
    S.demoAt = now;
    S.demoKnob = S.knobSet;
    Serial.printf("[demo] %s\n", S.demo ? "on" : "off");
  }
}

// Reads the knob, smooths it, and moves knobSet only in KNOB_STEP steps (with the two ends snapping
// to exactly 0 and 1), so ADC noise never makes the servos hunt.
void updateKnob() {
  S.knobMv = (int)readMv(PIN_KNOB, 8);
  float f = constrain((float)(S.knobMv - KNOB_MIN_MV) / (float)(KNOB_MAX_MV - KNOB_MIN_MV), 0.0f, 1.0f);
  if (KNOB_REVERSED) f = 1.0f - f;
  if (!S.knobReady) {
    S.knob = S.knobSet = f;
    S.knobReady = true;
    return;
  }
  S.knob += (f - S.knob) * KNOB_SMOOTH;
  float k = S.knob < 0.01f ? 0.0f : S.knob > 0.99f ? 1.0f : S.knob;
  bool snapEnd = (k == 0.0f || k == 1.0f) && k != S.knobSet;
  if (snapEnd || fabsf(k - S.knobSet) >= KNOB_STEP) S.knobSet = k;
}

void enterCritical(uint32_t now);

void updateBattery(uint32_t now) {
  S.vbat = readMv(PIN_BATT, BATT_SAMPLES) * BATT_DIVIDER / 1000.0f * S.battCal;
  bool usb = S.vbat < BATT_ABSENT_V;
  if (usb != S.onUsb) {
    S.onUsb = usb;
    Serial.println(usb ? "[batt] no battery reading: power button off, running from USB"
                       : "[batt] battery connected");
  }
  if (S.onUsb) {
    S.lowBat = false;
    S.lowCount = S.clearCount = S.critCount = 0;
    return;
  }

  S.critCount = S.vbat < BATT_CRIT_V ? S.critCount + 1 : 0;
  S.lowCount  = S.vbat < BATT_LOW_V  ? S.lowCount + 1  : 0;
  if (!S.lowBat && S.lowCount >= BATT_CONFIRM) {
    S.lowBat = true;
    Serial.printf("[batt] low: %.2f V\n", S.vbat);
  }
  if (S.lowBat) {
    S.clearCount = S.vbat > BATT_LOW_CLEAR_V ? S.clearCount + 1 : 0;
    if (S.clearCount >= BATT_CONFIRM) {
      S.lowBat = false;
      Serial.printf("[batt] ok again: %.2f V\n", S.vbat);
    }
  }
  if (S.critCount >= BATT_CONFIRM && S.mode != Mode::Critical) enterCritical(now);
}

void updateWing(uint32_t now) {
  S.idMv = (int)readMv(PIN_WINGID, 8);
  Wing w = Wing::Unknown;
  if (S.idMv > ID_NONE_MV) w = Wing::None;
  else if (S.idMv >= ID_GT3_MIN_MV && S.idMv <= ID_GT3_MAX_MV) w = Wing::GT3RS;
  if (w == S.wing) return;
  S.wing = w;
  Serial.printf("[wing] %s (%d mV)\n", wingName(w), S.idMv);
}

// ---------------------------------------------------------------------------
// Servos: eased moves, hard limits
// ---------------------------------------------------------------------------
void writeServos() {
  for (int i = 0; i < 2; i++) {
    int us = constrain(pulseAt(i, S.pos), SERVO_PULSE_MIN_US, SERVO_PULSE_MAX_US);
    if (us != S.sent[i]) {
      servo[i].writeMicroseconds(us);
      S.sent[i] = us;
    }
  }
}

void servosAttach() {
  if (S.attached) return;
  for (int i = 0; i < 2; i++) {
    servo[i].setPeriodHertz(50);
    servo[i].attach(SERVO_PIN[i], SERVO_PULSE_MIN_US, SERVO_PULSE_MAX_US);
    S.sent[i] = 0;
  }
  S.attached = true;
  writeServos();
  Serial.printf("[servo] on: left %d us, right %d us\n", S.sent[LEFT], S.sent[RIGHT]);
}

// Stops the pulses. The servos' lead screws hold the upper element where it is.
void servosRelease() {
  if (!S.attached) return;
  for (int i = 0; i < 2; i++) servo[i].detach();
  S.attached = false;
  Serial.println("[servo] off (holding position)");
}

// pos: 0 = DRS, 1 = airbrake
void setTarget(float pos, uint32_t now) {
  pos = constrain(pos, 0.0f, 1.0f);
  if (fabsf(pos - S.target) < 0.001f) return;
  S.target = pos;
  S.moveFrom = S.pos;
  S.moveTo = pos;
  S.moveStart = now;
  S.moveDur = (uint32_t)(SERVO_FULL_MOVE_MS * fabsf(pos - S.pos));
  if (S.moveDur < 40) S.moveDur = 40;
  S.moving = true;
}

void updateServos(uint32_t now) {
  if (!S.attached) {                     // no wing: the move waits, and starts from here once one is docked
    S.moveStart = now;
    return;
  }
  if (S.moving) {
    float t = (float)(now - S.moveStart) / (float)S.moveDur;
    if (t >= 1) {
      t = 1;
      S.moving = false;
    }
    float eased = t * t * (3 - 2 * t);   // smooth start and stop
    S.pos = S.moveFrom + (S.moveTo - S.moveFrom) * eased;
  }
  writeServos();                         // also picks up calibration changes while standing still
}

// ---------------------------------------------------------------------------
// Modes
// ---------------------------------------------------------------------------
void enterCritical(uint32_t now) {
  S.demo = false;
  Serial.printf("[batt] critical %.2f V: parking the wing in DRS, then sleeping\n", S.vbat);
  setMode(Mode::Critical, now);
}

void runLogic(uint32_t now) {
  if (S.demo && fabsf(S.knobSet - S.demoKnob) >= KNOB_DEMO_CANCEL) {
    S.demo = false;
    Serial.println("[demo] off (knob turned)");
  }
  float f;
  if (S.demo) {
    uint32_t t = (now - S.demoAt) % 8000;
    f = t < 2000 ? 0.0f : t < 4000 ? 0.5f : t < 6000 ? 1.0f : 0.0f;
  } else if (S.switchOn) {
    f = 1.0f;                       // airbrake override
  } else {
    f = S.knobSet;
  }
  setTarget(f, now);
}

// Test + calibrate: the button picks which end you are trimming (in = airbrake, out = DRS) and both sides
// go there, so you can match them by eye. Three presses change the side (left first). Turning the knob
// right adds angle, left takes it away (a full turn = CAL_KNOB_RANGE_US). The values save themselves once
// the knob has been still for CAL_SAVE_AFTER_MS.
void testLogic(uint32_t now) {
  if (!S.calStarted || S.switchOn != S.calBrake) {
    S.calStarted = true;
    S.calBrake = S.switchOn;
    calRebase();
    Serial.printf("[cal] trimming the %s servo, %s end: %d us\n", SIDE_NAME[S.calSide],
                  S.calBrake ? "airbrake" : "DRS", S.calBase);
  }
  int &p = calPulse();
  int want = calClamp(S.calBase + moreFlap(S.calSide) * (int)lroundf((S.knob - S.calRef) * CAL_KNOB_RANGE_US),
                      S.calSide, S.calBrake);
  if (abs(want - p) >= 2) {
    p = want;
    S.calDirty = true;
    S.calChangedAt = now;
    if (now - S.calPrintAt > 250) {
      S.calPrintAt = now;
      Serial.printf("[cal] %s servo, %s end: %d us\n", SIDE_NAME[S.calSide], S.calBrake ? "airbrake" : "DRS", p);
    }
  }
  if (S.calDirty && now - S.calChangedAt >= CAL_SAVE_AFTER_MS) {
    saveCalibration(now);
    S.calDirty = false;
  }
  setTarget(S.calBrake ? 1.0f : 0.0f, now);
}

void criticalLogic(uint32_t now) {
  setTarget(0.0f, now);
  if (now - S.modeAt < 2500 || (S.moving && S.attached)) return;
  leds.clear();
  leds.show();
  servosRelease();
  Serial.println("[sleep] deep sleep. Turn the power off, charge, then turn it on again.");
  Serial.flush();
  esp_deep_sleep_start();
}

// ---------------------------------------------------------------------------
// Light bar: LED_COUNT LEDs across the back of the lid. LED 0 is on the left as you look at the back.
// ---------------------------------------------------------------------------
void px(int i, Rgb c, float level) {
  if (i < 0 || i >= LED_COUNT) return;
  level = constrain(level, 0.0f, 1.0f);
  leds.setPixelColor(i, leds.Color((uint8_t)(c.r * level), (uint8_t)(c.g * level), (uint8_t)(c.b * level)));
}

// fills from the centre outward, like the car's light bar: f = 0 nothing, 1 all of it
void barFromCentre(float f, Rgb c) {
  float reach = f * (LED_MID + 1);
  for (int k = 0; k <= LED_MID; k++) {
    px(LED_MID - k, c, reach - k);
    px(LED_MID + k, c, reach - k);
  }
}

void renderLeds(uint32_t now) {
  leds.clear();
  uint32_t inMode = now - S.modeAt;
  float t = now / 1000.0f;

  switch (S.mode) {
    case Mode::SelfTest: {                 // red, then green, then blue, growing from the centre
      int phase = min<uint32_t>(inMode / 500, 2);
      barFromCentre((inMode % 500) / 500.0f, phase == 0 ? RED : phase == 1 ? GREEN : BLUE);
      break;
    }
    case Mode::Gauge: {                    // battery bar, left to right
      if (S.onUsb) {
        for (int i = 0; i < LED_COUNT; i++) px(i, CYAN, 0.35f);
      } else if (S.lowBat) {
        px(0, AMBER, 1);
      } else {
        float frac = constrain((S.vbat - BATT_EMPTY_V) / (BATT_FULL_V - BATT_EMPTY_V), 0.0f, 1.0f);
        int n = max(1, (int)ceilf(frac * LED_COUNT));
        for (int i = 0; i < n; i++) px(i, GREEN, 1);
      }
      break;
    }
    case Mode::Run: {
      if (!wingReady()) {
        px(LED_MID, BLUE, (now % 1000) < 500 ? 1 : 0);
      } else if (S.demo) {                  // a dot running back and forth
        int n = 2 * (LED_COUNT - 1);
        int k = (now / 70) % n;
        px(k < LED_COUNT ? k : n - k, CYAN, 1);
      } else if (S.pos > 0.02f) {           // wing position, growing from the centre
        barFromCentre(S.pos, S.switchOn ? RED : VIOLET);
      } else {                              // idle heartbeat
        px(LED_MID, WHITE, 0.3f + 0.25f * sinf(t * 2.2f));
      }
      break;
    }
    case Mode::Test: {                     // end LED of the side being trimmed: red = airbrake, white = DRS
      float k = S.knob * (LED_COUNT - 3);  // the LEDs between show the knob
      for (int i = 1; i < LED_COUNT - 1; i++) px(i, CYAN, 0.8f * (k - (i - 1)));
      px(S.calSide == LEFT ? 0 : LED_COUNT - 1, S.calBrake ? RED : WHITE, 1);
      if (!wingReady()) px(LED_MID, BLUE, (now % 1000) < 500 ? 1 : 0);
      if (S.savedAt && now - S.savedAt < 600)
        for (int i = 0; i < LED_COUNT; i++) px(i, GREEN, 1);
      break;
    }
    case Mode::Critical: {                 // three red flashes, then dark
      if (inMode < 1800 && (inMode % 600) < 300)
        for (int i = 0; i < LED_COUNT; i++) px(i, RED, 1);
      break;
    }
  }

  // low battery: the two outer LEDs blink amber in any running state
  if ((S.mode == Mode::Run || S.mode == Mode::Test) && S.lowBat && fmodf(t, 2.0f) < 0.3f) {
    px(0, AMBER, 1);
    px(LED_COUNT - 1, AMBER, 1);
  }
  leds.show();
}

// ---------------------------------------------------------------------------
// Serial commands
// ---------------------------------------------------------------------------
void printHelp() {
  Serial.println(F("Commands (type, then Enter):"));
  Serial.println(F("  h          this help"));
  Serial.println(F("  s          status"));
  Serial.println(F("  d          demo loop on/off"));
  Serial.println(F("  left right test mode: trim the left or the right servo"));
  Serial.println(F("  +  -       test mode: more or less angle at the selected end, 5 us per step"));
  Serial.println(F("  w          test mode: save now (it also saves itself 2 s after the last change)"));
  Serial.println(F("  reset      test mode: all four ends back to the defaults"));
  Serial.println(F("  v3.92      battery: tell it the multimeter reading (volts) to correct the gauge"));
}

void printStatus() {
  Serial.printf("[status] %s | %s (%d mV) | batt %.2f V%s%s | button %s | knob %.0f%% (%d mV) | wing %.0f%% | "
                "left %d us (DRS %d, brake %d) | right %d us (DRS %d, brake %d)%s\n",
                modeName(S.mode), wingName(S.wing), S.idMv, S.vbat, S.onUsb ? " (USB)" : "", S.lowBat ? " LOW" : "",
                S.switchOn ? "ON" : "off", S.knob * 100, S.knobMv, S.pos * 100,
                pulseAt(LEFT, S.pos), S.drs[LEFT], S.brake[LEFT], pulseAt(RIGHT, S.pos), S.drs[RIGHT], S.brake[RIGHT],
                S.attached ? "" : " (servos off)");
}

void runCommand(const char* c) {
  bool test = S.mode == Mode::Test;
  if (!strcmp(c, "left") || !strcmp(c, "right")) {
    if (!test) { Serial.println(F("Only in test mode (hold the button in while powering up).")); return; }
    calSelectSide(c[0] == 'l' ? LEFT : RIGHT);
    return;
  }
  if (!strcmp(c, "reset")) {
    if (!test) { Serial.println(F("Only in test mode.")); return; }
    resetCalibration();
    calRebase();
    S.calDirty = false;
    return;
  }
  switch (c[0]) {
    case 'h': case '?': printHelp(); break;
    case 's': printStatus(); break;
    case 'd':
      if (S.mode == Mode::Run) {
        S.demo = !S.demo;
        S.demoAt = millis();
        S.demoKnob = S.knobSet;
        Serial.printf("[demo] %s\n", S.demo ? "on" : "off");
      }
      break;
    case '+': case '-': {
      if (!test) { Serial.println(F("Only in test mode (hold the button in while powering up).")); break; }
      int &p = calPulse();
      p = calClamp(p + (c[0] == '+' ? 5 : -5) * moreFlap(S.calSide), S.calSide, S.calBrake);
      calRebase();
      S.calDirty = true;
      S.calChangedAt = millis();
      Serial.printf("[cal] %s servo, %s end: %d us\n", SIDE_NAME[S.calSide], S.calBrake ? "airbrake" : "DRS", p);
      break;
    }
    case 'w':
      if (test) { saveCalibration(millis()); S.calDirty = false; } else Serial.println(F("Only in test mode."));
      break;
    case 'v': {
      float real = atof(c + 1);
      if (real < 3.0f || real > 4.3f || S.onUsb) { Serial.println(F("Usage: v3.92 (battery connected, power on)")); break; }
      float raw = S.vbat / S.battCal;
      S.battCal = constrain(real / raw, 0.8f, 1.2f);
      prefs.putFloat("batt_cal", S.battCal);
      Serial.printf("[cal] battery correction x%.3f saved\n", S.battCal);
      break;
    }
    default: Serial.printf("Unknown command '%s'. Type h for help.\n", c); break;
  }
}

void handleSerial(uint32_t now) {
  while (Serial.available()) {
    char ch = (char)Serial.read();
    cmdLastAt = now;
    if (ch == '\n' || ch == '\r') {
      if (cmdLen > 0) {
        cmdBuf[cmdLen] = 0;
        runCommand(cmdBuf);
        cmdLen = 0;
      }
    } else if (cmdLen < (int)sizeof(cmdBuf) - 1 && ch != ' ') {
      cmdBuf[cmdLen++] = tolower(ch);
    }
  }
  // also accept commands sent without a line ending
  if (cmdLen > 0 && now - cmdLastAt > 150) {
    cmdBuf[cmdLen] = 0;
    runCommand(cmdBuf);
    cmdLen = 0;
  }
}

// ---------------------------------------------------------------------------
// Setup and main loop
// ---------------------------------------------------------------------------
void setup() {
  Serial.begin(115200);
  uint32_t t0 = millis();
  while (!Serial && millis() - t0 < 800) delay(10);   // give the USB serial a moment, never wait forever

  pinMode(PIN_SWITCH, INPUT_PULLUP);
  analogReadResolution(12);

  leds.begin();
  leds.setBrightness(LED_BRIGHTNESS);
  leds.clear();
  leds.show();

  Serial.println();
  Serial.println(F("== Active desk wing v2: GT3 RS replica =="));
#ifdef SIMULATION
  Serial.println(F("SIMULATION build: battery and wing ID are the two left-hand knobs"));
#endif
  prefs.begin("wing", false);
  loadCalibration();
  S.pos = S.target = 0.0f;                             // starts in DRS

  updateKnob();
  Serial.printf("[knob] %.0f%% (%d mV)\n", S.knob * 100, S.knobMv);

  uint32_t now = millis();
  updateBattery(now);
  updateWing(now);
  S.lastTick = now;
  S.nextBatt = now + BATT_PERIOD_MS;
  S.nextId = now + ID_PERIOD_MS;
  S.nextStatus = now + STATUS_MS;
  setMode(Mode::SelfTest, now);
  printHelp();
}

void loop() {
  uint32_t now = millis();
  handleSerial(now);
  if (now - S.lastTick < LOOP_MS) return;
  S.lastTick = now;

  updateSwitch(now);
  updateKnob();
  if ((int32_t)(now - S.nextBatt) >= 0) { S.nextBatt = now + BATT_PERIOD_MS; updateBattery(now); }
  if ((int32_t)(now - S.nextId) >= 0)   { S.nextId = now + ID_PERIOD_MS;     updateWing(now); }

  switch (S.mode) {
    case Mode::SelfTest:
      if (now - S.modeAt >= SELFTEST_MS) {
        if (S.switchOn) {
          S.calStarted = false;
          S.calSide = LEFT;
          setMode(Mode::Test, now);
          Serial.println(F("[cal] button in = trim the airbrake end, out = trim the DRS end. Left servo first."));
          Serial.println(F("[cal] turn the knob right for more angle, left for less; it saves itself 2 s after you stop."));
          Serial.println(F("[cal] press the button three times within 2 s (or type left / right) for the other servo."));
        } else {
          setMode(Mode::Gauge, now);
        }
      }
      break;
    case Mode::Gauge:
      if (now - S.modeAt >= GAUGE_MS) setMode(Mode::Run, now);
      break;
    case Mode::Run:      runLogic(now); break;
    case Mode::Test:     testLogic(now); break;
    case Mode::Critical: criticalLogic(now); break;
  }

  bool active = S.mode == Mode::Run || S.mode == Mode::Test || S.mode == Mode::Critical;
  if (active && wingReady()) servosAttach();
  else servosRelease();
  updateServos(now);
  renderLeds(now);

  if (S.mode == Mode::Run && (int32_t)(now - S.nextStatus) >= 0) {
    S.nextStatus = now + STATUS_MS;
    printStatus();
  }
}
config.hSettings, with the SIMULATION line switched on. For the real board, use the same file with that line commented out.83 lines
#pragma once
// ============================================================================
//  Active desk wing v2 (1:5 GT3 RS replica): settings
//  Everything you might want to tune lives here. The main file reads these.
// ============================================================================

// Uncomment to build for the Wokwi simulator: battery and wing ID are then two potentiometers
// (Wokwi has no analog circuits). The code is otherwise identical.
#define SIMULATION

// ---------- Pins (ESP32-C3 SuperMini) ----------
constexpr int PIN_BATT     = 0;   // ADC1: battery divider midpoint (VBAT / 2)
constexpr int PIN_KNOB     = 1;   // ADC1: knob wiper (10k potentiometer, 4.7k in series on its top end)
constexpr int PIN_SERVO_L  = 3;   // left servo signal (left dock connector, pin 3)
constexpr int PIN_WINGID   = 4;   // ADC1: wing ID (10k pull-up in the base, 10k ID resistor in the left neck foot)
constexpr int PIN_SWITCH   = 5;   // latching airbrake button to GND (internal pull-up); its red ring LED sits across it
constexpr int PIN_SERVO_R  = 6;   // right servo signal (right dock connector, pin 3)
constexpr int PIN_LEDS     = 10;  // WS2812B data (light bar), through 330 ohm

// ---------- Servos: 1.5 g micro linear servos (AFRC D1015 type), 9 mm stroke, 900-2100 us ----------
// Both stand on edge in the neck heads, sliders facing inboard, so the right one is turned round: its pulses run the
// other way. Defaults come from the replica's linkage (master dimensions v2.0): the upper element goes from
// -4 deg (DRS, slot open) to 30 deg (airbrake) using 3.9 mm of the stroke. Calibration replaces them.
constexpr int      SERVO_L_DRS_US     = 1759;  // left,  upper element -4 deg (slider 1.9 mm aft of mid-stroke)
constexpr int      SERVO_L_BRAKE_US   = 1244;  // left,  upper element 30 deg (slider 1.9 mm forward)
constexpr int      SERVO_R_DRS_US     = 1241;  // right, upper element -4 deg (turned round: mirror image)
constexpr int      SERVO_R_BRAKE_US   = 1756;  // right, upper element 30 deg
constexpr int      SERVO_PULSE_MIN_US = 950;   // hard limits: nothing outside these is ever sent
constexpr int      SERVO_PULSE_MAX_US = 2050;
constexpr uint32_t SERVO_FULL_MOVE_MS = 350;   // eased travel time for a full DRS <-> airbrake move

// Set to false for bench tests before the dock connectors and the ID resistor exist (build stage 7).
constexpr bool     REQUIRE_WING_ID    = true;

// ---------- Knob ----------
// 3V3 -> 4.7k -> potentiometer -> GND, wiper to GPIO1. The 4.7k keeps the wiper under ~2.25 V,
// below where the C3's ADC tops out (~2.5 V), so the whole turn is usable.
// The status line (type s) shows the knob in mV: set MIN/MAX from the readings at the two ends.
constexpr int      KNOB_MIN_MV        = 60;     // reading with the knob fully left
constexpr int      KNOB_MAX_MV        = 2150;   // reading with the knob fully right
constexpr bool     KNOB_REVERSED      = false;  // true if turning right lowers the wing (or swap the two outer wires)
constexpr float    KNOB_SMOOTH        = 0.25f;  // 0..1 per 10 ms: lower = smoother but slower to follow
constexpr float    KNOB_STEP          = 0.01f;  // ignore changes under 1 % of a turn, so the servos don't hunt
constexpr float    KNOB_DEMO_CANCEL   = 0.10f;  // turning the knob 10 % stops the demo loop

// ---------- Calibration (test mode) ----------
constexpr int      CAL_KNOB_RANGE_US  = 200;    // a full turn of the knob trims the selected end by this much
// Each end stays within +-90 us of its default: about 0.7 mm of slider, about 6 deg of upper element.
// 6 deg past the airbrake end the slot to the main element is down to 1.1 mm, so don't widen this without checking.
constexpr int      CAL_WINDOW_US      = 90;
constexpr uint32_t CAL_SAVE_AFTER_MS  = 2000;   // saves once the knob has been still this long

// ---------- Airbrake button ----------
constexpr uint32_t SWITCH_DEBOUNCE_MS   = 30;
constexpr uint32_t DEMO_FLIPS_WINDOW_MS = 2000; // button pressed three times within 2 s: demo on/off (test mode: other side)

// ---------- Battery ----------
constexpr float    BATT_DIVIDER     = 2.0f;    // 100k + 100k
constexpr float    BATT_FULL_V      = 4.15f;   // for the gauge
constexpr float    BATT_EMPTY_V     = 3.40f;
constexpr float    BATT_LOW_V       = 3.50f;   // amber warning
constexpr float    BATT_LOW_CLEAR_V = 3.60f;
constexpr float    BATT_CRIT_V      = 3.30f;   // park the wing in DRS and sleep
constexpr float    BATT_ABSENT_V    = 2.50f;   // below this the power button is off and USB powers the board
constexpr int      BATT_SAMPLES     = 16;
constexpr uint32_t BATT_PERIOD_MS   = 1000;
constexpr int      BATT_CONFIRM     = 5;       // readings in a row before acting (ignores dips while moving)

// ---------- Wing ID ----------
constexpr int      ID_NONE_MV    = 2400;       // above: no wing (3.3 V reads ~2.5 V+: the C3 ADC tops out near 2.5 V)
constexpr int      ID_GT3_MIN_MV = 1400;       // GT3 RS replica uses a 10k ID resistor, about 1650 mV
constexpr int      ID_GT3_MAX_MV = 1900;
constexpr uint32_t ID_PERIOD_MS  = 2000;

// ---------- Light bar (status LEDs) ----------
constexpr int      LED_COUNT      = 13;        // 13 LEDs at 60/m behind the light-bar slot (216 mm)
constexpr uint8_t  LED_BRIGHTNESS = 38;        // out of 255, about 15 %

// ---------- Timing ----------
constexpr uint32_t SELFTEST_MS = 1500;
constexpr uint32_t GAUGE_MS    = 2000;
constexpr uint32_t LOOP_MS     = 10;           // main loop runs 100 times a second
constexpr uint32_t STATUS_MS   = 10000;        // status line in the log every 10 s
diagram.jsonThe virtual circuit: the 13-LED light bar, two hobby servos standing in for the linear servos, the switch and three knobs.508 lines
{
  "version": 1,
  "author": "Active desk wing v2",
  "editor": "wokwi",
  "parts": [
    {
      "type": "board-esp32-c3-devkitm-1",
      "id": "esp",
      "top": 0,
      "left": 0,
      "attrs": {}
    },
    {
      "type": "wokwi-neopixel",
      "id": "led1",
      "top": -110,
      "left": 20,
      "attrs": {}
    },
    {
      "type": "wokwi-neopixel",
      "id": "led2",
      "top": -110,
      "left": 50,
      "attrs": {}
    },
    {
      "type": "wokwi-neopixel",
      "id": "led3",
      "top": -110,
      "left": 80,
      "attrs": {}
    },
    {
      "type": "wokwi-neopixel",
      "id": "led4",
      "top": -110,
      "left": 110,
      "attrs": {}
    },
    {
      "type": "wokwi-neopixel",
      "id": "led5",
      "top": -110,
      "left": 140,
      "attrs": {}
    },
    {
      "type": "wokwi-neopixel",
      "id": "led6",
      "top": -110,
      "left": 170,
      "attrs": {}
    },
    {
      "type": "wokwi-neopixel",
      "id": "led7",
      "top": -110,
      "left": 200,
      "attrs": {}
    },
    {
      "type": "wokwi-neopixel",
      "id": "led8",
      "top": -110,
      "left": 230,
      "attrs": {}
    },
    {
      "type": "wokwi-neopixel",
      "id": "led9",
      "top": -110,
      "left": 260,
      "attrs": {}
    },
    {
      "type": "wokwi-neopixel",
      "id": "led10",
      "top": -110,
      "left": 290,
      "attrs": {}
    },
    {
      "type": "wokwi-neopixel",
      "id": "led11",
      "top": -110,
      "left": 320,
      "attrs": {}
    },
    {
      "type": "wokwi-neopixel",
      "id": "led12",
      "top": -110,
      "left": 350,
      "attrs": {}
    },
    {
      "type": "wokwi-neopixel",
      "id": "led13",
      "top": -110,
      "left": 380,
      "attrs": {}
    },
    {
      "type": "wokwi-servo",
      "id": "servoL",
      "top": -20,
      "left": -260,
      "attrs": {
        "horn": "single"
      }
    },
    {
      "type": "wokwi-servo",
      "id": "servoR",
      "top": -20,
      "left": 330,
      "attrs": {
        "horn": "single"
      }
    },
    {
      "type": "wokwi-slide-switch",
      "id": "switch",
      "top": 140,
      "left": 180,
      "attrs": {}
    },
    {
      "type": "wokwi-potentiometer",
      "id": "knob",
      "top": 190,
      "left": 260,
      "attrs": {
        "value": "0"
      }
    },
    {
      "type": "wokwi-potentiometer",
      "id": "battery",
      "top": 120,
      "left": -170,
      "attrs": {
        "value": "712"
      }
    },
    {
      "type": "wokwi-potentiometer",
      "id": "wingid",
      "top": 230,
      "left": -170,
      "attrs": {
        "value": "600"
      }
    }
  ],
  "connections": [
    [
      "esp:TX",
      "$serialMonitor:RX",
      "",
      []
    ],
    [
      "esp:RX",
      "$serialMonitor:TX",
      "",
      []
    ],
    [
      "esp:10",
      "led1:DIN",
      "green",
      []
    ],
    [
      "led1:VDD",
      "esp:5V.1",
      "red",
      []
    ],
    [
      "led1:VSS",
      "esp:GND.1",
      "black",
      []
    ],
    [
      "led1:DOUT",
      "led2:DIN",
      "green",
      []
    ],
    [
      "led2:VDD",
      "esp:5V.1",
      "red",
      []
    ],
    [
      "led2:VSS",
      "esp:GND.1",
      "black",
      []
    ],
    [
      "led2:DOUT",
      "led3:DIN",
      "green",
      []
    ],
    [
      "led3:VDD",
      "esp:5V.1",
      "red",
      []
    ],
    [
      "led3:VSS",
      "esp:GND.1",
      "black",
      []
    ],
    [
      "led3:DOUT",
      "led4:DIN",
      "green",
      []
    ],
    [
      "led4:VDD",
      "esp:5V.1",
      "red",
      []
    ],
    [
      "led4:VSS",
      "esp:GND.1",
      "black",
      []
    ],
    [
      "led4:DOUT",
      "led5:DIN",
      "green",
      []
    ],
    [
      "led5:VDD",
      "esp:5V.1",
      "red",
      []
    ],
    [
      "led5:VSS",
      "esp:GND.1",
      "black",
      []
    ],
    [
      "led5:DOUT",
      "led6:DIN",
      "green",
      []
    ],
    [
      "led6:VDD",
      "esp:5V.1",
      "red",
      []
    ],
    [
      "led6:VSS",
      "esp:GND.1",
      "black",
      []
    ],
    [
      "led6:DOUT",
      "led7:DIN",
      "green",
      []
    ],
    [
      "led7:VDD",
      "esp:5V.1",
      "red",
      []
    ],
    [
      "led7:VSS",
      "esp:GND.1",
      "black",
      []
    ],
    [
      "led7:DOUT",
      "led8:DIN",
      "green",
      []
    ],
    [
      "led8:VDD",
      "esp:5V.1",
      "red",
      []
    ],
    [
      "led8:VSS",
      "esp:GND.1",
      "black",
      []
    ],
    [
      "led8:DOUT",
      "led9:DIN",
      "green",
      []
    ],
    [
      "led9:VDD",
      "esp:5V.1",
      "red",
      []
    ],
    [
      "led9:VSS",
      "esp:GND.1",
      "black",
      []
    ],
    [
      "led9:DOUT",
      "led10:DIN",
      "green",
      []
    ],
    [
      "led10:VDD",
      "esp:5V.1",
      "red",
      []
    ],
    [
      "led10:VSS",
      "esp:GND.1",
      "black",
      []
    ],
    [
      "led10:DOUT",
      "led11:DIN",
      "green",
      []
    ],
    [
      "led11:VDD",
      "esp:5V.1",
      "red",
      []
    ],
    [
      "led11:VSS",
      "esp:GND.1",
      "black",
      []
    ],
    [
      "led11:DOUT",
      "led12:DIN",
      "green",
      []
    ],
    [
      "led12:VDD",
      "esp:5V.1",
      "red",
      []
    ],
    [
      "led12:VSS",
      "esp:GND.1",
      "black",
      []
    ],
    [
      "led12:DOUT",
      "led13:DIN",
      "green",
      []
    ],
    [
      "led13:VDD",
      "esp:5V.1",
      "red",
      []
    ],
    [
      "led13:VSS",
      "esp:GND.1",
      "black",
      []
    ],
    [
      "esp:3",
      "servoL:PWM",
      "orange",
      []
    ],
    [
      "servoL:V+",
      "esp:5V.2",
      "red",
      []
    ],
    [
      "servoL:GND",
      "esp:GND.2",
      "black",
      []
    ],
    [
      "esp:6",
      "servoR:PWM",
      "orange",
      []
    ],
    [
      "servoR:V+",
      "esp:5V.2",
      "red",
      []
    ],
    [
      "servoR:GND",
      "esp:GND.2",
      "black",
      []
    ],
    [
      "switch:2",
      "esp:5",
      "yellow",
      []
    ],
    [
      "switch:3",
      "esp:GND.3",
      "black",
      []
    ],
    [
      "knob:SIG",
      "esp:1",
      "blue",
      []
    ],
    [
      "knob:VCC",
      "esp:3V3.1",
      "red",
      []
    ],
    [
      "knob:GND",
      "esp:GND.4",
      "black",
      []
    ],
    [
      "battery:SIG",
      "esp:0",
      "violet",
      []
    ],
    [
      "battery:VCC",
      "esp:3V3.1",
      "red",
      []
    ],
    [
      "battery:GND",
      "esp:GND.5",
      "black",
      []
    ],
    [
      "wingid:SIG",
      "esp:4",
      "gray",
      []
    ],
    [
      "wingid:VCC",
      "esp:3V3.2",
      "red",
      []
    ],
    [
      "wingid:GND",
      "esp:GND.6",
      "black",
      []
    ]
  ],
  "dependencies": {}
}
libraries.txtTells Wokwi which libraries to install.3 lines
# Wokwi installs these automatically
ESP32Servo
Adafruit NeoPixel