AOI Demo: 4-Station PCB Component Inspection
reCamera Pro is fully capable of real AOI inspection. To achieve good results, you need to fine-tune the detector on images of your own PCBs — or train a dedicated PCB model — and pair it with controlled lighting and fixtures. This demo deliberately ships an untuned general-purpose model, so what you see here demonstrates the out-of-the-box workflow, not the inspection accuracy the hardware can ultimately deliver.
This project is a demonstration of the end-to-end pipeline, not a strict, production-grade AOI (Automated Optical Inspection) method. Because the on-device detector is a general-purpose component model that has not been fine-tuned for these specific PCBs, you will sometimes see:
- Missing-part ("ghost") boxes that do not line up with the actual component positions;
- False detections — an intact board flagged FAIL, or a genuinely missing part overlooked.
Detection quality also depends on lighting, board placement and the golden template. A production AOI system would require a task-specific trained/tuned model, controlled illumination and fixtures, and validated decision rules. Please treat everything shown here as a feasibility demo only.
This project turns a reCamera Pro (RV1126B) into a desktop Automated Optical Inspection (AOI) station: a servo-driven 4-station turntable presents PCBs to the camera, an on-device 34-class component detector inspects each board with the NPU, and a rules engine flashes PASS (green) / FAIL (red) on a WS2812B LED ring. Beyond simple counting, the demo locates which components are missing on each board and can annotate them with red dashed "ghost boxes" on an optional MIPI display. Everything — camera app, RKNN model, MCU firmware, board scripts, wiring and BOM — is open source in the xr686/recamera-pro-aoi-demo repository.

Everything you need to replicate this project — camera app + RKNN model, XIAO firmware, board scripts (including the bilingual 中文/English servo calibration web UI), wiring diagrams and the full BOM — is open source at github.com/xr686/recamera-pro-aoi-demo.
Introduction
By following this tutorial you will build a fully self-contained inspection loop that runs entirely on the edge — no PC and no cloud are needed once the demo is deployed:
- Vision: a native reCamera Pro app (
aoi-pcb-detect) runs a YOLOv8n RKNN model (34 electronic-component classes, FP16) on the RV1126B NPU at ~4–5 fps, publishing per-frame detection boxes over a local WebSocket (ws://127.0.0.1:8124). - Motion + verdict: a Seeed XIAO ESP32-C5 (MicroPython) receives ASCII commands from the camera over UART, drives a DS3218 servo turntable between 4 PCB stations, and shows the inspection verdict on a WS2812B 16-LED ring.
- Missing-part detection: a "conductor" script on the camera samples the detection boxes, matches them against a golden template captured once from an intact reference PCB, and writes the missing-component list to
/userdata/aoi-missing.json. - Demo loop (per round, stations 1→4, M8b fast profile): rotate servo → brief 0.5 s pause → sample detection boxes for 5 s → template match (ROI filter + translation alignment + common-mode filtering) → write missing list → LED verdict (PASS solid green / FAIL red blink ×3 / no data amber) → hold 3.5 s → next station. ~10 s per station, ~44 s per full round — see Conductor and timing.
┌──────────────────────────────────────────────────────────────────┐
│ reCamera Pro (RV1126B) │
│ aoi-pcb-detect app ── RKNN NPU inference ──► det boxes WS :8124 │
│ ▲ │
│ aoi_conductor.py ── samples WS boxes, golden-template matching │
│ │ SERVO <angle> LED ALL 0 200 0 / red │
│ ▼ UART4 (/dev/ttyS4, 115200 8N1) │
│ aoi_cal_server.py ── web UI :8899 for servo calibration │
└────────┼─────────────────────────────────────────────────────────┘
▼ 3 wires (TX/RX/GND) via base board J7
┌─────────────────────────────┐
│ XIAO ESP32-C5 (main.py) │──PWM──► DS3218 servo ──► 4-slot turntable
│ fw v0.3-c5, MicroPython │──DIN──► WS2812B 16-LED ring (verdict)
└─────────────────────────────┘

The whole build takes about an afternoon: no soldering beyond Dupont wiring, and the camera side is a single one-click install script.
Hardware Preparation
The core of this project is one reCamera Pro (RV1126B) with its base board, plus a XIAO ESP32-C5 as the turntable controller:
| reCamera Pro | Seeed Studio XIAO ESP32-C5 |
|---|---|
![]() | ![]() |
With the parts in the BOM below assembled, the finished station looks like this: the reCamera Pro is mounted on a 2020 aluminum-extrusion frame looking straight down at the 4-slot servo turntable, while the XIAO ESP32-C5 and the WS2812B verdict ring sit at the base.

Bill of Materials (BOM)
📷 [Image 3] placeholder — Flat-lay photo of all BOM items on a desk: reCamera Pro + base board, XIAO ESP32-C5, DS3218 servo, WS2812B 16-LED ring, 5 V/4 A DC PSU + DC jack, 2020 aluminum extrusions (2×15 cm + 1×30 cm) + 9 cm handle, 1/4"-to-M5 adapter, MX1.25 cable, Dupont wires, 3D-printed 4-slot dial, 4 PCB samples. Each item labeled with a number matching the table.
| # | Item | Spec | Qty | Notes |
|---|---|---|---|---|
| 1 | reCamera Pro | RV1126B, reCamera OS | 1 | vision + app runtime |
| 2 | reCamera Pro base board | with J7 10-pin MX1.25 header | 1 | provides UART4 + power |
| 3 | Seeed XIAO ESP32-C5 | MicroPython-capable dev board | 1 | turntable controller |
| 4 | DS3218 digital servo | 20 kg·cm, 270° version, 50 Hz PWM | 1 | rotates the turntable disc |
| 5 | WS2812B LED ring | 16 pixels, 5 V | 1 | PASS/FAIL verdict indicator |
| 6 | Power supply | 5 V / 4 A DC adapter | 1 | servo + LED ring (not USB!) |
| 7 | MX1.25 cable | 10-pin or individual pigtails | 1 | J7 breakout |
| 8 | Dupont wires | F/M as needed | ~6 | XIAO ↔ J7 / servo / LED |
| 9 | Servo turntable disc (3D-printed) | Ø160 × 5 mm, PETG (PLA OK) | 1 | STL in the repo: hardware/servo_disc_160mm_DS3218_v4.stl — 0.2 mm layers, 3 walls, 100% infill, no supports; mounts on the DS3218 25T horn with 4× M3×5 screws |
| 10 | PCB test samples | boards with known component counts | 4 | 1 intact + 3 with parts removed |
| 11 | 2020 aluminum extrusion | 15 cm | 2 | frame uprights |
| 12 | 2020 aluminum extrusion | 30 cm | 1 | frame base beam |
| 13 | 2020 extrusion handle | 9 cm | 1 | carry handle |
| 14 | DC power jack | panel-mount, matches the PSU plug | 1 | 5 V input connector |
| 15 | 1/4"-20 to M5 screw adapter | camera thread adapter | 1 | camera mounting |
Software is pinned in the repository: MicroPython v1.29.0 for XIAO ESP32-C5 (bin included) and the components34.rknn model (bundled inside the camera-app tarball). Release checksums are published in the repository README — verify them after cloning if you want to be sure the bundle is intact.
How It Works
The system has three layers, each replaceable independently:
- Detection layer (camera app). The
aoi-pcb-detectapp captures frames, runs the RKNN model on the NPU and broadcasts every frame's detections as JSON messages onws://127.0.0.1:8124. Each message looks like{"type":"results","frame":{"width":1280,"height":720},"results":[{"cls_name":"ic","box":[x1,y1,x2,y2]}, ...]}with pixel coordinates. The app also writes per-frame counts to its log (/userdata/local/apps/aoi-pcb-detect/logs/app.log), which the conductor keeps as a count-only fallback. - Judgement layer (conductor).
aoi_conductor.pyon the board drives the whole loop: it sendsSERVO <angle>commands over UART4 to position each station, samples the WebSocket for a fixed window, normalizes boxes to 0–1 coordinates, filters out-of-ROI / oversized / edge-touching boxes, aligns the live detections to the golden template with a median translation offset (capped at 0.15), checks every template box for a live hit, subtracts common-mode "missing" boxes (weak components the detector cannot see even on the intact reference board), and writes the result atomically to/userdata/aoi-missing.json. - Motion + indication layer (XIAO firmware). The MicroPython firmware (
main.py, fw v0.3-c5) listens on UART (and USB serial) for a line-based ASCII protocol (SERVO,GOTO,LED,STATUS, …), generates 50 Hz PWM for the DS3218 servo and drives the WS2812B ring. It is stateless with respect to inspection — all judgement happens on the camera.
An optional fourth layer is the on-device MIPI display UI (aoi_display), which polls aoi-missing.json and draws red dashed ghost boxes at missing positions. It is a board-side customization and not part of the open-source bundle — see Optional: MIPI display.
Prerequisites
- A reCamera Pro with the base board, running reCamera OS, reachable over SSH from your PC (see Terminal, SSH and debug UART). You need the board's IP address and its root secret.
- A PC (Linux/macOS/Windows) with Python 3.8+,
pip, and SSH/SCP clients.install.pyadditionally needsparamiko; the XIAO flashing scripts needesptoolandmpremote(installed byprep.sh). - The parts listed in the BOM above, including a 5 V / 4 A power supply for the servo and LED ring.
- 4 PCB test samples: one intact reference board (station 1) and three boards with some components removed (stations 2–4). Identical layouts work best — the golden template is shared by all stations.
- A 3D-printed turntable disc that mounts on the DS3218 servo horn and holds each PCB flat under the lens — the final STL (v4, Ø160 × 5 mm) is in the repo under
hardware/(PETG preferred, 100% infill; fasten with M3×5 screws — M3×8 would hit the servo case).
Wiring
Only three signal wires run between the reCamera Pro and the XIAO (TX, RX, GND). The servo and LED ring are powered from the external 5 V supply, never from the XIAO or the camera.
reCamera Pro base board J7 (10-pin, MX1.25)

| Pin | Function | Note |
|---|---|---|
| 1–4 | CAN0_RXD / CAN0_TXD / CAN1_RXD / CAN1_TXD (M0) | not used in this demo |
| 5 | UART4_TX (GPIO5_A2) | board → XIAO (RX side) |
| 6 | UART4_RX (GPIO5_A3) | board ← XIAO (TX side) |
| 7–8 | 12–24 V power (12to24V_IO1 / IO2) | ⚠️ HIGH VOLTAGE — NEVER connect these to the XIAO |
| 9 | GND | common ground |
| 10 | DC_IN (board DC input rail, fused 1.5 A) | ⚠️ power rail — do not connect to the XIAO |
J7 pins 7 and 8 carry 12–24 V, and pin 10 is the board DC input rail (behind a 1.5 A fuse). Double-check the pinout before plugging anything in — connecting any of these to the XIAO will destroy it. The J7 header provides no 3.3 V/5 V power pin, so the XIAO must be powered separately over its USB-C port.
On the board side, UART4 appears as /dev/ttyS4 (115200 8N1, raw).
XIAO ESP32-C5 side

| XIAO pin | GPIO | Function | Connect to |
|---|---|---|---|
| D7 | GPIO12 | UART RX | J7 pin 5 (UART4_TX) |
| D6 | GPIO11 | UART TX | J7 pin 6 (UART4_RX) |
| D0 | GPIO1 | Servo PWM (50 Hz) | DS3218 signal (orange) |
| D1 | GPIO0 | WS2812 data in | LED ring DIN |
| 5V | — | servo + LED power | external 5 V 4 A supply (+) |
| GND | — | common ground | external supply (−) and J7 pin 9 |
The ESP32-C5 has no UART2 (unlike the classic ESP32). The firmware uses UART0/UART1 remapped to GPIO11 (TX) / GPIO12 (RX). Power the servo and LED ring from the external 5 V 4 A supply, not from the XIAO USB/3V3 rail — the servo stall current will brown out the MCU.
Connection summary

reCamera Pro J7 pin5 (UART4_TX) ──► XIAO D7 (GPIO12 RX)
reCamera Pro J7 pin6 (UART4_RX) ◄── XIAO D6 (GPIO11 TX)
reCamera Pro J7 pin9 (GND) ─── XIAO GND ─── PSU GND (three-way common ground)
XIAO 5V ─── PSU 5V (+)
DS3218: orange=D0(GPIO1), red=PSU 5V, brown=PSU GND
WS2812B ring: DIN=D1(GPIO0), VCC=PSU 5V, GND=PSU GND
Baud rate is 115200, 8N1, no flow control, line-based ASCII protocol. Wiring reference photos are in docs/wiring.md.
- J7 pins 7/8 (12–24 V) are not connected to anything on the XIAO side.
- PSU(−), XIAO GND and J7 pin 9 are all tied together — a missing common ground is the #1 cause of servo jitter (see Troubleshooting).
- The XIAO has its own USB-C power source; the servo and LED ring get 5 V from the PSU, not from the XIAO.
Flash the XIAO ESP32-C5 Firmware
The ESP32-C5 bootloader offset is 0x2000. Flashing the MicroPython bin at 0x0 or 0x1000 (the classic ESP32 offset) overwrites the boot/partition area and leaves the board unbootable-looking. The provided flash.sh already uses the correct offset — if you flash manually with esptool, double-check it.
From a PC, with the XIAO connected over USB-C:
git clone https://github.com/xr686/recamera-pro-aoi-demo.git
cd recamera-pro-aoi-demo/xiao-firmware
./prep.sh # once per host PC: installs esptool/mpremote/pyserial
PORT=/dev/ttyACM0 ./flash.sh # Linux; macOS: /dev/cu.usbmodem*, Windows: COMx
python3 verify.py # optional: full USB-serial command self-test

flash.sh does four things in order:
- Erases the flash (
esptool --chip esp32c5 erase_flash). - Writes MicroPython v1.29.0 from the bundled
SEEED_XIAO_ESP32C5-v1.29.0.binat offset0x2000with--flash_mode dio --flash_freq 80m --flash_size 8MB. - Uploads the firmware
main.py(fw v0.3-c5) to the MicroPython filesystem viampremote. - Resets the board so
main.pyruns immediately.
If the serial port is not found or not writable: on Linux add your user to the dialout group (sudo usermod -aG dialout $USER, then re-login). If the board is not detected at all, enter download mode: hold BOOT, tap RESET, release BOOT, then re-run flash.sh.
Power-on self-test: on every boot the firmware moves the servo to 90°, runs one rainbow pass over the LED ring, blanks the LEDs, then prints AOI-TEST-FW v0.3 XIAO-ESP32C5 READY (type HELP) — seeing the rainbow at power-up means servo + LEDs + firmware are all healthy.

If you prefer raw esptool commands, the exact invocation used by flash.sh is:
esptool --chip esp32c5 --port /dev/ttyACM0 --baud 460800 erase_flash
esptool --chip esp32c5 --port /dev/ttyACM0 --baud 460800 \
--before default_reset --after hard_reset \
write_flash -z --flash_mode dio --flash_freq 80m --flash_size 8MB \
0x2000 SEEED_XIAO_ESP32C5-v1.29.0.bin
mpremote connect /dev/ttyACM0 fs cp main.py :main.py
mpremote connect /dev/ttyACM0 reset
Keep the chip (esp32c5), the offset (0x2000) and the flash parameters exactly as shown — settings copied from classic-ESP32 or ESP32-S3 tutorials are the usual cause of a "dead" board after manual flashing.
Install the Camera App
The detection model and the app are shipped as a single bundle (camera-app/aoi-pcb-detect.tar.gz, 5.4 MB): app code, manifest, integrity lock files and the RKNN model (components34.rknn, YOLOv8n, 34 classes, FP16, target rv1126b). There is no separate model download or conversion step.
One-click install (recommended)
From a PC that can reach the board over SSH:
cd recamera-pro-aoi-demo/camera-app
pip install paramiko
export BOARD_PASS='<your board root secret>'
python3 install.py --host <BOARD_IP>
install.py does everything in one run:
- Signature bypass (dev only) — persists
APPMGR_REQUIRE_SIGNATURE=0in/etc/profile.d/RkEnv.shand restartsappmgrwith that env (the original file is backed up first). Skip with--no-fix-sigif your board already accepts unsigned bundles. - SFTP-uploads the bundle to
/userdata/appstage/. - Calls the local appMgr API:
upload→install→switch(activate). - Verifies for up to 150 s: the app is listed in
running_appsand producesframe#inference lines in/userdata/local/apps/aoi-pcb-detect/logs/app.log.

When it finishes you should see the live detection feed in the board's Web UI (App Center → AOI PCB Detect), with ~4–5 fps inference on 34 component classes.
📷 [Image 10] placeholder — Screenshot of the reCamera Pro Web UI App Center with the AOI PCB Detect app running: live video with colored detection boxes over PCB components and class labels, fps indicator visible.
Useful install.py options: --user (SSH user, default root), --tar (path to a different bundle), --no-fix-sig (skip the signature bypass), --timeout (SSH connect timeout). The secret is read only from the BOARD_PASS environment variable — it is never passed on the command line.
Manual install (alternative)
If you cannot run install.py (e.g. no Python on your PC), you can install the bundle through the board's Web UI:
- SSH into the board and apply the same developer signature bypass the installer uses: add
export APPMGR_REQUIRE_SIGNATURE=0to/etc/profile.d/RkEnv.sh(back the file up first), then restartappmgrso it picks up the env. - Copy
camera-app/aoi-pcb-detect.tar.gzto the board (e.g.scpto/userdata/appstage/). - In the board Web UI, open App Center, use the local upload/install flow to install the bundle, then activate (switch to) the app.
- Confirm it runs:
tail -f /userdata/local/apps/aoi-pcb-detect/logs/app.logshould showframe#inference lines.
APPMGR_REQUIRE_SIGNATURE=0 disables app-bundle signature verification so this unsigned demo bundle can be installed — use only on development/demo devices, never on a shipping product. To revert: remove the export APPMGR_REQUIRE_SIGNATURE=0 line from /etc/profile.d/RkEnv.sh (a .bak copy is made automatically by the installer) and reboot.
The bundle's model was converted from lukemitter7/Component-Detection v.5 with rknn-toolkit2 2.3.2 (target_platform="rv1126b", FP16, no quantization, mean 0 / std 255). To retrain or reconvert your own detector, see the model-conversion/ directory — it includes the export/convert scripts and a full conversion report. For the general conversion workflow, see Convert models with RKNN-Toolkit2.
Deploy the Board Scripts
The demo scripts live in board-scripts/. Three of them run on the reCamera Pro (reCamera OS, busybox userland); calibration.html runs on your PC and needs no installation:
| File | Install to | Purpose |
|---|---|---|
calibration.html | (none — open on your PC in Chrome/Edge) | zero-install servo calibration page: Web Serial over USB straight to the XIAO, no Python needed |
aoi_cal_server.py | /userdata/aoi_cal_server.py | servo calibration web UI on port 8899 (board-side UART alternative) |
aoi_conductor.py | /userdata/aoi_conductor.py | main demo loop (M8b): rotate → sample WS detections → golden-template match → missing-part list → LED verdict |
aoi_conductor_legacy.py | (reference only) | original count-based conductor (tails app.log, exact median-count rules), kept for reference/rollback |
S98aoi_autostart | /etc/init.d/S98aoi_autostart (chmod +x) | power-on autostart + UART/GPIO setup |
Install from a PC with SSH access:
cd recamera-pro-aoi-demo/board-scripts
scp aoi_cal_server.py aoi_conductor.py root@<BOARD_IP>:/userdata/
scp S98aoi_autostart root@<BOARD_IP>:/etc/init.d/
ssh root@<BOARD_IP> 'chmod +x /etc/init.d/S98aoi_autostart && /etc/init.d/S98aoi_autostart start'
The detection app itself is not started by these scripts — appmgr's boot_restore brings it up automatically at every boot (see Auto-start on boot).
Calibration
Step 1 — Calibrate the turntable angles
There are two ways to calibrate — pick whichever is more convenient:
Option A — zero-install HTML page (recommended). Download board-scripts/calibration.html from the demo repository and open it directly in desktop Chrome or Edge — no Python, no board deployment. Plug the XIAO ESP32-C5 into your computer with a USB cable, click 🔌 Connect XIAO (USB) and pick its serial port (115200 baud). The page uses the browser's Web Serial API to send the same commands the firmware already accepts on its USB console. Jog each station under the lens, record its angle, then click 💾 Export aoi-cal.json and copy the file to the camera board:
scp aoi-cal.json root@<BOARD_IP>:/userdata/aoi-cal.json
Web Serial requires desktop Chrome/Edge (Firefox, Safari and phone browsers are not supported). While calibrating over USB, stop the conductor first (touch /tmp/aoi_conductor.stop) so the board's UART link and your USB commands don't fight over the servo; restart it when you're done.
Option B — board-side web UI (:8899). Open http://<BOARD_IP>:8899/ in a browser on the same network — use this when you prefer to calibrate through the board's UART link with the XIAO staying wired to the base board. The calibration server forwards only whitelisted commands (STATUS, HELP, SERVO 0-180, GOTO 0-3) to the XIAO over /dev/ttyS4, and angles are persisted to /userdata/aoi-cal.json automatically.
Both pages are bilingual (English / 中文) — they default to English, and a language toggle in the page header switches to Chinese instantly (the choice is remembered in your browser).
📷 [Image 11] placeholder — Screenshot of the calibration page (calibration.html or :8899): servo jog slider with ±1°/±5° nudge buttons, the four station record buttons ("record current angle"), and the current angle readout.
- Jog the servo with the slider until station 1's PCB slot sits centered under the camera lens.
- Click record current angle for station 1.
- Repeat for stations 2, 3 and 4 — each PCB must arrive under the lens at the same orientation and position, because all four stations share one golden template.
- The angles end up in
/userdata/aoi-cal.json(exported + copied in Option A, persisted automatically in Option B):
{"slots": {"1": 45, "2": 90, "3": 135, "4": 180}}
Calibrated angles are real degrees (0–270); the conductor converts them to the firmware's 0–180 servo units before sending. If a board lands off-center, re-record that station — do not compensate in software, or the shared template will misalign.
Step 2 — Capture the golden template
The golden template /userdata/aoi-template.json is a list of component boxes sampled once from the intact reference PCB under the lens at station 1. Format (normalized 0–1 coordinates):
{"meta": {"station": 1, "note": "intact reference PCB"},
"single": [{"cls_name": "ic", "x1": 0.12, "y1": 0.08, "x2": 0.18, "y2": 0.14}]}
To capture it, position station 1 under the lens (via the calibration UI from Step 1), then collect the app's live WebSocket detections on the board. The app publishes {"type":"results","frame":{"width":W,"height":H},"results":[{"cls_name":...,"box":[x1,y1,x2,y2]},...]} messages on ws://127.0.0.1:8124; normalize each box by the frame size. A minimal capture script (run with the same Python environment the conductor uses, which has websockets installed):
import asyncio, json, websockets
async def main():
boxes = {}
async with websockets.connect("ws://127.0.0.1:8124",
close_timeout=0.5) as ws:
try:
for _ in range(60): # ~60 frames is plenty
j = json.loads(await asyncio.wait_for(ws.recv(), 5))
if j.get("type") != "results":
continue
fr = j.get("frame") or {}
fw, fh = fr.get("width", 1280), fr.get("height", 720)
for it in j.get("results") or []:
b = it.get("box")
if not b or len(b) < 4:
continue
key = (it.get("cls_name"), round(b[0]/fw, 3),
round(b[1]/fh, 3))
boxes[key] = {"cls_name": it["cls_name"],
"x1": b[0]/fw, "y1": b[1]/fh,
"x2": b[2]/fw, "y2": b[3]/fh}
finally:
ws.transport.abort() # kit WS server ignores close handshake
tpl = {"meta": {"station": 1}, "single": list(boxes.values())}
with open("/userdata/aoi-template.json", "w") as f:
json.dump(tpl, f)
print("template boxes:", len(tpl["single"]))
asyncio.run(main())

Deduplicate boxes across frames (the snippet keys on class + rounded top-left corner), and capture under the same lighting you will demo in — detection sensitivity drifts with ambient light, and weak components missed at capture time become common-mode "missing" boxes later.
To keep the illumination stable, this build adds a white fill light next to the lens. It floods the PCB with even, neutral light so that detection scores stay consistent between template capture and the live demo, regardless of the room lighting:

Step 3 — Set the inspection rules
/userdata/aoi-rules.json holds a one-sided count tolerance per component group:
{"single": {"ic": 26, "capacitor": 8}}
A live count below want − 1 fails; extra "junk" detections from the low threshold never fail an intact board. Without a template file, the conductor falls back to the legacy count-only judgement from app.log (per-station exact-match rules, as in aoi_conductor_legacy.py).
How the matching works (per station)
- ROI filter — drop live boxes outside the template-envelope ROI, oversized boxes (normalized area > 0.06) and boxes touching the frame edge (< 0.01 or > 0.99).
- Translation alignment — estimate a global offset from the median nearest-neighbour displacement between live and template boxes (capped at 0.15; falls back to zero offset with too few samples), then shift the template.
- Presence check — a template box is present if a live box of the same class group hits it (center distance ≤ 0.5 × template diagonal, or IoU > 0.2) in enough sampled frames.
- Common-mode filter — boxes already "missing" on the intact reference board (cached from station 1 in
/userdata/aoi-missing-st1.json) are subtracted from stations 2–4, so weak components the detector cannot see are not reported as removed parts. - Atomic write — the missing list is written to
/userdata/aoi-missing.jsonvia a temp file + rename, so a display UI polling the file never reads a half-written JSON.
Optional: MIPI Display (board-side UI)
The on-device MIPI display UI (aoi_display) used in the reference build is a board-side customization and is NOT part of the open-source bundle. You do not need it to replicate the demo — the LED ring verdicts and /userdata/aoi-missing.json are fully functional without any display. This section documents what it does and the public data interface, so you can build your own UI on top.
In the reference build, a small native UI renders on a 720×1280 MIPI DSI panel attached to the reCamera Pro:
- live camera video with detection boxes,
- red dashed ghost boxes drawn at the positions of missing components, plus a missing-parts list and a status bar (note: because the detector is a general-purpose, untuned model, ghost boxes may be offset from the real component positions — see the demo-scope warning at the top),
- verdict/state information per station.

The public data interface is the file the conductor writes after every station:
{"station": 4, "ts": 1764000000000, "verdict": "FAIL",
"missing": [{"cls_name": "ic", "x1": 0.31, "y1": 0.22, "x2": 0.36, "y2": 0.27}],
"counts": {"ic": 9, "capacitor": 16}}
station— 1–4, the station just judged;ts— epoch milliseconds.verdict—PASS/FAIL/NODATAas decided by the conductor.missing— normalized (0–1) boxes of components present in the golden template but not found live; coordinates are already translation-aligned, so a UI can draw them directly over the video frame.counts— median live group counts for the station.
Any UI (LVGL, a native DRM/KMS app, or even a web page served from the board) can poll this file — it is replaced atomically, so a plain read loop is safe. In the reference build the display is started at boot by an S99aoi_display init script (after S98aoi_autostart), and its launcher verifies the PID's /proc/<pid>/cmdline before trusting a pidfile — see the pid-reuse Q&A below for why that matters on busybox systems.
Conductor and Timing (M8b)
Run the loop
With the app installed, scripts deployed, turntable calibrated and template/rules set, start the loop (/etc/init.d/S98aoi_autostart start or simply reboot) and watch the LED ring:
- Solid green — PASS.
- Red blink ×3 — FAIL.
- Amber — the detection app is not producing data (check the app log).
The conductor log (/userdata/aoi-conductor.log) shows each round: servo moves, sampled frames, alignment offsets, missing counts and verdicts. Stop gracefully with touch /tmp/aoi_conductor.stop. For a manual single-station judge while the loop is paused:
python3 /userdata/aoi_conductor.py --once <1|2|3|4> [--rotate]
--once does not touch the stop flag and does not start the loop; without --rotate it judges whatever station is currently under the camera.
In the shipped demo configuration the LED verdicts are scripted for exhibition: station 1 carries the intact reference PCB (always PASS) and stations 2–4 carry boards with components removed (always FAIL). This is hardwired by two flags near the top of aoi_conductor.py:
ST1_FORCE_PASS = True # station 1 verdict hardwired PASS
ST234_FORCE_FAIL = True # stations 2/3/4 hardwired FAIL
The missing-component annotations are always computed live from template matching, regardless of these flags — the raw matching result is still logged. To let the matching engine decide the verdicts (real inspection mode), set both flags to False in /userdata/aoi_conductor.py and restart the conductor (/etc/init.d/S98aoi_autostart restart). In real mode the verdict follows the template match and the one-sided count rules, so expect FAILs on the intact board too if lighting degrades detection sensitivity (see the trade-off note below).
Detection cadence and performance
The M8b fast profile is a pure parameter change — the matching/judgement code is byte-identical to the original 30 s-window version:
| Metric | Original profile | M8b fast profile |
|---|---|---|
| Per station | ~72–75 s | ~10 s (measured 9.4–10.9 s) |
| Full round (4 stations) | ~295 s | ~44 s (6.7× faster) |
| Sampling window | 30 s | 5 s (~25 frames at ~4–5 fps) |
| Servo settle wait | 3.5 s | 0.5 s (no full settle) |
| Parameter | Original | M8b | Note |
|---|---|---|---|
SAMPLE_S | 30.0 | 5.0 | one retry window if frames < MIN_FRAMES |
MIN_FRAMES | 5 | 3 | |
SETTLE_S | 3.5 | 0.5 | turntable may still be moving |
HOLD_S | 6.0 | 3.5 | blink 1.05 s + hold 3.5 s ≤ 5 s |
| Red blink on/off | 0.4 / 0.3 s | 0.2 / 0.15 s | ×3 |
| Main-loop sleep | 1.0 s | 0.3 s |
All parameters live at the top of board-scripts/aoi_conductor.py — edit, re-scp, restart.
The short window plus sampling before the turntable fully settles makes the missing-component count fluctuate between rounds (e.g. 13–15 / 18–21 / 21–26 on stations 2/3/4 in the reference setup). The scripted demo verdicts are unaffected; the ghost-box annotation remains the core deliverable. If you need stable counts, raise SAMPLE_S and SETTLE_S back toward the original values.
The WebSocket close-handshake fix (essential)
The kit's WS server does not answer the RFC 6455 close handshake, so a graceful websockets close blocks for its full 30 s timeout — a "5 s" window actually takes ~35 s. The shipped conductor connects with close_timeout=0.5 and calls ws.transport.abort() right after sampling (a non-graceful disconnect; the server treats it as a normal drop, verified over many reconnects). If you modify the sampling code, keep both parts of this fix, or the per-station time silently regresses by 30 s. The template-capture snippet above includes the same fix.
Auto-start on Boot
S98aoi_autostart (installed in /etc/init.d/, runs via busybox init after S94appmgr) does, in order:
- Exports GPIO201 (external LED) high.
- Sets
/dev/ttyS4to 115200 raw (stty). - Starts
aoi_cal_server.py(:8899) if not already running. - Starts
aoi_conductor.pyif not already running (boot log:/userdata/aoi-conductor-boot.log).
"Already running" is checked by scanning /proc/*/cmdline — busybox pgrep is unreliable on reCamera OS, and plain pidfile liveness (kill -0) is not enough either, because PIDs get reused after reboot (see Q&A). Manage it with:
/etc/init.d/S98aoi_autostart start|stop|restart
# logs: /userdata/aoi-autostart.log, /userdata/aoi_cal_server.log, /userdata/aoi-conductor-boot.log
The detection app itself is auto-restored by appmgr's boot_restore at every boot — no extra wiring needed. If you run the optional MIPI display, give it its own S99aoi_display init script (later start order than S98) with cmdline-verified pidfile handling.
Verify the Demo
Work through this checklist after deployment; each step isolates one layer of the system.
- XIAO self-test: power-cycle the XIAO → servo to 90° + one rainbow pass +
AOI-TEST-FW v0.3 … READYbanner on USB serial. - Board serial node: on the reCamera Pro,
ls /dev/ttyS4andstty -F /dev/ttyS4 115200 raw. - UART ping:
echo STATUS > /dev/ttyS4and capture the reply (busybox has notimeout; usecat /dev/ttyS4 > /tmp/uart.log &in the background) — expectOK angle=… leds=… uart=1 fw=v0.3-c5. - Visible feedback: send
LED ALL 255 0 0(red ring) andGOTO 2(servo to 120°) — if the hardware reacts, the board→XIAO direction is good. - App inference:
tail /userdata/local/apps/aoi-pcb-detect/logs/app.logshowsframe#lines; the Web UI live feed draws boxes at ~4–5 fps. - Full loop: start the conductor and watch a complete round: 4 stations, ~10 s each, ~44 s total, verdicts green (station 1) / red-blink ×3 (stations 2–4) with the shipped demo flags.

- Missing list: after a round,
cat /userdata/aoi-missing.jsonshows the latest station's verdict and missing boxes; the conductor log shows servo moves, sampled frame counts (~25 per 5 s window), alignment offsets and per-station timings.

XIAO command protocol reference (115200 8N1, one command per line)
| Command | Action | Reply |
|---|---|---|
HELP | list commands | usage string |
STATUS | report state | OK angle=<n> leds=<n> uart=<0|1> fw=v0.3-c5 |
SERVO <0-180> | move servo to angle | OK SERVO <angle> |
GOTO <0-3> | move to station (0=0°, 1=60°, 2=120°, 3=180°) | OK GOTO <i> angle=<n> |
SWEEP | sweep demo 0→60→120→180→90 | OK SWEEP done angle=<n> |
LED <idx|ALL> <r> <g> <b> | set LED color (0-255) | OK LED ... |
RAINBOW [cycles] | rainbow demo | OK RAINBOW |
OFF | all LEDs off | OK OFF |
LEDCOUNT <n> | change LED count (default 16) | OK LEDCOUNT <n> |
The same protocol is accepted on both the XIAO USB serial console and the UART link to the reCamera Pro.
Troubleshooting
| Symptom | Cause / Fix |
|---|---|
| Servo jitters or hunts left-right | Missing common ground. The servo PSU, XIAO and reCamera Pro must share GND (three-way: PSU(−) ↔ XIAO GND ↔ J7 pin 9). Fix the ground before touching firmware. |
| Board TX counts increase but RX stays 0 | The XIAO is most likely not powered — J7 has no 3.3 V/5 V pin, so signal wires cannot power it. Give the XIAO its own USB-C supply and press reset; you should see the boot banner on the board's serial capture. |
| XIAO not detected when flashing | Enter download mode: hold BOOT, tap RESET, release BOOT, re-run flash.sh. On Linux also check dialout group permissions. |
| XIAO dead after manual esptool flash | Wrong bootloader offset or flash parameters — ESP32-C5 requires 0x2000 with dio/80m/8MB, not the classic-ESP32/S3 recipe. Re-flash with the provided flash.sh. |
Commands typed to XIAO raise SyntaxError | You are typing into the MicroPython REPL (>>>) — main.py was interrupted. Press Ctrl-D to soft-reset, then send protocol commands. |
| LED ring lights only 12 of 16 pixels | Firmware led_count default mismatch — send LEDCOUNT 16 (already the default in v0.3-c5). |
| Amber ring (no data) | The detection app is not running or not logging. Check /userdata/local/apps/aoi-pcb-detect/logs/app.log and the app state in the Web UI. |
| Install fails at signature check | appmgr requires APPMGR_REQUIRE_SIGNATURE=0 for unsigned bundles; re-run install.py without --no-fix-sig, and note appmgr does not respawn automatically — the installer restarts it for you. |
| Counts fluctuate around the rule | The M8b conductor needs ≥3 frames per station; with the 5 s window some fluctuation is expected (see the trade-off note above). Improve lighting, keep the PCB flat in the slot, or raise SAMPLE_S/SETTLE_S. |
| Each station takes ~35 s despite a 5 s sampling window | The kit WS server does not answer the WebSocket close handshake — a graceful close blocks for the full 30 s timeout. Keep the conductor's close_timeout=0.5 + ws.transport.abort() after sampling. |
| Intact reference board reported as FAIL in real (unscripted) mode | Detection sensitivity drifts with ambient light — components visible at template-capture time may be invisible now (scores below threshold). Recapture the template under your demo lighting, or improve/normalize the lighting. |
| Autostart says "already running" but nothing happens after reboot | PID reuse trap: a stale pidfile's PID may be taken over by another process after reboot, so a plain kill -0 check passes falsely. Verify /proc/<pid>/cmdline actually contains your script name before trusting a pidfile; delete the stale pidfile and restart. |
| MIPI display stays black after reboot while everything else works | Same PID reuse trap on the display launcher: panel/backlight/DRM are fine but the UI process was never started because the stale pidfile "proved" it was running. Add cmdline verification to the launcher, clear the stale pidfile, and restart the UI service. |
Q&A
Q: The servo jitters or keeps hunting left-right. Is the firmware broken?
A: Almost never. This is a missing common ground symptom. The servo power supply, the XIAO and the reCamera Pro must share GND (PSU(−) ↔ XIAO GND ↔ J7 pin 9). Fix the wiring before touching any software.
Q: The board sends commands but the XIAO never replies (rx = 0). What first?
A: Check that the XIAO is powered. J7 provides no 3.3 V/5 V pin — signal wires cannot power the board. Give the XIAO its own USB-C supply, press reset, and look for the boot banner AOI-TEST-FW v0.3 … READY.
Q: I flashed the firmware manually with esptool and the XIAO looks dead. Did I brick it?
A: You probably flashed at the wrong offset or with wrong flash parameters. The ESP32-C5 bootloader offset is 0x2000 (not 0x0/0x1000 like classic ESP32), with --flash_mode dio --flash_freq 80m --flash_size 8MB — recipes copied from ESP32-S3 tutorials do not apply. Re-flash with the provided flash.sh, which uses the correct combination.
Q: The LED ring shows amber instead of PASS/FAIL.
A: Amber means the conductor got no detection data. Open the App Center in the board Web UI and confirm aoi-pcb-detect is running, then check /userdata/local/apps/aoi-pcb-detect/logs/app.log for frame# lines.
Q: The demo always PASSes station 1 and always FAILs stations 2–4, even when I put a good board in station 2. Is the matching broken?
A: No — that is the scripted exhibition mode: ST1_FORCE_PASS / ST234_FORCE_FAIL (near the top of aoi_conductor.py) hardwire the LED verdicts, while the missing-component annotations are always computed live. To run real template-based judgement, set both flags to False and restart the conductor. See Conductor and Timing.
Q: Can I use my own trained model instead of the bundled 34-class detector?
A: Yes. The model-conversion/ directory in the repository contains the export/convert scripts and a full report (rknn-toolkit2, target_platform="rv1126b", FP16). Retrain on your own dataset, convert, and repack the app bundle.
Q: Is it safe to leave APPMGR_REQUIRE_SIGNATURE=0 enabled?
A: No — it disables app signature verification and is intended for development/demo devices only. To revert, remove the export APPMGR_REQUIRE_SIGNATURE=0 line from /etc/profile.d/RkEnv.sh (a .bak backup is created automatically) and reboot.
Q: I shortened the sampling window, but every station still takes ~35 seconds. Why?
A: This is the WebSocket close-handshake trap. The kit's WS server does not answer the RFC 6455 close handshake, so a graceful websockets close waits for its full 30 s timeout — a "5 s" window actually takes ~35 s. The shipped conductor fixes this by connecting with close_timeout=0.5 and calling ws.transport.abort() right after sampling (a non-graceful disconnect; the server treats it as a normal drop, verified over many reconnects). If you modify the sampling code, keep both parts of this fix or the per-station time silently regresses by 30 s.
Q: The missing-component count changes between rounds. Is the detection broken?
A: Not necessarily. In the M8b fast profile the 5 s window starts before the turntable fully settles, so the translation estimate and the number of reported missing boxes fluctuate (e.g. 13–15 vs 18–21 across rounds). The demo verdicts are scripted and unaffected. For stable counts, increase SAMPLE_S and SETTLE_S; for the exhibition demo, the fluctuation is an accepted trade-off.
Q: In real (unscripted) mode my intact reference board is reported FAIL with a few "missing" components.
A: This is detection-sensitivity drift, not a template or threshold bug: under different ambient light the detector's scores on some weak components fall below the confidence threshold (they may drop out even at very low thresholds). The common-mode filter absorbs them for stations 2–4 once they are recorded on station 1. Practical fixes: normalize/improve the lighting, recapture the golden template under the same lighting you demo in, and keep the PCB flat and centered in its slot.
Q: The MIPI display (or another board-side service) stays black after reboot, but panel, backlight and DRM all test fine.
A: Classic PID-reuse trap on busybox systems: a launcher that only checks a pidfile with kill -0 can be fooled after reboot, because another process (in the reference case, the camera daemon) may inherit the stale PID — the launcher then believes the UI is "already running" and skips starting it. Fix: verify /proc/<pid>/cmdline actually contains the expected program name, delete the stale pidfile, and restart. Never let stop scripts kill by pidfile alone without that check — in the reference build that mistake once killed the wrong process and needed a full reboot to recover.
Still stuck? Export the logs and contact technical support
If the Q&A and Troubleshooting sections above do not solve your problem, collect the demo logs and send them to Seeed technical support — this is the fastest way to get help.
- From a PC that can reach the board over SSH, run (single copy-paste block):
ssh root@<BOARD_IP> '
mkdir -p /tmp/aoi-logs
cp /userdata/local/apps/aoi-pcb-detect/logs/app.log \
/userdata/aoi-conductor.log \
/userdata/aoi-conductor-boot.log \
/userdata/aoi_cal_server.log \
/userdata/aoi-autostart.log \
/userdata/aoi-cal.json /userdata/aoi-rules.json \
/userdata/aoi-template.json /userdata/aoi-missing.json \
/tmp/aoi-logs/ 2>/dev/null
dmesg > /tmp/aoi-logs/dmesg.log
cd /tmp && tar czf aoi-logs.tar.gz aoi-logs/'
scp root@<BOARD_IP>:/tmp/aoi-logs.tar.gz .
- Email the downloaded
aoi-logs.tar.gzto techsupport@seeed.io, together with:- a description of the problem (what you did, what happened, what you expected);
- your hardware list (reCamera Pro firmware version — shown on the Web UI System page — XIAO model, servo/LED ring type);
- the step in this tutorial where the problem occurs.
The archive contains the detection app log, conductor log, calibration server log, autostart log, kernel messages (dmesg) and your calibration/rules/template/missing-list JSON files — everything support needs to locate the issue.
Resources
- Full source, scripts and docs: github.com/xr686/recamera-pro-aoi-demo
- Wiring table & photos:
docs/wiring.md· BOM:docs/bom.md· Turntable disc STL + print notes:hardware/ - Board scripts guide:
board-scripts/README.md· Firmware guide:xiao-firmware/README.md - Related wiki pages: Send detection results over HTTP or UART · Upload and configure an RKNN model · Terminal, SSH and debug UART
- Model source: lukemitter7/Component-Detection v.5 · Pipeline inspiration: MukeshSankhla/Edge-Ai-Vision-Inspection
Tech Support & Product Discussion
Thank you for choosing our products! We are here to provide you with different support to ensure your experience with our products is as smooth as possible. We offer multiple communication channels to cater to different preferences and needs.

