The Complete Guide to Embedded Rust on Microcontrollers
Learn embedded Rust from an empty directory to flashed, logged, interrupt-driven firmware on a Cortex-M board, with the toolchain, crates and mental model.

Embedded Rust is ordinary Rust compiled for a chip that has no operating system, and the whole difficulty of getting started is that everything an operating system normally does for you has to be named, found or written by someone. Where does the first instruction come from? Who sets up RAM? How does a program print when there is no terminal? How do you stop two parts of the program from fighting over one pin? This guide answers those questions in the order a beginner meets them, with a real board in mind: an STM32 NUCLEO-F411RE, a Cortex-M4F microcontroller with 512 KiB of flash and 128 KiB of RAM, and a debug probe built into the board's USB connector. Everything uses Rust 1.85, cortex-m 0.7, cortex-m-rt 0.7, embedded-hal 1.0 and stm32f4xx-hal 0.21, and each part is a step that builds on the one before it. By the end you will have flashed firmware, logged from it, handled an interrupt, read a sensor over I2C, and know where to go next for async, an RTOS, or a different chip.
If you only want the shortest path to a blinking LED, blink an LED on STM32 with Rust is the single-purpose version of what the first sections here explain in full.
What embedded Rust is, and what it is not
A microcontroller is a processor, some flash for code, some RAM, and a set of peripherals (pins, timers, serial ports, converters) wired to registers at fixed addresses. Embedded Rust means writing firmware for it in Rust, almost always with #![no_std], so the compiler produces a program that needs nothing but the chip. The language is the same: ownership, traits, generics, iterators, pattern matching. What changes is the environment.
Three things are different from desktop Rust, and the rest of this guide is mostly about them.
First, there is no standard library. The [core library](https://doc.rust-lang.org/core/) is available, and it contains most of what you use daily: Option, Result, slices, iterators, formatting traits, atomics. std (threads, files, println!, HashMap) is not, because those need an operating system. The beginner post what no_std means lists exactly what you lose.
Second, the program is not started by anyone. On reset the processor reads its stack pointer and its first instruction address from a table at the start of flash, then begins running. Something has to provide that table, set up RAM, and call your code. That something is a small runtime crate.
Third, the hardware is shared state, and the compiler has to be told who owns it. Memory-mapped registers are global by nature, and the main thing Rust adds to embedded programming is a way to turn that global state into values that can only be held once.
What embedded Rust is not: a different instruction set, a virtual machine or a garbage collector. The output is machine code like any other. It is also not tied to one vendor. The same language runs on STM32, nRF, RP2040, ESP32, SAMD, and several RISC-V families, with the same traits across them.
Who it suits
Rust suits firmware where a memory or concurrency bug is expensive: devices that are hard to update, safety-relevant products, anything with a network connection, and teams that spend more time debugging than writing. It suits people who like having the compiler check an invariant they would otherwise keep in their head. It suits less well a project that must use a vendor's C-only SDK for its radio stack, or a chip with no community support. Embedded Rust versus C for production firmware works through that decision in detail, and the boundary section at the end of this guide summarizes it.
What you need
Hardware
Any of these boards is a sound first target. The code in this guide is for the first.
| Board | Core | Why it is a good first board |
|---|---|---|
| NUCLEO-F411RE | Cortex-M4F, 100 MHz class | on-board ST-LINK debugger, user LED and button, wide HAL support |
| Raspberry Pi Pico | dual Cortex-M0+ | cheap, drag-and-drop UF2 loading, good Rust support |
| nRF52840 DK | Cortex-M4F | on-board J-Link, strong async story with Embassy |
| ESP32-C3 DevKit | RISC-V | Wi-Fi and Bluetooth, mainline Rust target |
The key requirement is a debug probe. An on-board one (ST-LINK on a Nucleo, J-Link on a DK) means a single USB cable does flashing, debugging and power. If your board has none, a CMSIS-DAP probe or a second Pico running the open-source debugprobe firmware does the same job.
Software
Install Rust with rustup, then add the compile target for your core:
rustup target add thumbv7em-none-eabihfThe target name encodes the core. thumbv7em is Thumb-2 with the DSP extensions (Cortex-M4 and M7), none means no operating system, eabi is the embedded ABI and hf means hardware floating point. A Cortex-M0 or M0+ is thumbv6m-none-eabi, a Cortex-M3 is thumbv7m-none-eabi, and an M4 or M7 without an FPU is thumbv7em-none-eabi. Using the wrong one is a common cause of programs that build and then fault immediately.
Install the flashing and debugging tool:
cargo install probe-rs-tools --lockedprobe-rs talks to the debug probe, erases and writes flash, resets the chip, and shows logs. It replaces the older OpenOCD plus GDB combination for most work. Check that it sees your board:
probe-rs listThe following debug probes were found:
[0]: STLink V2-1 -- 0483:374b:066DFF3833584B3043115433 (ST-LINK)The serial number is specific to your probe. If the list is empty, the cause is usually a cable that carries power only, or on Linux missing udev rules that let your user access the device.
The boot sequence, in order
Understanding what happens between power-on and main removes most of the mystery from embedded projects, and it explains each file you are about to create.
Reset. The core reads two 32-bit words from the start of flash: the initial stack pointer and the address of the reset handler. This table is the first part of the vector table.
The reset handler. Provided by
cortex-m-rt. It copies initial values of.datafrom flash into RAM, zeroes.bss, and (on cores with an FPU) enables it.Your entry point. The runtime then calls the function you mark with
#[entry]. It has the signaturefn() -> !, because there is nowhere to return to.Your code runs forever. If it returns or faults, the chip hangs or resets.
Two files configure this process for your chip. memory.x tells the linker where flash and RAM are. The linker script link.x, generated by cortex-m-rt, lays out the sections around those regions and puts the vector table first. Writing memory.x and custom linker sections goes deeper once you need more than the basics.
Your first project, from an empty directory
Create the project:
cargo new --bin hello-mcu
cd hello-mcu
mkdir .cargoCargo.toml
[package]
name = "hello-mcu"
version = "0.1.0"
edition = "2021"
[dependencies]
cortex-m = { version = "0.7", features = ["critical-section-single-core"] }
cortex-m-rt = "0.7"
defmt = "1.0"
defmt-rtt = "1.0"
panic-probe = { version = "1.0", features = ["print-defmt"] }
[dependencies.stm32f4xx-hal]
version = "0.21"
features = ["stm32f411"]
[profile.release]
opt-level = "s"
lto = "fat"
debug = 2Each dependency has a job. cortex-m gives access to the core's own peripherals (SysTick, NVIC) and assembly intrinsics. cortex-m-rt is the runtime. defmt and defmt-rtt are the logger, and panic-probe is a panic handler that reports through it. stm32f4xx-hal is the hardware abstraction layer, and its stm32f411 feature selects the exact chip, because the register layout differs between family members.
debug = 2 keeps full debug info in the ELF file. Debug info stays on your computer and is not flashed, so it does not use any of the chip's memory.
The memory map
MEMORY
{
FLASH : ORIGIN = 0x08000000, LENGTH = 512K
RAM : ORIGIN = 0x20000000, LENGTH = 128K
}These come from the chip's datasheet. Flash on STM32 parts starts at 0x08000000, and RAM at 0x20000000. The region names must be exactly FLASH and RAM, since link.x refers to them. For cortex-m-rt to find the file reliably, a build.rs copies it to the build directory:
use std::env;
use std::fs;
use std::path::PathBuf;
fn main() {
let out = PathBuf::from(env::var_os("OUT_DIR").unwrap());
fs::copy("memory.x", out.join("memory.x")).unwrap();
println!("cargo:rustc-link-search={}", out.display());
println!("cargo:rerun-if-changed=memory.x");
}The Cargo configuration
[build]
target = "thumbv7em-none-eabihf"
[target.thumbv7em-none-eabihf]
runner = "probe-rs run --chip STM32F411RETx"
rustflags = [
"-C", "link-arg=-Tlink.x",
"-C", "link-arg=-Tdefmt.x",
]
[env]
DEFMT_LOG = "info"Four settings in one file. target makes every cargo build cross-compile without a flag. runner makes cargo run flash the board and attach, which is the loop you will use all day. The two linker arguments pull in the runtime's layout script and the logger's. DEFMT_LOG sets how verbose the compiled-in logging is.
The first program
#![no_std]
#![no_main]
use cortex_m_rt::entry;
use defmt_rtt as _;
use panic_probe as _;
#[entry]
fn main() -> ! {
defmt::info!("hello from the microcontroller");
let mut counter: u32 = 0;
loop {
counter = counter.wrapping_add(1);
if counter % 1_000_000 == 0 {
defmt::info!("counter reached {}", counter);
}
}
}The two attributes at the top say the program does not link std and does not use the normal main. #[entry] marks the real entry point. The two use ... as _ lines link the logger and panic handler crates for their side effects, since nothing in your code calls them by name. Build and run:
cargo run --releaseINFO hello from the microcontroller
INFO counter reached 1000000
INFO counter reached 2000000Each log line takes a moment, and the gaps between them depend on the core clock, so the pace will vary. If your terminal shows nothing, check the two settings that silently disable logging: the -Tdefmt.x linker argument and DEFMT_LOG. Flashing with probe-rs and printing with defmt explains how RTT carries those messages over the debug connection with no serial port.
You now have a toolchain, a flash loop and a log. The rest is learning what to put in main.
Peripherals are values, and there is exactly one of each
On a desktop, opening a file twice is allowed. On a chip, two parts of a program configuring the same timer differently is a bug that shows up as a hang. Embedded Rust makes that mistake hard to write by turning each peripheral into a value that exists once.
The chip's peripheral access crate (PAC) defines a struct Peripherals with one field per peripheral: GPIOA, TIM2, I2C1, USART2, and so on. You get it with take():
#![no_std]
#![no_main]
use cortex_m_rt::entry;
use defmt_rtt as _;
use panic_probe as _;
use stm32f4xx_hal::pac;
#[entry]
fn main() -> ! {
let dp = pac::Peripherals::take().unwrap();
defmt::info!("took the peripherals once");
let second = pac::Peripherals::take();
defmt::info!("second take is none: {}", second.is_none());
let _gpioa = dp.GPIOA;
loop {}
}INFO took the peripherals once
INFO second take is none: trueThe first call returns Some, and every later call returns None. Whoever holds dp owns the chip. You then hand pieces of it out: dp.GPIOA goes to the code that needs port A, dp.I2C1 to the sensor driver. Because the struct fields are plain moves, the compiler tracks who has what. If you pass dp.I2C1 to one driver, you cannot also pass it to another; the second use is a "use of moved value" error. This is the same rule as ownership of a String, applied to a piece of silicon.
The core has its own peripherals (SysTick, NVIC, the debug unit), which cortex_m::Peripherals::take() provides as a separate singleton.
Layers of crates
You will see crate names that look similar and do different jobs. Here is the map, covered in depth in PACs vs HALs vs BSPs:
| Layer | Example | Does |
|---|---|---|
| core crate | cortex-m | CPU-level access, intrinsics |
| runtime | cortex-m-rt | boot, vector table, #[entry] |
| PAC | stm32f4 | every register, generated from an SVD file |
| HAL | stm32f4xx-hal | safe clocks, pins and buses on the PAC |
| BSP | rp-pico | board pin names on top of a HAL |
| traits | embedded-hal | the shared interface drivers depend on |
Use the highest layer available for your hardware, and drop down only when you must. The PAC alone makes you write register sequences by hand; the HAL does them in a safe order.
Clocks first, then everything else
A chip starts on a slow internal oscillator, and almost everything you build (delays, baud rates, I2C speed, timer periods) is a number derived from the clock tree. The HAL makes you commit to a configuration once and then proves it to the rest of the code.
#![no_std]
#![no_main]
use cortex_m_rt::entry;
use defmt_rtt as _;
use panic_probe as _;
use stm32f4xx_hal::{pac, prelude::*};
#[entry]
fn main() -> ! {
let dp = pac::Peripherals::take().unwrap();
let rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.sysclk(48.MHz()).freeze();
defmt::info!("sysclk = {} Hz", clocks.sysclk().to_Hz());
defmt::info!("pclk1 = {} Hz", clocks.pclk1().to_Hz());
loop {}
}INFO sysclk = 48000000 Hz
INFO pclk1 = 24000000 Hzconstrain() turns the raw reset and clock control registers into a builder. sysclk(48.MHz()) asks for a target, and freeze() computes dividers and PLL settings, writes them, and returns a Clocks value. On this chip the APB1 peripheral bus has a maximum frequency, so with no explicit request the HAL picks a divider that stays under it, which is why pclk1 came out at half the core clock. The values are determined by the HAL's choices and the chip's limits, so a different configuration prints different numbers.
The point of Clocks is that it is a witness. A function that needs a frequency, such as building a delay or a serial port, takes &clocks, so you cannot construct one before the clocks are final. The compiler rules out a whole class of "baud rate wrong because the clock changed afterwards" bugs.
Digital output and input
The first real peripheral is GPIO. On the Nucleo-F411RE the green user LED LD2 is on PA5 and the blue user button B1 is on PC13, which reads low when pressed, per the ST user manual for Nucleo-64 boards.
#![no_std]
#![no_main]
use cortex_m_rt::entry;
use defmt_rtt as _;
use panic_probe as _;
use stm32f4xx_hal::{pac, prelude::*};
#[entry]
fn main() -> ! {
let dp = pac::Peripherals::take().unwrap();
let cp = cortex_m::Peripherals::take().unwrap();
let rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.sysclk(48.MHz()).freeze();
let gpioa = dp.GPIOA.split();
let gpioc = dp.GPIOC.split();
let mut led = gpioa.pa5.into_push_pull_output();
let button = gpioc.pc13.into_pull_up_input();
let mut delay = cp.SYST.delay(&clocks);
defmt::info!("press the blue button");
loop {
if button.is_low() {
led.set_high();
} else {
led.set_low();
}
delay.delay_ms(10u32);
}
}The LED follows the button. Take the pieces one at a time. GPIOA.split() enables the port's clock and returns one field per pin. into_push_pull_output() takes the pin by value and returns a new type that has set_high, set_low and toggle, and no read method. into_pull_up_input() enables the internal pull-up resistor, so an unpressed button reads high through the resistor and a press connects the pin to ground. The 10 ms delay is not decoration: it keeps the loop from spinning at full speed and, crucially, it is a crude debounce.
Why the pin types matter
A pin's mode is part of its type, so led.is_low() is a compile error and so is button.set_high(). The compiler catches a mode mistake that in C shows up as a pin that does nothing. How type-state pins prevent misconfiguration builds the mechanism from scratch, and for this guide the practical lesson is that the error message names the mode you are in, which tells you which conversion to call.
Switch bounce
A mechanical button does not change cleanly. The contact bounces for a few milliseconds, so one press looks like several. Polling every 10 ms hides most bounce, and an interrupt handler would see every edge, which is why debouncing becomes a design topic as soon as you use interrupts or async waits. Debouncing buttons with Embassy shows the async approach.
Delays and time
The delay_ms call above is a blocking delay built on the SysTick timer, the 24-bit down counter that every Cortex-M core has. It is correct and simple, and it has one defect: the CPU does nothing else while it waits. For a blinking LED that is acceptable. For firmware that must also read a sensor and answer a serial port, you need another approach, and there are three, in increasing order of effort:
| Approach | Idea | Cost |
|---|---|---|
| polling a free-running timer | read a counter and compare to a deadline | you write the scheduler |
| interrupts | a timer interrupt sets a flag | shared state, careful ordering |
| async tasks (Embassy) | tasks sleep and an executor wakes them | a new programming model |
You will meet all three in this guide. For now, keep the blocking delay and remember that its precision is the timer's, not the program's.
Timing with a counter instead of a delay
The core's cycle counter gives you a free-running timestamp without any peripheral. The DWT unit on Cortex-M3 and above exposes it:
use cortex_m::peripheral::DWT;
fn init_cycle_counter(mut dcb: cortex_m::peripheral::DCB, mut dwt: DWT) {
dcb.enable_trace();
dwt.enable_cycle_counter();
}
fn elapsed_cycles(start: u32) -> u32 {
DWT::cycle_count().wrapping_sub(start)
}wrapping_sub is what makes it correct across overflow of the 32-bit counter: the difference of two readings is right as long as the interval is under one wrap. At 48 MHz the counter wraps in about 89 seconds, so this suits short intervals. Cortex-M0 and M0+ cores lack the DWT unit, so use a timer peripheral there.
Logging and the debugger
You have already used defmt. Four levels exist (error, warn, info, debug, trace), and a compile-time filter removes the ones you do not want:
defmt::error!("sensor timeout after {} ms", 500u32);
defmt::warn!("battery at {}%", 17u8);
defmt::info!("started");
defmt::debug!("raw adc = {=u16:#06x}", 0x0A3Fu16);
defmt::trace!("loop tick");ERROR sensor timeout after 500 ms
WARN battery at 17%
INFO started
DEBUG raw adc = 0x0a3fWith DEFMT_LOG = "debug" the trace! line compiles to nothing. The {=u16:#06x} hint says the argument is a u16 printed as zero-padded hex, which also makes the wire encoding two bytes instead of the generic one.
For the cases where a log line is not enough, probe-rs also supports a debug session. probe-rs gdb --chip STM32F411RETx starts a GDB server, and VS Code's probe-rs-debugger extension gives breakpoints, variable views and single stepping. Build with debug = 2 so the debugger knows your source lines. A breakpoint on the panic handler is the quickest way to find where a program died.
Errors and panics
Rust has two ways to fail, and firmware needs to choose between them deliberately.
A Result is a failure you expect and can handle: a sensor that does not answer, a buffer that is full, a checksum that does not match. Return it, and let the caller decide.
A panic is a broken assumption: an index that cannot be out of range is out of range. In firmware a panic does not unwind. It calls the panic handler, which is a function you chose by linking a crate. panic-probe prints the message through defmt and halts in a breakpoint, ideal on the bench. A device in the field wants a handler that records the reason and resets, as in writing a custom panic handler.
A short example of the two together:
#[derive(Debug, defmt::Format, PartialEq)]
pub enum FrameError {
TooShort,
BadChecksum { expected: u8, got: u8 },
}
/// Frame layout: [start 0xA5][len][payload...][checksum = xor of payload]
pub fn parse_frame(bytes: &[u8]) -> Result<&[u8], FrameError> {
if bytes.len() < 3 || bytes[0] != 0xA5 {
return Err(FrameError::TooShort);
}
let len = bytes[1] as usize;
if bytes.len() < 3 + len {
return Err(FrameError::TooShort);
}
let payload = &bytes[2..2 + len];
let expected = payload.iter().fold(0u8, |acc, b| acc ^ b);
let got = bytes[2 + len];
if expected != got {
return Err(FrameError::BadChecksum { expected, got });
}
Ok(payload)
}This function never panics on bad input: every length is checked before slicing, so a corrupted frame from the wire becomes an Err, which the caller logs and drops. Notice that it uses nothing from the hardware, so it runs unchanged under cargo test on your laptop, which is the cheapest place to find parsing bugs.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_a_good_frame() {
let frame = [0xA5, 0x02, 0x10, 0x20, 0x30];
assert_eq!(parse_frame(&frame), Ok(&[0x10u8, 0x20][..]));
}
#[test]
fn rejects_a_bad_checksum() {
let frame = [0xA5, 0x02, 0x10, 0x20, 0x31];
assert_eq!(
parse_frame(&frame),
Err(FrameError::BadChecksum { expected: 0x30, got: 0x31 })
);
}
}running 2 tests
test parse::tests::accepts_a_good_frame ... ok
test parse::tests::rejects_a_bad_checksum ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered outThe XOR of 0x10 and 0x20 is 0x30, so the first test passes, and the second shows the error carrying both values, which makes a log line useful. To run host tests in a firmware crate, keep logic in a library that is no_std only when the test cfg is off, or put it in a separate crate in a workspace.
Interrupts and shared state
Polling works until something has to happen while the CPU is busy. Interrupts invert the control: the hardware stops your code, runs a handler, and resumes. In Rust the handler is a function with an attribute, and the hard part is data shared between the handler and main.
use core::sync::atomic::{AtomicU32, Ordering};
use cortex_m_rt::exception;
static TICKS: AtomicU32 = AtomicU32::new(0);
#[exception]
fn SysTick() {
TICKS.fetch_add(1, Ordering::Relaxed);
}
fn ticks_now() -> u32 {
TICKS.load(Ordering::Relaxed)
}An atomic is the simplest safe way to share one word. A static mut would need unsafe at each access and would be unsound if both sides wrote to it. For anything bigger than a word, such as a pin, a buffer or a struct that must change together, the pattern is a critical_section::Mutex<RefCell<Option<T>>>, explained in sharing peripherals between interrupts. The mechanics of attaching a handler to a device interrupt, unmasking it in the NVIC and clearing its pending flag are in writing interrupt handlers with cortex-m-rt.
Two rules cover most interrupt bugs. Keep handlers short: they block every interrupt of equal or lower priority. And clear the interrupt's pending flag, or on level-triggered sources the handler runs again immediately and the program appears to hang.
Talking to hardware over a bus
Most useful devices are not pins but chips on a bus: a temperature sensor on I2C, a flash on SPI, a GPS on a UART. Embedded Rust handles all of them through one idea: the embedded-hal traits.
embedded-hal 1.0 defines traits such as I2c, SpiDevice, OutputPin and DelayNs. A HAL implements them for its peripherals, and a driver crate is written against them. A driver for a TMP102 temperature sensor therefore depends on embedded-hal, not on stm32f4xx-hal, and works on any chip with a compliant HAL. The complete driver and its host tests are in writing a portable sensor driver; here is the part you write on the chip.
#![no_std]
#![no_main]
use cortex_m_rt::entry;
use defmt_rtt as _;
use panic_probe as _;
use stm32f4xx_hal::{i2c::I2c, pac, prelude::*};
use tmp102_driver::Tmp102;
#[entry]
fn main() -> ! {
let dp = pac::Peripherals::take().unwrap();
let cp = cortex_m::Peripherals::take().unwrap();
let rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.sysclk(48.MHz()).freeze();
let gpiob = dp.GPIOB.split();
let i2c = I2c::new(dp.I2C1, (gpiob.pb8, gpiob.pb9), 100.kHz(), &clocks);
let mut sensor = Tmp102::new(i2c);
let mut delay = cp.SYST.delay(&clocks);
loop {
match sensor.read_millicelsius() {
Ok(mc) => defmt::info!("{} mC", mc),
Err(_) => defmt::error!("sensor did not answer"),
}
delay.delay_ms(1000u32);
}
}INFO 25125 mC
INFO 25125 mC
INFO 25188 mCThe readings change with the room. PB8 and PB9 are the I2C1 clock and data pins in alternate function 4 on this chip, and the HAL configures them as open-drain when you pass them to I2c::new. I2C needs pull-up resistors on both lines, and most breakout boards include them. If every read returns an error, check wiring and pull-ups first, the sensor address second (0x48 when ADD0 is grounded), and the pin pair third.
Serial output for tools that are not a debugger
RTT needs a probe. For a device in a test rig, a UART is the output that always works. The Nucleo wires USART2 on PA2 and PA3 to the ST-LINK's virtual COM port, so no extra hardware is needed.
use core::fmt::Write;
use stm32f4xx_hal::serial::Config;
let gpioa = dp.GPIOA.split();
let serial = dp
.USART2
.serial(
(gpioa.pa2, gpioa.pa3),
Config::default().baudrate(115_200.bps()),
&clocks,
)
.unwrap();
let (mut tx, _rx) = serial.split();
writeln!(tx, "temperature {} mC", 25125).unwrap();Open the board's serial port at 115200 baud in any terminal and the text arrives. Tx implements core::fmt::Write, so the whole formatting machinery works, at the flash cost of core::fmt that shrinking Rust firmware discusses.
Concurrency without an operating system
Real firmware does several things at once: read a sensor every second, answer a command on the serial port, blink a status LED, and sleep when idle. There are four common ways to structure that in Rust, and choosing one early saves a rewrite.
The super-loop
One loop that checks each job in turn, with interrupts setting flags. It is the oldest design, it works for small programs, and it gets tangled as the number of jobs and their timing constraints grow. Everything in this guide so far has used it.
Interrupt-driven with RTIC
RTIC (Real-Time Interrupt-driven Concurrency) is a framework where tasks are interrupt handlers, shared resources are declared, and the framework generates the locking with priority ceilings, so a higher-priority task is blocked only by the resources it actually uses. It has no runtime scheduler beyond the NVIC, which makes its overhead small and its timing analyzable. It suits hard-real-time systems on Cortex-M.
Async tasks with Embassy
Embassy is an async runtime for microcontrollers. A task is an async fn, .await is a point where the task yields, and an executor runs whichever task is ready. When no task is ready the executor puts the core to sleep with wfi, which gives low-power behavior without extra code. The code reads like blocking code, and the structure is that of cooperating tasks:
#![no_std]
#![no_main]
use defmt::info;
use embassy_executor::Spawner;
use embassy_stm32::gpio::{Level, Output, Speed};
use embassy_time::{Duration, Timer};
use {defmt_rtt as _, panic_probe as _};
#[embassy_executor::task]
async fn blink(mut led: Output<'static>) {
loop {
led.toggle();
Timer::after(Duration::from_millis(500)).await;
}
}
#[embassy_executor::main]
async fn main(spawner: Spawner) {
let p = embassy_stm32::init(Default::default());
info!("starting");
let led = Output::new(p.PA5, Level::Low, Speed::Low);
spawner.spawn(blink(led)).unwrap();
loop {
info!("main task alive");
Timer::after(Duration::from_secs(5)).await;
}
}INFO starting
INFO main task alive
INFO main task aliveTwo tasks share the core: one toggles the LED every 500 ms and the other logs every 5 seconds, and neither blocks the other because Timer::after(...).await hands control back to the executor. Creating an Embassy project for STM32 is the step-by-step version, and the guide to async embedded Rust with Embassy covers the rest.
Embassy's HAL crates are separate from the classic ones: embassy-stm32 replaces stm32f4xx-hal, with a different API where pins are runtime-configured and borrowed. Embassy HALs also still implement the embedded-hal traits, so your drivers keep working.
An RTOS
FreeRTOS, Zephyr and others are usable from Rust through bindings, and there are Rust-native kernels. You choose this when you need preemptive priority scheduling, a large existing RTOS ecosystem, or you port a C codebase. The cost is a foreign scheduler and a C build step.
| Style | Preemption | Best for | Costs |
|---|---|---|---|
| super-loop | none | small, single-purpose firmware | does not scale |
| RTIC | by interrupt priority | hard real time, analyzable timing | static design |
| Embassy | cooperative, plus interrupt-driven wakeups | connected, many-task, low power | async mental model |
| RTOS | preemptive threads | porting or mixed C systems | foreign runtime |
For a first project, the super-loop teaches the hardware, and Embassy is a good second step on a chip it supports.
Testing firmware
Hardware bugs need hardware, but most firmware bugs are logic bugs, and logic runs anywhere. A reliable layout puts three layers of tests in place.
Host unit tests. Put parsing, state machines, protocol codecs and conversions in code that does not touch registers, and test it with plain cargo test. The parse_frame example above is that: it depends on core only. A driver written against embedded-hal traits is tested with embedded-hal-mock, which fakes the bus.
On-target tests. defmt-test runs #[test] functions on the real chip and reports through RTT, with probe-rs as the runner. Use it for tests that need the actual peripheral, such as "the timer fires within the expected window". Run on-target Rust tests with defmt-test gives the setup.
Hardware in the loop. A rig with the board wired to known stimuli, run in continuous integration, is the final layer. It is expensive to build, so reserve it for behavior that nothing else can check.
A rule that keeps this manageable: the code that touches hardware should be thin, and the code that decides things should be pure functions and types you can test on your laptop.
Reading and writing registers directly
Sometimes the HAL does not cover a feature, and you reach down to the PAC. The accessors are generated from the chip's SVD file, and the shape is always the same:
use stm32f4xx_hal::pac;
fn enable_gpioa_clock(dp: &pac::Peripherals) {
dp.RCC.ahb1enr().modify(|_, w| w.gpioaen().set_bit());
}
fn read_idr(dp: &pac::Peripherals) -> u32 {
dp.GPIOA.idr().read().bits()
}modify reads the register, lets you change some fields, and writes it back, preserving the others. write starts from the register's reset value instead. read returns a snapshot with one method per field. Accessor style depends on the PAC version: older PACs expose registers as fields (dp.RCC.ahb1enr) and newer ones as methods (dp.RCC.ahb1enr()). Generating a PAC from an SVD file explains where those names come from and how to fix a wrong file.
When it goes wrong: a checklist by symptom
Most beginner failures are one of a few causes. Match the symptom, check the cause in order.
| Symptom | Likely cause | Check |
|---|---|---|
probe-rs finds no probe | cable, permissions | probe-rs list, a data cable, udev rules on Linux |
| flashes, then nothing runs | no vector table at flash start | cargo size -- -A: .vector_table at 0x8000000 |
| hard fault at start | wrong target or missing FPU enable | thumbv7em-none-eabihf for an M4F; check memory.x |
can't find crate for std | crate without #![no_std] | add the attribute, disable std features |
#[panic_handler] required | no panic crate linked | add panic-probe or panic-halt |
duplicate lang item panic_impl | two panic crates | remove one |
| no log output | -Tdefmt.x or DEFMT_LOG missing | see the config file above |
| peripheral does nothing | clock not enabled, wrong pin mode | use the HAL's split() and into_* conversions |
| interrupt never fires | NVIC line masked, flag not set | unmask, check the pending flag |
| interrupt fires forever | pending flag not cleared | clear it in the handler |
| garbage serial output | baud rate wrong for the clock | freeze clocks before building the serial port |
region FLASH overflowed | image too large | shrink the firmware |
When none of these fits, simplify: reduce the program to the smallest version that shows the problem, and use the debugger to find where it stops. A hard fault handler that prints the stacked registers (cortex-m-rt lets you define one with #[exception] unsafe fn HardFault(frame: &ExceptionFrame) -> !) tells you the address of the faulting instruction.
use cortex_m_rt::{exception, ExceptionFrame};
#[exception]
unsafe fn HardFault(frame: &ExceptionFrame) -> ! {
defmt::error!("hard fault at pc = {=u32:#010x}", frame.pc());
loop {
cortex_m::asm::bkpt();
}
}ERROR hard fault at pc = 0x08000a3eLook that address up with arm-none-eabi-addr2line -e target/thumbv7em-none-eabihf/release/hello-mcu 0x08000a3e to get the source line. The address in your run will differ.
Size, speed and power
You will meet three limits sooner or later: flash is full, the loop is too slow, or the battery drains. Each has a first move.
Flash full. Measure with cargo size --release. The usual first wins are opt-level = "s" or "z", lto = "fat", a minimal panic handler, and defmt instead of core::fmt. Shrinking Rust firmware goes through them and cargo bloat.
Too slow. Measure before optimizing: the DWT cycle counter above gives exact counts. Build in --release, since debug builds are slow enough to break timing. Then look for work done in a loop that could be done once, and for hardware that could do it instead, such as DMA moving a buffer so the CPU does not.
Power. The cheapest saving is not running: end every idle loop with cortex_m::asm::wfi(), so the core sleeps until the next interrupt. Embassy does this automatically when no task is ready. Deeper sleep modes are chip-specific and live in the HAL or PAC.
The ecosystem, at a glance
The pieces fit together in a small number of crates, and knowing their roles makes the crates.io search results readable.
| Need | Crate |
|---|---|
| runtime and core access | cortex-m, cortex-m-rt (RISC-V: riscv, riscv-rt) |
| chip registers | a PAC, such as stm32f4, rp2040-pac, nrf52840-pac |
| safe peripherals | a HAL, such as stm32f4xx-hal, rp2040-hal, nrf52840-hal |
| board pins | a BSP, such as rp-pico |
| portable traits | embedded-hal, embedded-hal-async, embedded-io |
| logging | defmt, defmt-rtt |
| flashing and debugging | probe-rs |
| fixed-capacity collections | heapless |
| concurrency primitives | critical-section, RTIC, Embassy |
Using heapless collections covers the allocation-free data structures, which you will reach for as soon as a buffer has to hold more than a few values.
A learning route
The order below follows the difficulty of the ideas, not the list of crates. Each step is a project you can finish in a sitting and then build on.
Blink and button. Toolchain, flash loop, ownership of pins. Done above.
Log and panic.
defmt,panic-probe, reading a hard fault.A timer and an interrupt. SysTick or a general-purpose timer, a handler, an atomic shared with
main.A bus device. I2C or SPI sensor through an
embedded-haldriver, then write your own small driver and test it on the host.A UART protocol. A framed command parser with checksums, tested on the host, driven by interrupts or DMA.
Structure. Move to Embassy or RTIC and rebuild the previous project as tasks.
Production concerns. A reset-on-panic handler, a watchdog, flash size, and a second board to prove the code is not accidentally tied to the first.
Spend the most time on step 4. Writing a driver against embedded-hal traits teaches ownership, generics and testing at once, and the result is a crate other people can use. Migrating a driver to embedded-hal 1.0 is worth reading before you publish one.
Other chips, same ideas
Everything above carries over, with different crate names.
| Chip family | Target | HAL | Notes |
|---|---|---|---|
| STM32F4 | thumbv7em-none-eabihf | stm32f4xx-hal | features select the part |
| RP2040 | thumbv6m-none-eabi | rp2040-hal | needs a second-stage bootloader block; PIO available |
| nRF52840 | thumbv7em-none-eabihf | nrf52840-hal | Embassy support is strong |
| ESP32-C3 | riscv32imc-unknown-none-elf | esp-hal | flashed with espflash, not probe-rs |
| ESP32 (Xtensa) | xtensa-esp32-none-elf | esp-hal | needs the esp toolchain from espup |
Running no_std Rust on ESP32-C3 and programming RP2040 PIO from Rust show what differs in practice: the boot path, the flashing tool, and chip-unique features.
When embedded Rust is not the right choice
Be honest about the cases where it costs more than it gives.
A vendor-only radio or security stack. If your Bluetooth or cellular stack ships as a C library with a fixed SDK and support contract, you will call it through FFI, and most of the Rust benefit stays outside the boundary. Use Rust for your application code and accept the C interface.
A chip with no community support. For a part with no PAC or HAL you must write one, starting with an SVD file and a few weeks of work. That is a project, not a detour, and it is reasonable only if the product justifies it.
A team with no Rust time. The learning curve around ownership, traits and lifetimes is real, and it lands during the project's most schedule-sensitive period if you start in the middle of one. Pilot on a side module first.
A certification path built on a qualified C toolchain. Qualified Rust toolchains exist, but your assessor must accept yours, and that conversation takes time. Embedded Rust versus C lays out the trade in a decision table.
Very small chips. An 8-bit AVR or a part with a few kilobytes of flash is better served by C or Arduino code, where toolchains are mature. Rust for AVR exists and is experimental.


