Embedded Firmware
ASecurityThis skill should be used when the user writes, structures, builds, flashes, tests or debugs microcontroller firmware (ESP32, STM32, AVR / Arduino, RP2040, nRF52, CH32) with Arduino, PlatformIO, ESP-IDF, Zephyr, FreeRTOS, MicroPython or Rust, including bootloaders, settings storage, OTA, secure boot and CI tests. It carries production rules from a product in the field, and tools. Load it before writing or reviewing firmware, because its production rules and flashing steps are specific to each...
- 3 stars
- 0 votes
- 0 copies
- 0 views
- Added December 1, 2026
Works with
Security analysis
100/100Pro scans all 20 files and shows the line behind each finding
npx -y skills add gkochievi/boulder-hardware-skills --skill embedded-firmware --agent claude-codeAre you the author of Embedded Firmware?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/gkochievi-embedded-firmware)---
name: embedded-firmware
description: This skill should be used when the user writes, structures, builds, flashes, tests or debugs microcontroller firmware (ESP32, STM32, AVR / Arduino, RP2040, nRF52, CH32) with Arduino, PlatformIO, ESP-IDF, Zephyr, FreeRTOS, MicroPython or Rust, including bootloaders, settings storage, OTA, secure boot and CI tests. It carries production rules from a product in the field, and tools. Load it before writing or reviewing firmware, because its production rules and flashing steps are specific to each MCU.
user-invocable: false
---
# Embedded firmware
Write or review firmware for a custom board that has to run unattended. The rules come from a finished product that runs unattended in the field (a payment-operated controller on an ESP32-S3 with Arduino core 3.x, called the reference design in the reference files); they apply to any MCU. The user's project will usually be something else (a vending machine, an irrigation controller, a lamp, a sensor node). Take the patterns, not the domain.
## Choose the toolchain
Stay on the Arduino framework while it meets the requirements; move to the vendor SDK or Zephyr for a named reason (secure boot, flash encryption, low-power modes, DMA-heavy drivers, radio qualification, customer mandate). Pin every core, SDK and library version for anything that ships.
| Family | Default (Arduino) | Vendor SDK / RTOS when needed | Program / debug |
|---|---|---|---|
| ESP32 family | Espressif esp32 core 3.x (PlatformIO: pioarduino platform) | ESP-IDF (or Arduino as an IDF component) | esptool over USB / UART; built-in USB-JTAG on S3 / C3 / C6 |
| ESP8266 | esp8266 core (maintenance only) | ESP8266 RTOS SDK | esptool |
| STM32 | STM32duino | STM32CubeMX + HAL / LL (CMake), FreeRTOS via CMSIS-RTOS v2, Zephyr | ST-Link / CMSIS-DAP over SWD; ROM bootloader (UART, USB DFU) |
| ATmega Arduino boards | Arduino AVR Boards; MiniCore for bare chips | avr-gcc + avr-libc + avrdude | Optiboot over serial; ISP for fuses and bootloader |
| tinyAVR 0/1/2, AVR Dx / Ex | megaTinyCore, DxCore | avr-gcc | SerialUPDI |
| RP2040 / RP2350 | Arduino-Pico (earlephilhower) | Pico SDK, Zephyr | UF2 / picotool over USB; SWD (Debug Probe) |
| nRF52 / nRF53 / nRF54 | Adafruit nRF52 (nRF52840) | nRF Connect SDK (Zephyr) | SWD (J-Link, nRF DK debug-out); UF2 / serial DFU |
| SAMD21 / 51 | Arduino or Adafruit SAMD | Microchip / ASF, Zephyr | bossac with UF2 bootloader; SWD |
| CH32V / CH32X | openwch core | WCH SDK, ch32fun | WCH-LinkE (SWIO / SWD) |
| Teensy 4.x | Teensyduino | NXP MCUXpresso | Teensy Loader |
Python (MicroPython / CircuitPython) fits prototypes, fixtures and UI gadgets with RAM to spare; Rust (embassy, esp-hal, RTIC) fits long-lived products with complex state. Details and decision tables: `references/arduino-and-platformio.md`, `references/vendor-sdks.md`, `references/rtos-and-zephyr.md`, `references/micropython-circuitpython.md`, `references/rust-tinygo-and-others.md`.
Guard the board selection at compile time so a wrong target fails early:
```cpp
#if !CONFIG_IDF_TARGET_ESP32S3 // ESP32: CONFIG_IDF_TARGET_*; STM32: STM32F0xx etc.; AVR: __AVR_ATmega328P__
#error "Wrong board: select Tools > Board > esp32 > ESP32S3 Dev Module"
#endif
```
## Lay out the project
One module (`.h` + `.cpp`) per concern. The header is the module's API with a one-line comment per function; state lives in `static` variables inside the `.cpp`. Application logic stays in plain C/C++ without SDK calls, so it ports between frameworks and runs in host tests.
| File | Holds |
| --- | --- |
| `<Product>.ino` / `main.c` | Boot order, task or superloop setup, a bench status print |
| `config.h` | Every pin, bus address, threshold, timing constant, storage layout, `FW_VERSION` |
| `shared.h/.cpp` | Shared types, settings and counter records, defaults, sanitizing, locks, status snapshots |
| `storage.*` | Persistent records (A/B copies), event log |
| `expander.*` / `shiftio.*` | Output enable line, I/O expanders or shift registers, bus recovery |
| `power.*` | Supply watch, power-fail trip |
| `<domain>.*` | The state machine |
| `display.*`, `webui.*`, `buzzer.*`, `rtc_*.*` | One peripheral or service each |
| `tools/`, `tests/`, `README.md` | Generators and previews; host tests with mock headers; install, board settings, flashing, changelog |
Treat `config.h` as the single source of pin truth. Copy every pin from the schematic netlist with the net name and reference designator in the comment (`#define PIN_OUT_EN 3 // Q9 gate, R71 pull-up keeps outputs off at boot`). No pin number appears in any other file. When the board changes, change `config.h` first and record it in the README changelog in the same edit.
Give every piece of shared data exactly one writer. Other tasks or ISRs read a snapshot copied under a lock (or with interrupts disabled on 8-bit parts), or ask the owner through a request flag.
## Structure the timing
- **Superloop plus interrupts** when there is one timing domain and nothing blocks for more than a few milliseconds (AVR, CH32V003, small STM32): a fixed-period tick, non-blocking state machines, `millis()`-style timers, ISRs that only capture and flag.
- **RTOS tasks** when a slow job (network, display, flash erase) must not delay a fast one. ESP32 already runs FreeRTOS; STM32 uses FreeRTOS via CMSIS-RTOS v2 or Zephyr; nRF uses Zephyr.
The reference design's ESP32 task split:
| Task | Core / priority | Period | Job |
| --- | --- | --- | --- |
| power | 0 / 6 | 1 ms | Sample the supply, cut all outputs through one GPIO on a drop, wake the control task |
| control | 0 / 5 | 10 ms or notify | Inputs, pulses, state machine, outputs, saves, health checks, snapshot |
| display | 1 / 4 | 40 ms | Render the snapshot |
| web | 0 / 1 | 5 ms | WiFi, page, OTA, NTP |
Write the control logic as `void domainStep(uint32_t now)` with a thin task or loop wrapper, so host tests can call it with simulated time. Details: `references/architecture.md`, `references/rtos-and-zephyr.md`.
## Apply the production rules
Check each rule when writing or reviewing firmware, on any MCU.
1. **Outputs off before anything else.** A hardware pull resistor holds the master output enable off through reset, boot and flashing, on a pin the MCU's power-up glitches cannot turn on (`references/io-patterns.md`). Firmware writes the pin level before making it an output, writes an expander's output latch before its direction register, and turns the master enable on only after the output chip answered.
2. **Nothing switches on by itself.** After a reset, a power return, a fault recovery or a failed update, restore to a hold state that waits for a human action. Inputs already active at boot are not presses.
3. **Fail-safe polarity.** Choose signal polarity so a dead or resetting controller is the safe case (a coin inhibit line: optocoupler on = coins accepted, so no power = coins refused).
4. **Wrap-safe timing.** Unsigned arithmetic and `now - start >= duration`; never compare a timer against a stored deadline. Version 1.0 of the reference design kept relays off after 24.9 days: a comparison overflowed at 2^31 ms.
5. **Watchdog everywhere.** Hardware or task watchdog on every task or the superloop, fed only when the work really ran, and inside long handlers such as an OTA upload. Record the reset cause at boot.
6. **Bus recovery and fault state.** Clock a stuck I2C slave free at boot and before every retry. Count consecutive failed transfers; at the limit cut outputs through the GPIO enable, show "out of service", retry, and recover into the hold state.
7. **Brown-out detection and save.** Enable the chip's brown-out reset at a level inside the clock's voltage spec (AVR at 16 MHz: 4.3 V). Where state must survive a power cut, sample the input supply, trip on raw consecutive samples, cut outputs, then save the most valuable state first while a hold-up capacitor keeps the logic alive.
8. **Storage written twice with sequence numbers.** Every record carries magic, version, size, sequence and CRC. Write into the slot that does not hold the newest copy; load the newest valid copy; records grow only at the end; sanitize after every load. Respect the medium's endurance (internal flash and EEPROM wear; FRAM does not).
9. **Integer money and counters.** Integer minor units, carried remainders, a save on every payment event.
10. **Updates only in a safe state.** Refuse OTA or a bootloader jump unless the machine is idle; hold outputs off during it; use A/B slots with rollback where the platform has them (ESP-IDF, MCUboot, nRF DFU), and mark the image valid only after a self-test.
11. **Per-unit credentials.** Random hotspot and admin passwords per unit, shown on the device, changed before any other setting; nothing network-facing ships with a shared default password.
12. **Debounce every input** with N equal samples; time holds from press timestamps; ignore a key held since boot until it is released.
13. **Validate on the device.** Clamp every received value, terminate every string, copy UTF-8 without cutting a character, escape HTML.
14. **Lock production parts deliberately.** Read-out protection, secure boot, flash encryption and fuses are often one-way (STM32 RDP 2, ESP32 eFuses, AVR RSTDISBL / SPIEN fuses that need a high-voltage programmer to undo); write down what was set and keep a few unlocked boards.
15. **Version everything.** `FW_VERSION` in `config.h`, record versions separate from it, a dated README changelog, and a boot banner with the version and the status of each peripheral. Pin every dependency to an exact version and keep an SBOM per release (`scripts/fw_sbom.py`; the EU Cyber Resilience Act requires one for products placed on the EU market from 11 December 2027).
16. **Say what was tested.** State whether code passed host tests only, was built with the real toolchain, or ran on hardware.
Family notes: AVR has 2 KB SRAM on the 328P (use `F()`, `PROGMEM`, no `String` in loops, `volatile` and atomic copies for ISR data); never `while (!Serial);` on native-USB boards; on Cortex-M, an ISR that calls FreeRTOS needs a priority numerically at or above `configMAX_SYSCALL_INTERRUPT_PRIORITY`; ESP32-S2 / S3 / C3 / C6 need USB CDC On Boot set to where `Serial` should go.
## Workflow for a new board
1. **Collect inputs.** Schematic or netlist, BOM, exact MCU or module (flash, RAM, temperature grade), what each output drives, and the answer to "what must happen when power drops or the controller dies?" If the board came from `kicad-generator`, read the pin nets from its `netlist.py`.
2. **Write `config.h`.** Check strapping and boot pins, programming and debug pins, flash / PSRAM pins, ADC channels usable with the radio on, and the level each pin has during reset (`microcontrollers` skill, per family).
3. **Write a bring-up sketch** first: boot banner, bus scan, each output toggled with the field supply off and then on, each input printed, ADC readings in millivolts, a display test pattern.
4. **Write the state table and failure modes** (power loss, bus fault, reset mid-operation, update) and confirm them with the user before the state machine.
5. **Build module by module:** `config.h` and `shared` → storage → I/O → power → state machine → display → network and updates. Add host tests with each module.
6. **Run host tests** that simulate time, the timer wrap, every bus device, cut writes and power failures (`references/testing-and-release.md`); add `pio test` or CI where the project uses them.
7. **Flash and debug on hardware** with the probe and connector the board provides (`references/flashing-and-debugging.md`). Run the build → flash → monitor loop of `references/dev-loop.md`: never guess the baud rate, have the firmware print `[READY] <fw> <version>` after init and `[ERROR] <code> <text>` on failures, and wait for them with `scripts/serial_expect.py` instead of reading the log by eye. Decode any panic with `scripts/decode_backtrace.py`. Then run the hardware test plan (`references/testing-hil-ci.md` for HIL with pytest and CI) and the release checklist.
8. **Before locking parts** (secure boot, flash encryption, eFuses, RDP, AVR fuses), follow `references/esp-idf-production.md` or `references/mcuboot-and-secure-ota.md`, rehearse on virtual eFuses or a spare board, and tell the user what is irreversible. The plugin's safety hook asks the user before such commands run.
## Engineering plugin skills
If the Engineering plugin is installed, use it at these points:
- `/engineering:architecture` or `/engineering:system-design`: toolchain and RTOS choice, task split, storage medium, recorded as decisions.
- `/engineering:testing-strategy`: the host test list and the hardware test plan.
- `/engineering:code-review`: before every release, with the production rules above as the checklist.
- `/engineering:debug`: field faults (resets, lost settings, stuck outputs); start from the event log, reset cause and boot banner.
- `/engineering:deploy-checklist`: before shipping an update image or flashing a batch.
- `/engineering:documentation`: the README (install, board settings, first start, changelog).
## Reference files
| File | Use for |
|---|---|
| `references/architecture.md` | module and header pattern, `config.h`, shared state and locks, boot order, tasks versus loop, state machines, timing, error handling, versioning |
| `references/io-patterns.md` | glitch-free boot, pin traps, debouncing, pulse inputs, relay outputs, optocoupler polarity, I2C expanders with bus recovery, shift registers, ADC, buzzer, RTC with NTP |
| `references/persistence-and-power-fail.md` | NVS vs FRAM vs EEPROM, the A/B record with code, schema versioning, counters, wear, brown-out sampling, hold-up capacitor sizing, save order |
| `references/webui-and-ota.md` | AP and STA handling, hotspot timeout, passwords, embedded page, JSON endpoints, form validation, guarded OTA, security notes |
| `references/displays-and-fonts.md` | HUB75 panels, bitmap fonts for non-Latin scripts, UTF-8 layout, starting points for OLED, TFT and e-paper |
| `references/testing-and-release.md` | host tests with mock headers, what to simulate, hardware test plan, ESP32-S3 board settings, arduino-cli, release checklist |
| `references/arduino-and-platformio.md` | Arduino IDE / arduino-cli, cores and Boards Manager URLs per family, PlatformIO, `pio test`, CI, pitfalls |
| `references/vendor-sdks.md` | ESP-IDF, STM32Cube, AVR bare metal, Pico SDK, nRF Connect SDK, WCH, Microchip, others; moving an Arduino prototype to an SDK |
| `references/rtos-and-zephyr.md` | superloop vs RTOS, FreeRTOS on ESP32 and STM32, Zephyr, other RTOSes, concurrency bugs |
| `references/flashing-and-debugging.md` | debug connectors, probes, host tools, ROM bootloaders, production programming, fault handlers, per-family summary |
| `references/micropython-circuitpython.md` | choosing and flashing Python firmware, file transfer, performance, products and updates, testing |
| `references/rust-tinygo-and-others.md` | embedded Rust (embedded-hal, embassy, RTIC, esp-hal, probe-rs), TinyGo, other languages |
| `references/dev-loop.md` | build → flash → monitor → verify per toolchain, port detection by VID:PID, baud rules, serial markers `[READY]` / `[ERROR]` / `[PASS]` / `[FAIL]`, reset behaviour, what to do when flashing fails |
| `references/esp-idf-production.md` | ESP-IDF production setup: partition tables, sdkconfig per build, app rollback, anti-rollback, Secure Boot v2, flash encryption, NVS encryption, eFuse planning, core dumps, factory programming |
| `references/mcuboot-and-secure-ota.md` | secure OTA principles, MCUboot modes, imgtool and sysbuild signing, downgrade prevention, confirmation, MCUmgr, ESP-IDF / STM32 / RP2350 / nRF specifics |
| `references/testing-hil-ci.md` | test pyramid, host unit tests (Unity, GoogleTest, `pio test`, ztest / Twister), fuzzing, hardware-in-the-loop with pytest, fixtures, GitHub Actions CI, self-hosted runner security |
| `references/bus-tools.md` | logic analysers, I2C, SPI, UART, CAN / CAN FD with SocketCAN, RS-485 / Modbus, 1-Wire, USB debugging, scope triggers, with formulas |
| `references/edge-ai.md` | TinyML: whether a model is worth it, data and features, int8 quantization, LiteRT for Microcontrollers (TFLM) resolver and arena sizing, ESP-NN / CMSIS-NN, NPUs, latency and energy, model OTA |
| `references/motor-control-firmware.md` | PWM and dead time (STM32 timers, ESP32 MCPWM, RP2040), brushed DC, steppers and acceleration profiles, RC servo pulses, encoders and Hall inputs, protection, libraries and SDKs |
| `references/bldc-foc-and-control-loops.md` | BLDC six-step and sensorless commutation, field-oriented control (Clarke / Park, SVPWM, current sampling), discrete PID with anti-windup, cascaded loops, tuning procedure |
## Scripts and examples
Every script prints a readable report or, with `--json`, one result object (`status`, `action`, `summary`, `details`, `error`); exit 0 ok, 1 check failed, 2 usage or runtime error. Parameters that could mislead or damage (baud rate, CAN bitrate, chip) are never guessed; anything that transmits asks first unless `--yes`.
| File | Use for |
|---|---|
| `scripts/serial_scan.py` | list serial ports with VID:PID and the likely bridge / chip (CH340, CP210x, FTDI, ESP USB-Serial/JTAG, ST-Link, RP2040, nRF, ...) |
| `scripts/serial_expect.py` | open a port, optionally reset or send commands, wait for a marker (`[READY]`) or a failure (`[ERROR]`, panic, HardFault) with a timeout, save the log |
| `scripts/decode_backtrace.py` | ESP32 Xtensa / RISC-V panic logs and Cortex-M fault registers to function / file:line with the matching addr2line |
| `scripts/can_tool.py` | CAN monitor, send (asks first), replay and bus-load statistics with python-can; interface, channel and bitrate required |
| `scripts/fw_sbom.py` | CycloneDX 1.6 (and SPDX 2.3) SBOM of a release from dependencies.lock, west.yml, platformio.ini, sketch.yaml, Cargo.lock and submodules, merged with `esp-idf-sbom` / `west spdx` output and the board BOM, with the image hash and a gap report for the CRA |
| `scripts/tflite_to_c_array.py` | a `.tflite` model to an aligned `const` C array with length and checksums |
| `scripts/make_font.py` | a 1-bit bitmap font header from a TTF for the characters a product shows (Georgian, Cyrillic, Armenian, Greek, symbols), with a magnified preview and a report of characters the font lacks |
| `examples/partitions/` | ESP-IDF partition tables for 4 / 8 / 16 MB flash with OTA, checked with gen_esp32part.py |
| `examples/hil/` | pytest HIL fixtures and a smoke test using the serial markers, runnable against a fake device |
| `examples/ci/firmware.yml` | GitHub Actions workflow: host tests, PlatformIO, ESP-IDF, Zephyr, Arduino builds, HIL on a protected self-hosted runner, release |
## Related skills
- `microcontrollers`: pins, boot and programming per family; `microcontrollers/scripts/esp32_pincheck.py` for ESP32 pin maps.
- `iot-systems`: MQTT, BLE, LoRaWAN, cellular, Thread / Matter, provisioning, fleet OTA and the backend.
- `embedded-linux`: when the product runs Linux on an MPU (Yocto, Buildroot, device tree, RAUC / SWUpdate).
- `circuit-simulation`: check an analog front end or power stage in ngspice before writing its driver.
- `embedded-mentor`: teaching mode with exercises when the user is learning.
## Next step
When this is done, say what comes next: `firmware-build` for the path and the review (`firmware-build/scripts/fw_review.py`), then `bringup-and-test` on the real board.
Files in this skill
- SKILL.md
- examples/ci/firmware.yml
- examples/hil/README.md
- examples/hil/conftest.py
- examples/hil/fake_device.py
- examples/hil/test_smoke.py
- examples/partitions/partitions_16mb_ota_storage.csv
- examples/partitions/partitions_4mb_ota.csv
- examples/partitions/partitions_8mb_ota.csv
- references/architecture.md
- references/arduino-and-platformio.md
- references/bldc-foc-and-control-loops.md
- references/bus-tools.md
- references/dev-loop.md
- references/displays-and-fonts.md
- references/edge-ai.md
- references/esp-idf-production.md
- references/flashing-and-debugging.md
- references/io-patterns.md
- references/mcuboot-and-secure-ota.md
Attribution
Related skills
View all in ai-agents →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.