Skip to content

Embedded Applications

Embedded Rust firmware operates on resource-constrained microcontrollers without a host operating system. Select the hardware abstraction layer (HAL), concurrency model, memory safeguards, hardware security controls, and test strategy before you ship firmware to devices.

Hardware families and HAL selection

Target embedded-hal version 1.0 or later so sensor and bus drivers stay portable across microcontrollers.

Target family Primary HAL Toolchain notes Best fit
ESP32 (RISC-V and Xtensa) esp-hal (no_std) RISC-V uses standard rustup targets. Xtensa uses espup. Bare-metal firmware, low power, and Embassy async workloads
ESP32 (std on ESP-IDF) esp-idf-svc Builds on Espressif ESP-IDF and FreeRTOS Projects that need full ESP-IDF Wi-Fi, Bluetooth, or OTA stacks
Arduino and 8-bit AVR avr-hal (no_std) Requires avr-gcc and ravedude for flashing Legacy 8-bit boards such as Arduino Uno and Mega with small RAM
ARM Cortex-M (STM32, nRF, RP2040, RP2350) embassy-stm32, embassy-nrf, embassy-rp, or vendor HALs Standard thumbv6m / thumbv7em / thumbv8m targets via rustup Industrial controllers, wearables, and connected sensors

Concurrency and runtime selection

Select the concurrency model that matches your hardware limits and timing requirements.

  • Embassy: Use embassy-executor for async/await cooperative multitasking on 32-bit microcontrollers. It fits connected devices that manage networking, USB, timers, and sensors without a traditional RTOS.
  • RTIC: Use Real-Time Interrupt-driven Concurrency for hard real-time systems with strict deadlines. RTIC maps tasks directly to hardware interrupt priorities and checks resource locks at compile time.
  • Synchronous loops: On 8-bit AVR boards with a few kilobytes of RAM, use blocking embedded-hal traits and small interrupt handlers. Avoid async executors on 8-bit targets.

Decouple slow peripheral transfers (such as I2C or SPI display writes) from fast input polling. Use a one-frame mailbox or signal from embassy-sync so a slow bus transfer does not stall input sampling.

Toolchain, flashing, and diagnostics

Pin the compiler channel and cross-compilation targets in rust-toolchain.toml.

rust-toolchain.toml
[toolchain]
channel = "1.100.0"
components = ["rustfmt", "clippy"]
targets = ["thumbv7em-none-eabihf", "riscv32imc-unknown-none-elf"]

Configure the default target and flash runner in .cargo/config.toml.

.cargo/config.toml
[build]
target = "thumbv7em-none-eabihf"
[target.thumbv7em-none-eabihf]
runner = "probe-rs run --chip STM32F411RETx"

Use these standard diagnostic tools:

  • probe-rs: Flash firmware, stream logs, and debug over SWD or JTAG on ARM Cortex-M and RISC-V targets.
  • espflash: Flash and monitor ESP32 devices over serial or USB-JTAG.
  • defmt: Send compact binary log indices from the microcontroller and format strings on the host. This saves flash memory and CPU cycles compared to core::fmt.

Flash layouts and release profiles

  • Commit custom flash partition tables (for example, partitions.csv on ESP32) and pass --partition-table partitions.csv to espflash. Keep application data and hidden device settings in separate partitions.
  • Set opt-level = "s" or opt-level = "z" in [profile.release] to reduce flash usage. Override opt-level = 3 for timing-critical radio or cryptography crates that require high speed.
[profile.release]
opt-level = "s"
# Radio stacks can require -O2 or higher for real-time timing.
[profile.release.package.esp-radio]
opt-level = 3
  • Document pin assignments by module label, voltage levels (for example, 3.3 V or 5 V), pull resistors, I2C addresses, and minimum flash or PSRAM sizes in WIRING.md or README.md.

Memory safety and no_std controls

Bare-metal firmware has no virtual memory manager. Prevent memory exhaustion and silent corruption at compile time and link time.

  • Avoid dynamic allocation: Keep firmware in #![no_std] without alloc where possible. Use fixed-capacity collections from heapless so memory use stays bounded and predictable.
  • Detect stack overflows: On ARM Cortex-M targets, use flip-link as the linker wrapper. flip-link puts the stack at the start of RAM so a stack overflow triggers a hardware fault instead of silent corruption of static variables.
  • Select a production panic handler: Use panic-probe during development so probe-rs prints a backtrace. In production firmware, use a handler that records fault metadata and resets the device (or triggers a hardware watchdog) into a safe state.
  • Isolate unsafe register access: Prefer HAL drivers over direct peripheral access crate (PAC) calls. Keep unavoidable unsafe blocks in small reviewed modules with // SAFETY: comments. Refer to Restrict unsafe code.

Security and firmware updates

Connected microcontrollers are exposed to both network and physical attackers.

  • Enable hardware protections: Configure Secure Boot and Flash Encryption before manufacturing so devices reject unsigned firmware and protect stored keys.
  • Sign over-the-air (OTA) updates: Sign every firmware image with an offline key. Check the cryptographic signature on the device before activation, and keep an A/B partition scheme for automatic rollback if boot fails.
  • Disable debug ports in production: Lock JTAG and SWD read-out protection on production units so an attacker cannot dump firmware or credentials from flash memory.
  • Use hardware entropy: Seed cryptographic operations and TLS sessions from the microcontroller hardware random number generator (TRNG).

Refer to Secure development lifecycle for threat models and security controls.

Testing and simulation

Separate hardware-independent logic from board-specific initialization so most tests operate on standard CI runners. Refer to Testing strategy.

Host tests in an embedded workspace

When the root .cargo/config.toml sets an embedded build target, cargo test targets the microcontroller by default. Use these patterns to check no_std logic on the host:

  1. Put protocol parsers, state machines, and embedded-hal device drivers in separate workspace crates under crates/. Start host tests with an explicit host target and exclude the firmware package:
Terminal window
cargo nextest run --locked --workspace --exclude my-firmware --target x86_64-unknown-linux-gnu
  1. For host-only integration tests (such as filesystem or storage image tests), create a separate Cargo package with its own .cargo/config.toml that sets the host target. Because Cargo ignores a member package’s .cargo/config.toml when invoked from the workspace root, start those tests from that package’s directory (cargo nextest run --locked) or select the package explicitly with an explicit host target from the workspace root (cargo nextest run --locked -p <test-package> --target x86_64-unknown-linux-gnu).
  2. Use embedded-hal-mock to simulate I2C, SPI, and GPIO transactions without physical boards.

Hardware and desktop simulation

Combine firmware simulation with host desktop simulators to detect regressions before you flash hardware.

  • Wokwi CI simulation: Define the board circuit in diagram.json and wokwi.toml. Use wokwi-cli with YAML test scenarios (wait-serial and set-control) to automate smoke checks in CI. Use a Cargo feature flag (for example, --no-default-features --features sim) for peripherals that the simulator cannot emulate.
  • Desktop simulator: Compile the same no_std UI and application crates into a host desktop window (for example, with Tauri or eframe) that replaces only display, input, storage, and radio drivers. Optional localhost-only control endpoints let automated scripts or coding agents send inputs and capture screen frames.
  • Final hardware check: Simulators do not model real ADC noise, display electrical timing, or brownout behavior. Always check initialization, timing, and thresholds on physical hardware before a release.

Target builds and hardware-in-the-loop (HIL)

  • Add a CI job that compiles the firmware crate for every embedded target with cargo build --release --locked and tracks flash and RAM usage.
  • For hardware-in-the-loop (HIL) checks, use defmt-test with probe-rs to start unit tests directly on target silicon.

Release artifacts and compliance

  • Build firmware with --locked and record the exact compiler version, target triple, and linker script for each release.
  • Publish the .elf symbols (for internal crash analysis), flashable .bin or .hex images, SHA-256 checksums, and a software bill of materials (SBOM). Refer to Release automation.
  • For safety-critical industrial, automotive, or medical products (for example, IEC 61508 or ISO 26262), evaluate a qualified Rust compiler toolchain such as Ferrocene.

Further reading