Files

poorBird firmware — XIAO ESP32S3 Sense + HLK-LD2410

ESP-side skeleton.

Verified: builds clean from scratch against pioarduino 53.03.13 (Arduino-ESP32 3.1.x / IDF 5.3), no warnings in project sources. 1132 KB flash (34 % of a 3.2 MB OTA slot), 60 KB static RAM.

Not verified: none of it has run on hardware. The LD2410 frame offsets are transcribed from the datasheet, the XIAO status-LED pin has moved between board revisions, and no radio, camera or radar code path has executed. Treat the first bring-up as a debugging session, not a smoke test.

Layout

platformio.ini            build config; the knobs live in [common]
secrets.ini.example       copy to secrets.ini (gitignored) before flashing
partitions/               8 MB, dual OTA slots + rollback  (SPEC C6)
scripts/load_secrets.py   turns secrets.ini into -D flags

include/board_pins.h      ALL wiring in one place, every free pin overridable
include/app_config.h      the full runtime config struct

src/app_config.cpp        NVS load/save, JSON merge from the endpoint, clamps
src/power_mgr.cpp         the deep-sleep on/off switch and its inhibit locks
src/camera_mgr.cpp        OV2640 lifecycle + day/night tuning profiles
src/frame_ring.cpp        PSRAM pre-trigger ring  ← the interesting one
src/ld2410.cpp            radar UART protocol + presence pin
src/net_mgr.cpp           WiFi with bounded retries, clock from the endpoint
src/api_client.cpp        REST client: enroll, ingest, heartbeat, status, config, stream
src/battery.cpp           supply voltage, percentage curves, the OTA gate
src/device_stats.cpp      daily counters in RTC memory, local-midnight rollover
src/nightlight.cpp        night window, illuminator, what to do after dark
src/ota_mgr.cpp           SHA-256 verify, trial boot, automatic rollback
src/stream_session.cpp    time-boxed MJPEG push
src/commands.cpp          the WebUI → device command queue
src/main.cpp              both operating modes

API.md is the contract for the Pi side.

Wiring

LD2410 XIAO GPIO Note
VCC 5V — plain LD2410, no Bluetooth
GND GND —
TX D1 2 ESP receives — measure this, see below
RX D0 1 ESP transmits; 3.3 V clears the module's input threshold
OUT D2 3 active high; RTC-capable, so it doubles as the deep-sleep wake pin — measure this too

Measure OUT and TX with a multimeter before connecting them. The LD2410's logic is supposed to be 3.3 V even on a 5 V supply, but this varies between batches and clones, and the ESP32-S3 is not 5 V tolerant. Wave a hand at the module so OUT asserts, then measure. If either reads ~5 V, drop it with a divider: 10k from the module into the GPIO, 20k from the GPIO to ground. Two minutes now beats discovering a dead pin on a camera you cannot reach.

Baud rate needs no decision. radarBegin() probes 256000, 115200, 57600, 38400 and 9600 and keeps whichever produces valid frames, so a factory-default module and a reconfigured one both just work — and a factory reset (which returns the module to 256000) does not silently take the trigger offline. Pin it with the radar_baud setting if you would rather it not probe.

Optional, nothing wired by default:

Function Default pin Note
Battery sense D3 / GPIO4 needs an external divider — see the diagram in include/battery.h
Divider enable — (-1) MOSFET on the divider's low side, so it only draws during a read
Nightlight — (-1) PWM; drive a MOSFET, never the LED directly
Radar power gate — (-1) only useful for timer-only deep sleep

Still free: D4/GPIO5 + D5/GPIO6 (I²C for a future BME280 or DS3231), D6/GPIO43 + D7/GPIO44 (UART0 — deliberately left for hardware debug). D8–D10 are the Sense board's microSD; leave them if you want local buffering later.

Change any of it with a -D flag, no source edit:

build_flags = ${common.build_flags} -DPIN_RADAR_OUT=4 -DRADAR_BAUD=115200

First flash

cp secrets.ini.example secrets.ini      # then edit it
pio run -e xiao_s3_sense -t upload
pio device monitor

The first build downloads ~1 GB of toolchain and takes about 12 minutes; afterwards a clean rebuild is under a minute.

platformio.ini pins pioarduino 53.03.13 because PlatformIO Core 6.1.x cannot load the current stable release (it needs Core >= 6.2.0). If you run pio upgrade to 6.2.0, you can switch the platform = line to the stable alias and get Arduino 3.3 / IDF 5.5.

On the Pi, generate the enrollment secret with openssl rand -hex 32 and put the same value in both places. On first boot the device trades it for a per-device token, stores that in NVS, and wipes the secret.

Expected first-boot log:

poorBird 0.1.0  (xiao-esp32s3-sense-ld2410)
power: boot #1, wake cause power-on, 0s slept so far
--- poorBird config ---
radar: UART1 @256000 baud (detected) rx=2 tx=1 out=3
radar self-test: 1284 bytes, 7 decoded frames, OUT=0
wifi: 192.168.1.88  rssi -58 dBm
enrolled via stored secret: token + per-device re-enrollment secret stored
time: synced, 2026-09-20T14:31:07Z
camera ready: sensor PID 0x2640, SVGA (800x600) quality=12 psram_free=6784KB
ring: 24 slots x 48KB = 1152KB PSRAM (free 6784KB)
awake mode: pre-trigger ring active (24 frames, ~9.6 s of history)

radar: no UART frames at any baud ⇒ TX and RX are not crossed, the module is not powered, or it is dead. The baud rate is no longer a candidate explanation, since all the plausible rates were tried. The OUT pin path still works in the meantime: set radar_mode: 0 to trigger on it alone.

The two power modes

One flag, deep_sleep_enabled, switchable from the WebUI at runtime.

awake (default) sleep
Camera always initialised off between events
Pre-trigger frames yes, ~10 s of history no
Trigger→first frame effectively negative 1–3 s (SPEC C4)
Command latency one loop tick up to deep_sleep_s
Streaming on demand only from the next wake
ESP current ~80–120 mA tens of µA asleep

Switching it on does not slam the door: the device finishes the current wake (so the ack reaches the Pi) and only then sleeps, giving you sleep_idle_timeout_s to change your mind. Switching it off takes effect at the next wake — unavoidable, that is SPEC C1.

Sleep is blocked outright by refcounted inhibits: an upload in flight, a live stream, an OTA flash, a wake_and_hold. sleep_max_awake_s is a deadlock escape that overrides all of them except OTA — sleeping mid-flash bricks the device.

The honest caveat

The LD2410 draws roughly 80 mA continuously and must stay powered to act as a wake source. So with sleep_wake_on_radar = true, the ESP sleeping at 20 µA saves you almost nothing — the radar dominates. Deep sleep is a real power win only if you either:

  • set sleep_wake_on_radar = false, wake on the timer alone, and power-gate the radar through a MOSFET on PIN_RADAR_EN; or
  • fit an AM312 PIR on PIN_AUX_ADC as the wake source and use the radar only to confirm once awake.

That is a wiring decision. The switch works either way.

Why the ring buffer is the point

SPEC C4 says the first usable frame lands 1–3 s after the bird arrives, by which time a small bird is gone. That is only true if capture starts at the trigger.

Running on mains, the camera captures continuously into a PSRAM ring. On a trigger the device ships pre_roll frames from before it plus post_roll frames from after. Effective latency goes negative and C4 stops being a problem. Cost: ring_frames × ~48 KB of the 8 MB PSRAM — about 1.1 MB at the defaults, for roughly 10 s of history.

This is the single largest quality difference between the battery design in SPEC.md and this one, and it is why the mains decision is worth more than it first looks.

Cameras

The XIAO ESP32S3 Sense ships with an OV2640 on its expansion board, and that is what this firmware drives. The ESP32-S3 handles it better than the original ESP32-CAM does, because the S3 has a dedicated LCD_CAM peripheral rather than repurposing I²S.

Three things worth knowing before you buy or swap anything:

The bare XIAO ESP32S3 cannot take a camera. The DVP pins (GPIO 10–18, 38, 39, 40, 47, 48) are not on the 14 castellated pads — they only come out through the board-to-board connector that the Sense expansion board mates with. "XIAO ESP32S3 + a camera module" is not a working combination; you need the Sense.

You may receive an OV3660 rather than an OV2640. Seeed's wiki still says OV2640, but newer units have reportedly shipped with OV3660. The driver detects the sensor over SCCB at init, so the firmware does not care — it logs the PID (0x2640 / 0x3660 / 0x5640) and reports it in the status payload. An OV3660 gives you QXGA 2048×1536 instead of the OV2640's UXGA ceiling.

The OV5640 is an official drop-in upgrade (Seeed sells it for this board, with a heat sink). 2592×1944 versus the OV2640's 1600×1200, better low light, and autofocus. Whether it is worth it here:

  • For — pixels on target is the real limit when the bird is small in frame.
  • Against — bigger JPEGs mean fewer ring slots and longer uploads, it is slower at full resolution (so a lower ring frame rate and less pre-trigger history), and it runs hot enough to ship with a heat sink. Autofocus is arguably a downside on a fixed-distance feeder, where fixed focus is more predictable and never hunts at the wrong moment.
  • If you switch, drop ring_frames. Twenty-four slots at ~400 KB is 9.6 MB, more than the 8 MB of PSRAM; the ring degrades gracefully and logs, but you want about 12.

The frame size is set by name ("SVGA", "UXGA"), never by number — see API.md for why that matters.

Night, and why the default is to sleep through it

night_behaviour decides what happens between night_start_min and night_end_min (minutes from local midnight; the Pi should push real sunset/sunrise, the 21:00–06:00 defaults are a fallback):

  • 0 capture — keep working, using the cam_night tuning profile and the illuminator if one is fitted.
  • 1 idle — stay awake and reachable, capture nothing.
  • 2 sleep (default) — deep sleep until morning, even when deep_sleep_enabled is false. A camera with no illuminator has nothing to do at 03:00 whether it is mains-powered or not. The cost: unreachable until dawn, so a config change made at 23:00 lands in the morning.

Night sleep never wakes on the radar. The point is to ignore the night, not to photograph every cat that walks past.

Read this before buying an illuminator

The obvious choice is 850 nm or 940 nm IR, because birds barely perceive it and white light at a feeder at night is disruptive. But the OV2640 module on the XIAO Sense has an IR cut filter bonded over the sensor, which blocks exactly those wavelengths. An IR LED on an unmodified Sense gives you a black frame.

In the order I would try them:

  1. Accept no night capture (night_behaviour: 2). Most garden birds are diurnal; you lose very little and the whole problem goes away.
  2. Dim, warm, continuous white light (nightlight_mode: 2). Continuous beats a flash per burst — animals habituate to steady light and startle at sudden light — and auto-exposure is already settled when a bird arrives. Still disturbs wildlife.
  3. Remove the IR filter and use 850 nm. Best images, irreversible, and it wrecks daytime colour unless you fit a switchable filter.

The firmware supports all three; option 3 needs no code change.

Battery sensing

Off by default: the XIAO does not bring its battery rail out to a pin you can simply read, so this needs an external divider from BAT+ to PIN_BATTERY_ADC. The wiring is documented at the top of include/battery.h. Until it is wired, readings report valid: false — which the endpoint must render as "not measured", never as 0 V.

Once wired, set battery_divider_x100 from your measured resistor values (not their printed ones) and trim battery_offset_mv against a multimeter. Percentage comes from a piecewise curve per chemistry. For LiFePO4 be warned that the curve is nearly flat between 20 % and 90 % — the percentage there is close to meaningless, which is a property of the chemistry, not of the code.

This also arms SPEC C6's OTA battery gate. One deliberate choice worth knowing: with no sensing hardware the gate allows the flash rather than blocking it, on the grounds that refusing every OTA on a mains-powered device because an optional sensor is absent is worse than the risk it guards against.

Tuning the radar for birds

The LD2410 is designed to detect humans. A blue tit has a far smaller radar cross-section, and swaying branches and heavy rain both register. Expect to spend an evening on this. Everything below is a config push, not a reflash:

  • max_distance_cm — window it tightly to the feeder. The single most effective false-positive filter.
  • min_energy — raise until branches stop triggering, lower until birds start.
  • accept_stationary — a bird sitting on a perch is a stationary target. On for a feeder, off if you only care about arrivals.
  • radar_mode — 0 ignores the UART entirely and trusts the OUT pin. Useful to isolate whether a problem is the protocol decode or the sensor itself.

If it cannot be made to work, PIN_AUX_ADC is free for an AM312 and the trigger logic is one function (radarIsTrigger).

What is deliberately not here

  • Local SD buffering. Uploads that fail are lost rather than queued to the microSD. Worth adding if the WiFi link turns out to be marginal; the pins are free.
  • On-device frame differencing (SPEC Option C). The ring buffer makes this much easier to add later — you already have consecutive frames in PSRAM.
  • TLS. Deliberate, SPEC C2.

Open items in the code

  • ld2410.cpp frame offsets are from the datasheet, not verified.
  • Battery percentage curves are generic open-circuit approximations at room temperature. Good enough for a low banner and the OTA gate, not for a runtime estimate.
  • nightlight.cpp allocates an LEDC channel after the camera has taken channel 0 for XCLK. That should route around it, but it is untested.
  • Daily counters live in RTC memory and reset on power loss, by design. The endpoint's own count is authoritative.
  • radarSetGateSensitivity sends the command but only checks that something came back, not that the ACK matches.
  • PIN_STATUS_LED (GPIO21) has moved between XIAO board revisions — verify.
  • The LD2410's logic level on a 5 V supply is unverified on this hardware. Measure before connecting; see Wiring.