---
name: embedded-firmware
description: Rules and workflows for AI coding agents working on embedded C firmware (microcontrollers, RTOS, drivers). Use for any change to firmware source, build files, hardware configuration, flashing, Git or documentation in an embedded project.
---

# Embedded firmware: rules for AI coding agents

One file for any coding agent. Save it as:

- `AGENTS.md` in the repository root (Codex, Cursor, GitHub Copilot and most other agents read it),
- `CLAUDE.md` in the repository root for Claude Code (or keep `AGENTS.md` and put the line `@AGENTS.md` in `CLAUDE.md`),
- or `.claude/skills/embedded-firmware/SKILL.md` to use it as a Claude skill (the header above is the skill's metadata).

Part 1 is filled in by the user. Parts 2 to 6 apply to every project. When Part 1 and the rules below disagree, Part 1 wins, except for the safety rules in 2.1, which only the user can lift, and only for a specific action.

---

## Part 1. Project preferences (the user decides)

`ASK` means not decided yet. Follow the workflow in Part 3 to fill this in. Never guess a value; never change one without the user saying so.

| Topic | Preference |
| --- | --- |
| Target MCU / board | ASK |
| Clock, power source and voltage | ASK |
| Toolchain and version (GCC Arm, Clang, IAR, Arm Compiler/Keil, ESP-IDF, ...) | ASK |
| Build system (Make, CMake, vendor IDE project, west, PlatformIO, ...) | ASK |
| C standard (C99, C11, C17) and compiler extensions allowed | ASK |
| RTOS (none / FreeRTOS / Zephyr / ThreadX / other) | ASK |
| Hardware access (vendor HAL, LL drivers, CMSIS registers, own drivers) | ASK |
| Generated code (CubeMX, Kconfig, devicetree, SDK config) and how to regenerate it | ASK |
| Dynamic memory after initialisation (forbidden / allowed / pool only) | ASK |
| Coding standard (MISRA C:2012/2023, CERT C, BARR-C, house style, none) | ASK |
| Formatter and its config (clang-format, ...) | ASK |
| Naming style (snake_case, module prefixes, ...) | ASK |
| Static analysis (cppcheck, clang-tidy, PC-lint, compiler warnings only) | ASK |
| Unit tests (Unity/Ceedling, CppUTest, GoogleTest on host, none) | ASK |
| Hardware-in-the-loop or on-target tests | ASK |
| Debug probe and flashing tool (ST-LINK, J-Link, CMSIS-DAP, esptool, ...) | ASK |
| May the agent build? flash? erase? run on hardware? | ASK |
| Logging (UART, RTT, ITM, none) and log levels in release builds | ASK |
| Safety or regulatory context (none, IEC 62304, IEC 61508, ISO 26262, ...) | ASK |
| Branch naming and default branch | ASK |
| Commit message convention (Conventional Commits, free text, ticket IDs) | ASK |
| Who commits, pushes and merges (agent with permission / user only) | ASK |
| Merge strategy (squash, merge commit, rebase) and required checks | ASK |
| Versioning and release tags (SemVer, date, build number) | ASK |
| Documentation format and location (README, docs/, Doxygen, wiki) | ASK |
| Language of comments and docs | ASK |

---

## Part 2. Rules for every embedded project

### 2.1 Safety: hardware and irreversible actions

Ask first, every time, even if a similar action was approved earlier:

- Flashing, erasing (mass or sector), writing option bytes, fuses, OTP, eFuses or readout protection, and changing debug-port or boot configuration. Some of these permanently brick or lock a chip.
- Anything that energises outputs: motors, heaters, relays, high-current loads, radio transmitters.
- Changing clock trees, voltage scaling, brown-out levels or power modes on a board that is connected.
- Running unfamiliar scripts or vendor tools against connected hardware.

When asking, say which device, which tool, what will change and whether it can be undone. After a hardware action, report exactly what happened.

### 2.2 Facts about the hardware

- Never invent a register address, bit position, reset value, timing figure, pin assignment or electrical limit. Take it from the datasheet, reference manual, errata sheet or vendor header. Name the document and section in a comment or in your answer.
- If the document is not available, say so and ask for it. Do not fill the gap from memory.
- Check the errata sheet for every peripheral you touch.
- Use the vendor's device headers (CMSIS or SDK) for register definitions instead of raw addresses.

### 2.3 C code

- Fixed-width types from `<stdint.h>` and `bool` from `<stdbool.h>`. Unsigned types for bit operations and register values (`1u << n`).
- `volatile` for memory-mapped registers and for data shared with an ISR or another core. `volatile` is not atomicity: protect multi-byte or read-modify-write access.
- `static` for every function and variable that does not need to be global; `const` wherever a value does not change; `extern` declarations only in headers.
- No magic numbers: named constants or enums, with units in the name (`TIMEOUT_MS`, `VREF_MV`).
- Every wait on hardware has a timeout. No unbounded loops except the main loop or a task's loop.
- No recursion. No variable-length arrays. No large buffers on the stack.
- Dynamic memory only as Part 1 allows. Never in an ISR.
- Check every return value and every error flag; never ignore a failed initialisation.
- Bounded string functions only: `snprintf`, not `sprintf`; no `gets`, `strcpy` or `strcat` into fixed buffers.
- Avoid undefined behaviour: signed overflow, shifts by the type width or more, unaligned or out-of-bounds access, uninitialised variables, strict-aliasing violations.
- Make layout explicit where it matters: endianness, padding and packing for anything sent over a wire or stored in flash.
- Prefer inline functions to function-like macros. Wrap macro arguments and bodies in parentheses.
- Keep code warning-free with at least `-Wall -Wextra` (or the toolchain's equivalent). Do not silence a warning without explaining why.

### 2.4 Interrupts, concurrency and RTOS

- ISRs are short: read the status, clear the flag, move data to a buffer, signal a task. No blocking calls, no `printf`, no allocation, no long loops.
- Use the RTOS's ISR-safe API (for example FreeRTOS `...FromISR` functions) inside interrupts.
- Keep critical sections as short as possible and never call blocking functions inside one.
- Use mutexes with priority inheritance for shared resources and semaphores or notifications for signalling.
- State interrupt priorities explicitly and check them against the RTOS's limits (for example `configMAX_SYSCALL_INTERRUPT_PRIORITY`).
- Give every task a measured stack size and enable stack overflow checking in debug builds.

### 2.5 Resources, timing and power

- Report the flash and RAM impact of a change (from the map file or size output) when it is more than trivial.
- Say how a change affects timing on the critical paths: ISR latency, control loops, communication deadlines.
- Do not leave peripherals, clocks or debug features enabled when they are not needed; say how a change affects sleep current.
- The watchdog stays enabled in release builds. Feed it only when the system has shown real progress.

### 2.6 Project hygiene

- Make the smallest change that solves the task. Do not reformat, rename or reorganise code you were not asked to touch.
- Do not edit vendor, SDK or generated files. Put code in the places meant for it (for example `USER CODE BEGIN` blocks), or change the generator's configuration and regenerate.
- No new libraries, packages or tools without asking. Pin exact versions.
- Never commit secrets, keys, certificates, production credentials, device serials or customer data. Signing keys never enter the repository.
- Keep build output (`build/`, `*.elf`, `*.bin`, `*.hex`, `*.map`) out of Git unless the user decides otherwise.

### 2.7 Honest reporting

- Say what you verified and how: compiled, analysed, unit-tested on the host, tested on hardware.
- Never say something works on hardware unless it ran on hardware. If you could not test, say so and give the steps to test it.
- If a test fails, show the output. Do not weaken or delete a test to make it pass.

---

## Part 3. Workflow: first session and preferences

1. Read this file, the README and the build files. Detect what you can (MCU from the device header or linker script, toolchain from the build files, RTOS from the sources) and show it to the user as a proposal, not as a decision.
2. Ask the user about every `ASK` row in Part 1 that matters for the current task, in one short grouped list. Offer the common choices and a recommended default for each; never pick silently.
3. Write the answers into Part 1 of this file and show the change. Only edit Part 1 with the user's agreement.
4. Later, when a task needs a preference that is still `ASK`, stop and ask before going on.
5. When the user states a new preference in a conversation, offer to record it in Part 1.

---

## Part 4. Workflow: a firmware task

1. **Understand.** Restate the task, the target and how success will be measured. Ask when the requirement, the hardware or the acceptance test is unclear.
2. **Read.** Read the relevant code, the datasheet and reference-manual sections, and the errata before writing code.
3. **Plan.** For anything beyond a small fix, list the files to change, the peripherals and resources used (pins, DMA channels, timers, interrupts and their priorities), the risks and how you will test. Wait for agreement when the plan touches hardware configuration or shared resources.
4. **Implement.** Small steps, following Part 2. Keep hardware access in drivers, logic in testable modules.
5. **Verify.** Build with warnings on, run the static analysis and the unit tests, check size and timing, and test on hardware only as Part 1 allows.
6. **Report.** What changed, why, what was verified, what was not, and anything the user must do (for example flash and measure).

---

## Part 5. Workflow: Git

Defaults until Part 1 says otherwise:

- Never commit or push directly to the default branch. One branch per task: `feat/...`, `fix/...`, `refactor/...`, `docs/...`, `chore/...`.
- Commit only when the user asks, or when Part 1 gives the agent permission. Each commit is one logical change that builds.
- Commit messages: a short imperative subject (about 72 characters), a blank line, then what changed and why. Mention the hardware it was tested on, or that it was not tested on hardware.
- Before every commit: format, build, static analysis and unit tests pass. Never skip hooks (`--no-verify`) or signing.
- Never commit build output, local IDE settings, secrets or large binaries (unless the project uses Git LFS for them).
- Push only when the user asks. Open a pull request with: summary, reason, files and peripherals affected, flash and RAM change, how it was tested, open questions.
- Merging is the user's decision. Use the merge strategy from Part 1, and only after the required checks pass.
- Never force-push a shared branch, rewrite published history, or delete branches or tags without the user's say.
- Releases: tag the merged commit with the version from Part 1, record the toolchain version, and keep the exact `.elf`/`.bin`/`.hex` and map file with the release (not in the source tree), so any field unit can be matched to its source.
- Keep the branch up to date with the default branch the way Part 1 says (rebase or merge); resolve conflicts in generated files by regenerating, not by hand.

---

## Part 6. Workflow: documentation

Documentation changes go in the same branch and pull request as the code they describe.

| When you change | Update |
| --- | --- |
| A public function or module interface | Its header comment (Doxygen style unless Part 1 says otherwise): purpose, parameters, return values, units, context (ISR-safe or not), blocking or not |
| Pins, peripherals, DMA channels, interrupts or priorities | The hardware resource table (for example `docs/hardware.md`): pin, function, peripheral, priority |
| Build steps, tools or versions | The README's build and flash instructions |
| Memory map, linker script or bootloader | The memory layout document |
| A design decision with trade-offs | A short decision record (`docs/decisions/NNNN-title.md`): context, options, decision, consequences |
| Behaviour a user or tester can see | The changelog, under an Unreleased heading |
| A known limitation or erratum workaround | A comment at the code and a line in the known-issues list |

Rules:

- Write for the next engineer: what it does, why it is done this way, and which document or datasheet section it relies on.
- Comments explain why; the code shows what. Delete comments that no longer match the code.
- Keep every number in the docs traceable to a measurement or a datasheet. Mark estimates as estimates.
- When the docs and the code disagree, say so to the user instead of guessing which one is right.
