Two interrupts and one UART. In C the build passes and your message sometimes arrives torn. In Rust the build refuses until you say who owns the port. Run both, then learn why.
Learn how Rust runs with no operating system, how it gives each peripheral one owner, and where the unsafe keyword really lives in a firmware project.
Pick a way to build, drag the slider to choose when the interrupt fires, and press Build and run. Watch what reaches the wire. Then we build, piece by piece, everything underneath: no_std, ownership of peripherals, register crates, typestate, embedded-hal, critical sections, RTIC and Embassy.
You need a little C (what a function, a pointer and an interrupt handler are) and the idea of a driver from From Register Map to Driver. We teach the Rust from zero.
Built from primary sources: the Embedded Rust Book, the micro:bit v2 Discovery Book, the RTIC and Embassy sites, and ST’s RM0383 reference manual. The full list is in the Field Guide. Every device here is a model that runs in your browser, not real silicon.
A toy model: the main loop sends the 5 bytes of HELLO, an interrupt wants to send the 2 bytes of ok. One byte on a 115,200 baud 8N1 line takes 10 bit times, which is 86.8 µs. The build messages are paraphrased from what a C compiler and rustc report for this shape of program; the E0133 code is real, the exact wording varies by version.
Chapter 0
See how one interrupt can undo one line of C, and why a language that checks sharing at build time changes the game
You are writing firmware for a small frequency counter. The main loop watches a pin. Each time the pin goes high, it adds one to a counter. Once a second, a timer fires, and its handler reports the count and resets it to zero.
The handler is an interrupt service routine (ISR). An interrupt is a signal from hardware that pauses your running code, runs the ISR, and then resumes the old code at the exact instruction it left. Think of a phone call that lands while you write a sentence. You finish the call, then carry on mid-word. The paused code never learns that anything happened.
Here is the C for the counter. It looks harmless.
cvolatile uint32_t counter = 0; void main_loop(void) { while (1) { if (pin_rose()) counter += 1; // main context } } void TIM2_IRQHandler(void) { // interrupt context, once a second report(counter); counter = 0; }
The line counter += 1 is not one step for the processor. A Cortex-M core cannot add to memory directly. It does a read-modify-write: load the value from memory into a register, add one in the register, store the register back to memory. That is three instructions. An interrupt can land between any two of them.
Take a count of 5 and let the timer fire after the load. The main code has already copied 5 into its register. The ISR then reports 5 and writes 0 to memory. Then main resumes, adds one to its stale 5, and stores 6. The reset is gone. The next second starts at 6, not at 0 or 1.
Drag the slider to move the interrupt between the three steps. Count how many placements give a wrong answer.
Each row is one step in the order it really runs. Purple rows belong to the interrupt, orange rows to the main code. The slider chooses how many main steps run before the interrupt lands.
Model of the Embedded Rust Book’s frequency-counter example: load, add, store, with the count at 5 and the ISR doing COUNTER = 0. The book states that the increment “is not guaranteed to be atomic”. The register and memory values are exact for this sequence.
Two of the four placements are fine. Reset first, then count: memory ends at 1. Count first, then reset: memory ends at 0. Both are valid orders of two events. The other two placements end at 6, and that matches neither order. A bug like this appears once in thousands of edges, so a bench test passes and the field unit drifts.
The symptom is a count that is sometimes a few too high right after a reset, with no pattern you can reproduce on demand. The measurement is a stress test: fire the interrupt at random points a million times and compare the result with the two legal answers. Any other value counts as a failure. A debugger will not help, because stopping the chip changes the timing.
The fix has three families. First, turn interrupts off around the increment, so nothing can land in the gap. Second, use one atomic instruction, which the hardware runs as a single indivisible step. Third, give the counter one owner, so only one piece of code ever touches it. C offers all three. C never requires any of them, and the compiler stays silent.
Rust is a language whose compiler checks sharing before your program exists. It rests on one idea. Every value has one owner. The owner may lend the value out by reference. You may lend it to many readers at once, or to one writer. You may never lend it to a reader and a writer together.
The Rust edition guide names this rule “mutability XOR aliasing”. It sounds abstract. Here it just says: two pieces of code may not hold the counter at the same time if one of them can change it. That is exactly the situation in our bug.
The compiler does not know what an interrupt is. The Embedded Rust Book solves this with one decision: it treats an interrupt handler as a separate thread of execution. Then the rules for threads apply to interrupts too. The check costs nothing at run time. It happens on your laptop, in the build.
That is the plan for this lesson. We will meet the pieces one by one: how Rust runs with no operating system, how it hands out hardware as owned values, how a driver is written once for every chip, and what you do when two interrupts really must share one UART. The device at the top of this page is that last question, played in full.
This lesson builds on From Register Map to Driver, where you met drivers, layers and state machines in C. Interrupt basics live in Interrupts, DMA and the 12 Cycles, and the survey lesson Embedded Systems gives the wider map.
Chapter 1
Learn which parts of Rust you keep when nothing sits under your program, and what runs before main
Picture the chip on a BBC micro:bit v2. It holds a Nordic nRF52833: a 64 MHz Arm Cortex-M4 core, 512 KB of flash and 128 KB of RAM (Nordic’s product page). There is no Linux here, no file system, no thread scheduler and no memory manager. Your program is the only thing that runs. If you copy a desktop Rust program onto it, the first line of use std:: fails.
The reason is that Rust’s big library, std, assumes an operating system (OS) sits underneath. The OS is the program that lends out files, threads, memory and a clock. std asks it for those things. With no OS, there is nobody to ask.
Rust splits its library in two. core is the part that needs nothing from the world: numbers, slices, strings, Option, Result, atomic operations. std is core plus everything that needs an OS. The Embedded Rust Book puts it plainly: core is “a platform-agnostic subset of std that makes no assumptions about the host system”.
One line at the top of your crate flips the switch: #![no_std]. It tells the compiler to link core and not std. The book’s feature table shows what you give up and what you keep. Pick a mode below and look at all seven rows.
Choose how the crate links. A green tick means the feature is there. A pink star means you must add something. A red cross means it is gone. Tap a row name for the reason.
The seven rows and their marks are the feature table from the Embedded Rust Book, page “A no_std Rust Environment”. The no_std + alloc column applies its two footnotes: heap and collections return once you give the program an allocator, such as the alloc-cortex-m crate the book names.
Read the no_std column. You keep two things for sure: core, and the right to write firmware. The heap and the collections (Vec, BTreeMap) come back only if you add the alloc crate and an allocator, a piece of code that hands out memory. HashMap and HashSet stay missing, because the book notes there is no secure random number generator to seed them.
Two lost rows deserve a second look. The first is stack overflow protection. On a desktop, the OS puts a guard page beside the stack. If the stack grows into it, the program stops with an error. On a bare chip the stack just grows into whatever memory sits next to it. The program does not stop. It corrupts data and goes on. The lesson Where Memory Goes shows how to measure stack depth.
The second is runs init code before main. The book’s table marks it as a loss for the standard runtime: std sets up the stack guard, reads the command line and starts the main thread. That does not mean nothing runs before main. A small crate called cortex-m-rt supplies the startup. Its docs say the Reset handler “initializes .bss and .data” and enables the floating-point unit when the chip has one. You met this path in Reset to main(). The Rust crate does the same job as the C startup file.
Here is the book’s minimal program. Every line has a job.
rust#![no_std] // link core, not std #![no_main] // there is no OS to call main(), so skip the usual entry use panic_halt as _; // say what a panic does: here, halt use cortex_m_rt::entry; // the attribute that marks the entry point #[entry] fn main() -> ! { // "!" means: never returns loop { // your code goes here } }
Three points matter. First, #![no_main] is there because, per the book, the normal main interface in a no_std program needs the nightly compiler. The #[entry] attribute marks your start instead. Second, a program that panics needs to know what to do. panic_halt answers: stop. Other crates log the message or reset the chip. Third, -> ! is a promise that main never ends. Nobody is there to receive a return value, and the compiler checks the promise.
Compare that with C. A C startup file also has a reset handler, a vector table and an infinite loop. The structure is the same. What changes is that Rust makes you say each choice in code, and it checks the promises.
On a desktop, a failed unwrap() prints a message and exits. On the micro:bit, step by step: the failed unwrap() calls the panic handler you linked. panic_halt spins in a loop. The chip now sits there, LEDs frozen, doing nothing. A watchdog (a timer that resets the chip if you forget to feed it) would reboot it. Whether that is good is a design choice, not a language fact.
#![no_std] to a firmware crate and write let mut v = Vec::new();. What happens, and what is the fix?Chapter 2
Treat a hardware block as a value you can hold, move and lend, and see how take() hands it out exactly once
In C, a peripheral is a number. On an STM32F411, the second serial port, USART2, sits at address 0x4000 4400 on the APB1 bus (ST’s reference manual RM0383). A header file turns that number into a pointer, and from then on any function in the program can write USART2->DR = 'x';. Nothing in the language says who may.
Now two files both set up USART2. One picks 9,600 baud. The other picks 115,200. Whichever runs last wins, and the other file’s code talks to a port that no longer matches. The bug is a conflict between two readers of the same header, and no tool sees it.
Rust answers with a rule you can state in one line: every value has exactly one owner. The owner is the variable that holds the value. When the owner goes out of scope, the value is dropped.
The owner can move the value to a new owner, the way you hand someone a key. After a move the old variable is dead. If you use it, the build stops with error E0382, “borrow of moved value”. The key is no longer in your pocket.
The owner can also borrow the value out: a shared borrow &T lets many readers look, and a mutable borrow &mut T lets exactly one writer change it. Two writers at once stop the build with E0499, “cannot borrow as mutable more than once at a time”. Both errors are checked at compile time and cost nothing at run time.
Embedded Rust applies this to hardware. A peripheral is not a bare address. It is a value, such as a struct named USART2, and holding that struct is the only way to touch the port. If you hold it, you may use it. If a driver holds it, you may not.
One problem is left. Who creates the value? If any code could write Usart2 {} twice, the rule would mean nothing. The answer is the singleton pattern: a value that can be created once. The Embedded Rust Book builds it by hand with an Option.
ruststruct Peripherals { serial: Option<SerialPort>, } impl Peripherals { fn take_serial(&mut self) -> SerialPort { let p = replace(&mut self.serial, None); p.unwrap() } } static mut PERIPHERALS: Peripherals = Peripherals { serial: Some(SerialPort), };
Read it step by step. The static holds Some(SerialPort). The function take_serial uses replace to swap the stored value for None and return what was there. The first call gets the port. A second call finds None, and unwrap() panics. The book comments on this directly: “This structure allows us to obtain a single instance of our peripheral.”
The real crates do the same. In cortex-m, the call Peripherals::take() returns the core peripherals “once” as an Option: Some(p) the first time, None after that. The struct holds SYST (the SysTick timer), NVIC (the interrupt controller), SCB, DWT, MPU and more. Each field is its own owned value. A chip-specific crate gives the same for USART, GPIO and the rest.
Try it. The vault holds the USART2 value. Take it, hand it around, and see what the checker says.
The vault is a static holding Some(usart2). Press take(), then try the other actions. Each answer is the one the real toolchain gives for this shape of code.
A model of the singleton and move rules. take(), the Option it returns and the unsafe steal() are from the cortex-m docs and the Embedded Rust Book; E0382 is rustc’s code for use after move. The panic on a second unwrap() is what the book’s hand-written version does.
Notice what steal() does. The docs call it the “unchecked version” of take. It is declared unsafe, which means the compiler will not let you call it outside an unsafe block. It is for the rare case where you must make a second owner, for example in a panic handler. Everywhere else, the single owner stays single.
Compare the two worlds. In C, the double setup of USART2 is the symptom of garbled text that depends on file order. The measurement is a scope or logic analyzer on the TX pin, which shows a bit time that does not match the terminal. The fix is a code review that finds both files.
In Rust, the second call to take() gives None. If you unwrap() it, the board panics on boot, every time, on your desk. The bug cannot hide. It also cannot wait for a rare timing event in the field. That is the trade: a rare, silent failure becomes a certain, loud one.
The book adds one more detail. With the RTIC framework (Chapter 8), you receive the Peripherals struct already built, with fields that are not wrapped in Option. The framework calls take() once for you, so your code never sees the None case.
take() to configure the same peripheral. What happens in Rust, compared with C where both write the same registers?Chapter 3
Follow one register write up through the layers, and see how write() and modify() differ in what they keep
You want an interrupt every time USART2 receives a byte. On an STM32F411 that is one switch: the RXNEIE bit (“RXNE interrupt enable”), bit 5 of the control register USART_CR1. The register sits at offset 0x0C from the USART2 base at 0x4000 4400. Every bit in it is a switch for a different feature.
In C, the common line is USART2->CR1 |= USART_CR1_RXNEIE;. The common mistake is USART2->CR1 = USART_CR1_RXNEIE;, with a plain equals sign. One character of difference. The second line writes the whole register, and it turns off every other switch, including the one that enables the whole port.
Embedded Rust stacks small crates (Rust’s word for a library) so that each layer does one job. From the bottom up:
cortex-m): the parts every Cortex-M core has, such as SysTick and the interrupt controller.Nobody types the PAC by hand. A tool called svd2rust generates it from the chip maker’s SVD file, an XML description of every register and bit field. It is the same file your debugger uses to draw its register view. So the register names in the PAC match the reference manual.
The generated code gives three calls on each register. The book describes them like this. read() returns a read-only snapshot you can ask about fields. write() takes a closure that sets fields, and “fields you don’t set revert to defaults, so existing register contents are lost”. modify() gives your closure both the old value and a writer, so you change one field and leave the others.
rustlet dp = pac::Peripherals::take().unwrap(); // read: is a byte waiting? (RXNE is bit 5 of USART_SR) let got = dp.USART2.sr.read().rxne().bit_is_set(); // modify: turn on RXNEIE, keep every other bit dp.USART2.cr1.modify(|_, w| w.rxneie().set_bit()); // write: start from the reset value, set RXNEIE, drop the rest dp.USART2.cr1.write(|w| w.rxneie().set_bit());
Put the C and Rust side by side. write() is the C plain equals. modify() is the C |=. The names are longer, but they make the choice visible in the code, so a reviewer sees it. Rust does not forbid the bug. It makes it easy to spot. Run both on the register below.
The register starts as a working serial port: UE, TE and RE are on. Enable the receive interrupt with each style and compare what survives.
Register facts are from ST’s RM0383 (STM32F411): USART_CR1 at offset 0x0C, reset value 0x0000 0000, with UE bit 13, M bit 12, PCE bit 10, TXEIE bit 7, TCIE bit 6, RXNEIE bit 5, TE bit 3 and RE bit 2. The write() behaviour (unset fields return to defaults) is from the Embedded Rust Book. The start value 0x200C is UE + TE + RE, chosen for this demo.
After modify() the register holds 0x202C: the port, the transmitter, the receiver and the new interrupt. After write() it holds 0x0020. Only RXNEIE is on. The port is disabled, because UE went back to its reset value of zero. The interrupt is enabled on a port that is switched off.
The HAL turns the register work into one call. The exact names vary between HALs, so read this as a typical shape.
rust// the HAL consumes the PAC's USART2: it now owns the port let mut serial = Serial::new(dp.USART2, (tx_pin, rx_pin), config, &clocks); serial.listen(Event::Rxne); // sets RXNEIE, without clobbering
This ties back to Chapter 2. Serial::new takes dp.USART2 by value. It is a move. After the call, your code no longer has the raw register block, so it cannot poke CR1 behind the driver’s back. In C, the driver and a stray line elsewhere can both write the register.
Some register fields accept any bit pattern. Others do not. The book explains that when the generated code “can’t confirm that every possible argument” is valid, the accessor is marked unsafe, for example when you write a raw number with bits(). So the PAC sorts writes into two kinds: named, checked ones, and raw ones where you say “trust me”.
Some reads change the chip. ST’s manual says the ORE (overrun error) bit is cleared by a read of USART_SR followed by a read of USART_DR. RXNE is also cleared by reading DR. A read() in Rust is still a plain read of the address. It does not know about side effects. This is why a debugger that polls a register view can change what the chip does.
cr1.write(|w| w.rxneie().set_bit()). What is in CR1 afterwards?Chapter 4
Move a pin through its modes and watch the compiler remove the calls that are not valid yet
A pin on a microcontroller has moods. It can be switched off. It can be an input, floating or pulled up or down by a resistor. It can be an output driving the line high or low. Each mood allows some actions and forbids others. Setting an input pin high means nothing. Reading a pin that is switched off returns junk.
In C, the mood lives in the chip, and your code keeps it in its head. Nothing stops you from calling gpio_set(pin) on a pin that is still an input. The call either does nothing or writes a bit that no circuit reads. You find out when the LED stays dark.
The Embedded Rust Book builds the same GPIO config two ways. The first way checks the mood at run time. Every method looks at the hardware state first. The book’s set_direction returns Err unless the pin is enabled. That works, but it has two costs. Each call spends cycles on the check, and you must remember to handle the error.
The second way checks at build time. The mood becomes part of the value’s type. This is called typestate programming. The book defines it as “the encoding of information about the current state of an object into the type of that object”.
The type carries three marks. GpioConfig<ENABLED, DIRECTION, MODE> says whether the pin is enabled, whether it is an input or an output, and which pull it has. Each mark is a tiny type with no data inside, such as Enabled or Output. A type with no data takes no memory, so the marks vanish when the program is built.
Here is the key trick. You write a method only in the impl block of the state where it makes sense. The book states it exactly: set_bit is available only on GpioConfig<Enabled, Output, DontCare>. On any other state, the method does not exist. Calling it is a compile error, with no run-time check at all.
rustlet pin: GpioConfig<Disabled, _, _> = get_gpio(); // pin.into_input_pull_down(); // compile error: pin is not enabled let input = pin.into_enabled_input(); let high = input.bit_is_set(); // input.set_bit(true); // compile error: input pins have no set_bit
Each change of state is a method that takes self by value and returns the new type. That is a move, from Chapter 2. The old value is consumed. You cannot keep using the pin in its old mood after you changed it, because the old name is dead. The book says of its builder example that calling the final step “consumes the original structure, meaning it can not be reused”.
Try the pin below. It models the book’s GPIO example. Press the calls in any order, including wrong ones.
The highlighted box is the pin’s current type. Press a call. If the method exists in that type, the pin moves. If not, the build refuses.
Modelled on the GpioConfig example in the Embedded Rust Book, chapter “Design Contracts”. The method set is simplified: the book’s version has more pull modes and states. The rule it shows is the same: set_bit exists only on an enabled output, and illegal moves do not compile. E0599 is rustc’s code for “no method found”.
The book says: “Because we are enforcing our design constraints entirely at compile time, this incurs no runtime cost.” The check is gone before the chip sees the code. The price is paid elsewhere. Type names grow long, and the error messages talk about generics. A pin that changes mood at run time, for example because a user pressed a button, needs more care. You can hold it in an enum or give up a little of the guarantee.
Real HALs follow this pattern for pins, often typing a pin as an input or an output, and for peripherals that need set-up in a fixed order. The idea is wider than GPIO. Any rule of the form “do A before B” can become a type: a clock must be on before you use a timer, a bus must be configured before you read a sensor.
set_bit(true) on a pin that is an enabled input. When do you find out, and what does it cost at run time?Chapter 5
Compare the same sensor driver in C and in Rust, and count how many ports shared traits save
You wrote a driver for a temperature sensor on an STM32. It works. A month later the team moves the product to a Nordic chip. The sensor is the same, the I2C protocol is the same, and the register map is the same. But your driver calls HAL_I2C_Mem_Read, a function that exists only in ST’s library. The driver must be edited, and the edit touches every line that reaches the bus.
You met this layering in From Register Map to Driver. The C answer there was a table of function pointers: the driver calls bus->write_read(...), and each chip supplies its own function. Rust has a built-in way to say the same thing, with a check.
A trait in Rust is a list of functions a type promises to have. It is like a header file the compiler enforces. A generic function says: “I accept any type that keeps this promise.” The compiler then makes a copy of the function for each real type, at build time.
The embedded-hal crate is a library of such contracts. Its own words: “a set of traits which define implementation contracts between HAL implementations, drivers and applications”. Version 1.0.0 has modules for digital pins, i2c, spi, pwm and delay. There are no serial traits in it. Serial ports are covered by a sibling crate, embedded-io, which models a port as a stream of bytes.
Three parties use these contracts. The book names them. A HAL implementation (for STM32, nRF, RP2040) supplies the types and implements the traits. A driver (for a sensor, a display) is written once against the traits. The application picks a HAL and a driver and joins them. The application is the part you must port when the board changes, because pins and clocks differ.
Here is a driver for an imaginary temperature sensor, called T1, at I2C address 0x48. It has a 16-bit temperature register at register 0x00. First in C, then in Rust.
ctypedef struct { int (*write_read)(void *bus, uint8_t addr, const uint8_t *w, size_t wl, uint8_t *r, size_t rl); void *bus; // the chip's I2C handle, as an untyped pointer uint8_t addr; } t1_t; int t1_read_raw(t1_t *d, int16_t *out) { uint8_t reg = 0x00, buf[2]; int rc = d->write_read(d->bus, d->addr, ®, 1, buf, 2); if (rc) return rc; *out = (int16_t)((buf[0] << 8) | buf[1]); return 0; }
rustuse embedded_hal::i2c::I2c; pub struct T1<I> { i2c: I, addr: u8 } impl<I: I2c> T1<I> { pub fn new(i2c: I, addr: u8) -> Self { Self { i2c, addr } } pub fn read_raw(&mut self) -> Result<i16, I::Error> { let mut buf = [0u8; 2]; self.i2c.write_read(self.addr, &[0x00], &mut buf)?; Ok(i16::from_be_bytes(buf)) } }
Compare them line by line. The C struct holds the bus as void *, so the compiler cannot tell whether you passed an I2C handle or a UART. The Rust struct holds a value of type I, and the bound I: I2c says it must be an I2C bus. Pass a UART and the build stops.
The C code returns an integer you can forget to check. The Rust code returns Result, and the compiler warns when you ignore it. The ? passes an error up in one character. The error type is the bus’s own, I::Error, so the driver does not invent codes.
There is one more link to Chapter 2. T1::new(i2c, 0x48) takes the bus by value. The driver now owns it. Two sensors on one wire need a shared bus. The embedded-hal-bus crate exists for that, and it faces the same sharing problem as our UART. Chapters 6 and 7 are about exactly that.
Why does a standard contract matter? The book answers with arithmetic. Without shared traits, each of M chips needs its own version of each of N drivers: M × N pieces of work. With shared traits, each chip implements the traits once and each driver is written once: M + N pieces. Slide the numbers and watch the grids.
Rows are chips, columns are drivers. In the left grid every cell is a port you write by hand. On the right, one bar per chip and one per driver.
The M × N versus M + N comparison is the one in the Embedded Rust Book’s portability chapter. Chip and driver counts here are yours to choose; real projects also port the application, which no trait removes.
With 4 chips and 8 drivers, you write 32 ports by hand or 12 pieces with traits. The gap widens as the numbers grow.
The symptom after porting is a sensor that reads all zeros or all ones. The measurement is a logic analyzer on the I2C lines: you see the address byte on the wire and the sensor never answers with an acknowledge bit. A common cause is the 7-bit address versus the 8-bit address, which is the 7-bit address shifted left once with the read/write bit added. Some C libraries expect the shifted form, others do not.
The fix is to put that convention in one place. The embedded-hal I2C trait takes a 7-bit address, so a HAL implementation does the shift once, and every driver passes 0x48 and is right. In C the same fix needs discipline. In Rust the shared contract carries it.
A last benefit: a HAL implementation may be a mock. The book lists “a mock for unit tests” as one valid backend. You can run the T1 driver on your laptop against a fake bus. The testing lesson, Test Firmware Without the Board, uses that idea in C and in Rust.
Chapter 6
Try five ways to give the port to three callers, and learn why Rust accepts only some of them
Here is the board you are programming. It has one serial port, USART2, wired to a terminal. Three pieces of code want to use it. The main loop prints a status line every 100 ms. The receive interrupt, RX ISR, echoes each byte you type. A timer interrupt, TIM ISR, sends a heartbeat dot once a second. One port, three callers, and two of them can cut into the third at any instruction.
Chapter 2 gave you the rule: one owner. Three callers need one owner. That is the puzzle, and it is real. Every firmware that logs from an interrupt meets it.
Start with the plain idea. Give the port to main as uart, then pass &mut uart to each caller. Rust refuses, with error E0499: you cannot borrow uart as mutable more than once at a time. That is the rule from Chapter 0, now aimed at your code: two writers at once.
There is a second reason. An interrupt handler is a plain function the hardware calls. It takes no arguments, so there is nowhere to pass the port in. The handler can only reach things that live in a static. And the book tells us that a static must be Sync, which means safe to share between threads. It also says interrupts count as a separate thread. So the type of whatever you put in that static must prove that sharing is safe.
The easy way out is static mut, a mutable global. The book is blunt: “static mut variables are always unsafe to read or write.” Rust makes you write unsafe each time you touch it. Recent compilers go further. In the 2024 edition the static_mut_refs lint is deny by default, because merely taking a reference to a static mut breaks the aliasing rule, “even if the reference is never read from or written to”.
Choose each approach below. The device shows who holds the UART, what the compiler says, and what happens when you run 1,000 messages through it.
Pick an approach. The picture shows who may reach the UART. Then press Run 1,000 messages to see what each approach does under load.
The compiler messages are paraphrased; E0133 (unsafe needed), E0499 (second mutable borrow) and E0382 (use after move) are rustc’s real codes, and the static_mut_refs lint level is from the Rust 2024 edition guide. The run is a seeded toy: an interrupt lands inside a message on 30% of messages (illustrative), a message is 5 bytes, and a byte takes 86.8 µs at 115,200 baud. The queue capacity rule (N minus 1 slots) is from the heapless docs.
Look at the five answers in turn.
A, static mut. It builds once you add unsafe at every use. Nothing checks the sharing. The bug from Chapter 0 is back, now in a UART: an interrupt cuts into a half-sent message. Symptom: garbled lines, about one in three under load in our toy run. Measurement: a logic analyzer on TX shows bytes of two messages interleaved. Fix: one of the next two rows.
B, pass &mut. Rejected, for the two reasons above. This is Rust doing its job: it found the design flaw before the chip ran.
C, move to one ISR. Builds, and is correct, but only one caller can use the port. The main loop now fails with E0382, because its name for the UART moved away. This fits when only one party really needs the port, such as a pure echo.
D, queues. Make one owner and let everyone else send it messages. The main loop owns the transmit side. Each ISR owns the producer end of a queue, and the main loop owns the consumer ends. The heapless crate provides a single-producer, single-consumer queue whose split() gives you a (Producer, Consumer) pair, and the docs say the two halves can go to different contexts such as interrupt handlers. No locks. No interrupt is ever delayed. The price: a byte waits until the main loop drains the queue. Setup takes one small unsafe to get the queue’s &'static mut, as the docs show.
E, Mutex with a critical section. Put the UART in a static wrapped in Mutex<RefCell<Option<Uart>>>. Any caller must enter a critical section, which turns interrupts off, before it can open the box. Correct, simple, and no unsafe in your code. The price is time: while main holds the box, an interrupt waits. Chapter 7 measures it.
| Approach | Builds in safe Rust? | Data race? | Price |
|---|---|---|---|
| A. static mut | No, needs unsafe at each use | Yes | Your attention |
| B. pass &mut | No, E0499 | Not applicable | Does not exist |
| C. move to ISR | Yes | No | Main cannot print |
| D. queues | Yes, one unsafe in setup | No | Bytes wait for main |
| E. Mutex | Yes | No | Interrupts wait for main |
In C, row A is the default and rows D and E take extra work. Nothing in C asks you which row you chose. A reviewer must spot a missing lock by reading. In Rust the choice is forced into the types, so the build itself asks the question. That is the whole trade of this lesson: the compiler cannot pick the right design for you, but it will not let you skip the choice.
&mut uart to both interrupt handlers?Chapter 7
Measure what a lock costs an interrupt, and learn when one atomic instruction does the job instead
You picked row E in Chapter 6, the Mutex. It works. Then a motor ISR that must run every millisecond starts to jitter. It is sometimes 15 µs late, sometimes 40. Nothing is broken. The motor ISR is waiting at a locked gate, and the gate is the lock your UART code takes.
A critical section is, in the book’s words, “a context where interrupts are disabled.” Inside it, no interrupt can cut in, so your code can touch shared data in peace. On a Cortex-M the entry and exit are a few instructions that mask and restore interrupts. The book’s example is one line of structure:
rustcortex_m::interrupt::free(|_| { unsafe { COUNTER += 1 }; });
The portable way is the critical-section crate. Its function with() runs your closure inside a critical section and hands it a token named cs. The token proves to other code that you are inside one. Its Mutex only opens when you show the token:
rustuse core::cell::Cell; use critical_section::Mutex; static MY_VALUE: Mutex<Cell<u32>> = Mutex::new(Cell::new(0)); critical_section::with(|cs| { MY_VALUE.borrow(cs).set(42); // the token "proves" we are inside });
This is the same idea as Chapter 2, one level up. The token is an owned value that only exists inside the section. Code that needs the data must hold the token, and the token cannot escape the closure. The compiler enforces that, so you cannot forget the lock.
The crate does not pick how to disable interrupts. Each platform does. The crate docs list them: on a single-core bare-metal chip, disable interrupts; on a multi-core chip, disable them on this core and take a spinlock; under an RTOS, take the scheduler lock. The book adds a warning: a critical section alone “does not provide an exclusivity guarantee on multi-core systems”.
While interrupts are off, every interrupt waits. An interrupt that arrives right after the section starts waits for the whole section. Then the core needs its normal entry time. Arm’s blog gives that as 12 cycles for a Cortex-M4 with zero-wait-state memory: the time from the request to the first handler instruction. So:
worst-case latency = cycles inside the section + 12 cycles
At an illustrative 100 MHz, one cycle is 10 ns. A section of 2,000 cycles holds an interrupt for up to 20 µs, and 12 more cycles bring the total to 20.12 µs. The book names the cost: critical sections “add code size and raise interrupt latency and jitter”. Try numbers.
The orange bar is the critical section. The purple arrow is an interrupt that arrives at the worst moment, just after it begins. The dashed line is your deadline.
The 12-cycle entry latency is Arm’s figure for Cortex-M4 with zero-wait-state memory (Arm Community blog on interrupt latency); wait states, a busy bus or a higher-priority interrupt add to it. The 100 MHz clock and every section length here are illustrative. An atomic instruction is a single step, so it adds no masked time.
With the defaults, a 600-cycle section means up to 6.12 µs of delay, well inside a 20 µs deadline. Raise the cycles past 1,988 and the deadline is missed. Switch to Atomic and the delay drops to the 12 cycles of entry, because nothing was masked.
An atomic operation is one the hardware does as a single indivisible step. Nothing can land in the middle. The Chapter 0 counter becomes:
rustuse core::sync::atomic::{AtomicUsize, Ordering}; static COUNTER: AtomicUsize = AtomicUsize::new(0); COUNTER.fetch_add(1, Ordering::Relaxed); // main COUNTER.store(0, Ordering::Relaxed); // ISR
No unsafe, no gate, no wait. The book recommends atomics where the platform allows. But there is a catch tied to the chip. On thumbv6 targets (Cortex-M0 and M0+), the book says the core provides only atomic load and store. No atomic add. On thumbv7 (Cortex-M3 and up), it provides compare-and-swap, which is enough to build the rest. So an atomic counter works on your M4 board and may not on a cheap M0.
The Ordering argument tells the compiler how much to fence in other memory. On a single core, the book says Relaxed is enough. Stricter orderings make the compiler emit memory barriers, which cost time.
For a peripheral like our UART, the book gives the shape: Mutex<RefCell<Option<T>>>. Read it from the inside out. Option because the peripheral exists only after startup, so the static starts as None. RefCell because it lets you borrow the value mutably, with a run-time check. Mutex because it opens only inside a critical section.
Order matters. The book warns: enable the interrupt only after you have put the peripheral in the static. If the interrupt fires first, the handler finds None.
Failure, in the usual three beats. Symptom: the first interrupt after boot does nothing, or panics on unwrap(). Measurement: a toggled pin at the top of the handler shows it ran, and a second pin after the unwrap never rises. Fix: move the line that enables the interrupt below the line that fills the static.
Chapter 8
Compare tasks that preempt by priority with tasks that take turns, and see what each does with idle time
By now you have written the same plumbing three times: put the peripheral in a static, wrap it in a lock, remember the order of setup. Two frameworks do this plumbing for you and check it at build time. RTIC schedules by interrupt priority. Embassy schedules tasks that take turns. Both run without a heap, and both avoid a stack per task.
RTIC stands for Real-Time Interrupt-driven Concurrency. Its own book calls it “a hardware accelerated RTOS” that uses the interrupt controller (the NVIC) on Cortex-M chips. A task is a function. A hardware task is bound to an interrupt, so the hardware starts it. Each task has a static priority, a number you set in the code. A higher number preempts a lower one.
Data shared between tasks lives in a #[shared] struct. Data owned by one task lives in #[local]. To touch shared data, a task calls lock, which the book describes as temporarily raising the task’s priority to a ceiling, the highest priority of any task that uses that data. While the lock is held, no task that shares the data can preempt. That rule is the Stack Resource Policy (SRP), and it gives what the RTIC book promises: “guaranteed race-free resource access and deadlock-free execution on a single-shared stack”.
The RTIC book’s lock example shows the idea. It has three tasks: foo at priority 1, bar at 2 and baz at 3. Only foo and bar use the shared number.
rust#[task(shared = [shared])] // priority 1 by default async fn foo(mut c: foo::Context) { hprintln!("A"); c.shared.shared.lock(|shared| { *shared += 1; bar::spawn().unwrap(); // waits: bar needs `shared` hprintln!("B - shared = {}", *shared); baz::spawn().unwrap(); // runs now: baz does not use it }); hprintln!("E"); }
Follow it step by step. First foo prints A and takes the lock, which raises it to the ceiling, priority 2. Then it asks for bar (priority 2). The scheduler holds bar back, because foo is already at 2. Next foo prints B. Then it asks for baz (priority 3). baz does not use the shared number, so it is above the ceiling and runs at once and prints C. When the lock ends, bar runs and prints D. Finally foo prints E. The book lists the order A, B, C, D, E. Notice the key line from the book: the highest-priority handler “is free to preempt a critical section created by the lowest priority handler”. Only tasks that share the data are held back.
That is the big gain over the global gate of Chapter 7. The gate stops every interrupt. The ceiling stops only the tasks that could collide. The RTIC examples even begin with #![deny(unsafe_code)], which makes the compiler reject any unsafe in the app.
Embassy uses Rust’s async and await. An async function can stop in the middle, say “wake me later”, and give the core to someone else. The marker for that pause is .await. The Embassy site says tasks “get transformed at compile time into state machines that get run cooperatively”. The compiler writes the state machine that you would otherwise code by hand, as you did in the drivers lesson.
rust#[embassy_executor::task] async fn blink(pin: Peri<'static, AnyPin>) { let mut led = Output::new(pin, Level::Low, OutputDrive::Standard); loop { led.set_high(); Timer::after_millis(150).await; // yields: the core can run others or sleep led.set_low(); Timer::after_millis(150).await; } }
The executor is the loop that runs ready tasks. When no task is ready, Embassy’s docs say it will “put the microcontroller to sleep”, and an interrupt wakes it. Tasks need “no dynamic memory allocation” and run “on a single stack, so no per-task stack size tuning is required”. If you need priorities, you start several executors, and a higher-priority one can preempt a lower one.
The catch is in the word cooperative. A task runs until it awaits. A task that never awaits blocks everything on its executor. Compare the two schedulers on a real-looking clash.
Task B (blue) is a long formatting job that starts at 0 ms. Task A (purple) is a received byte that needs 0.4 ms of work and arrives at 3 ms. Grey time is the core asleep.
A toy schedule in a 12 ms window, not a measurement. The behaviours are from the RTIC book (higher static priority preempts) and the Embassy site (tasks run until they await; several executors give priorities; the core sleeps when nothing is ready). The second slider only matters for one Embassy executor; 9 ms means B never awaits.
With the defaults, B needs 6 ms and never awaits. Under RTIC, A starts the moment it arrives at 3 ms. On one Embassy executor, A waits until B finishes at 6 ms, so it starts 3 ms late. Move the second slider to 1 ms and A waits only until B’s next await. Or choose two executors and A preempts again.
Symptom: on one executor, bytes arrive but some are lost, with the overrun flag set. ST’s manual says an overrun happens when the receive register is still full as the next byte arrives. Measurement: timestamp the start of the RX task and compare with the arrival time. The gap is the longest stretch of another task without an await. Fix: add await points to the long task, move the RX work to a higher-priority executor, or let DMA catch the bytes.
Chapter 9
Walk down the layers of a Rust firmware project and find the few places that must say “trust me”
Open a firmware repository written in Rust and search for the word unsafe. A newcomer expects hundreds of hits, because the code pokes raw hardware. A well-built project shows a handful, in a few files, almost all deep in the stack. Your application code often shows none. This chapter explains why, and where the hits live.
The word is easy to misread. unsafe does not mean “this code is dangerous”. It means “the compiler cannot check this part, and a human promises it is right.” The Rust book lists exactly five things an unsafe block lets you do:
union.The same page adds two rules worth keeping. One: unsafe “doesn’t turn off the borrow checker or disable any of Rust’s other safety checks.” A reference inside an unsafe block is still checked. Two: “Keep unsafe blocks small.”
Now you can see why firmware needs it. A peripheral is a fixed address, so it needs a raw pointer (power 1). A static mut needs power 3, which is what Chapter 6 row A used. Some functions, such as Peripherals::steal() from Chapter 2, are declared unsafe (power 2). And a lock type that says “sharing me is fine” must implement an unsafe trait (power 4).
Rust does not remove those five powers. It lets you wrap them. The author of a crate writes an unsafe block once, checks the reasoning, and exposes a safe function. Callers use the safe function and need no unsafe. If the wrapper is right, nothing a caller does can break memory safety. If it is wrong, the bug is in that one small block, which you can find by search.
The Embedded Rust Book shows this in the counter example. The counter lives in an UnsafeCell inside a struct, and the author writes unsafe impl Sync for CSCounter {}, a promise that sharing it is fine. The book then explains the condition: that promise holds only on single-core chips, and the methods demand a CriticalSection token. After that, every user calls plain safe methods.
Click through the layers of a typical project. For each one, the device shows which of the five powers it tends to use and who vouches for it.
Pick a layer from the stack. Dots show which of the five unsafe powers it typically needs. Switch to C to see the same stack with no marker at all.
The five powers are the list in the Rust book, chapter “Unsafe Rust”. Which layer uses which is typical and reasoned from the Embedded Rust Book (PAC accessors marked unsafe, the unsafe impl Sync in the abstraction example, cortex-m-rt’s startup); real crates vary. The RTIC examples begin with deny(unsafe_code), which is why the application row shows none.
Read the stack from the top. The application sits above everything and can ban the keyword in one line: #![deny(unsafe_code)], which the RTIC book’s examples use. If your app crate has that line, every unsafe must live in a library you chose. The reviewer's question becomes: do I trust these crates?
The PAC is the first honest user. The register block is a fixed address, so it dereferences a raw pointer. And, per the book, writers for fields it cannot fully check are marked unsafe. The HAL builds safe calls on top. It still faces hardware facts it cannot prove, such as a DMA buffer that must stay in place while the hardware reads it. Below that, the runtime crates run startup code and implement the critical-section token.
An unsafe mistake looks different from a normal bug. Symptom: the firmware works in a debug build and fails in release, or fails only after an unrelated edit. The optimizer assumed a rule you broke, so the language gives no promise about the result. Measurement: count the unsafe blocks, and read each next to its reasoning. Search the repository for unsafe, and compile your app crate with deny(unsafe_code) to see which dependencies you rely on. Fix: shrink the block until it holds one fact, state the fact in a comment, and wrap it in a function whose arguments make the fact impossible to break.
The heapless docs model the comment habit. Their usual setup note says the queue static is split once:
ruststatic mut Q: Queue<u8, 64> = Queue::new(); // SAFETY: this runs once, in main, before any interrupt is enabled, // so nothing else can reach Q while we hold this reference. let (prod, cons) = unsafe { (&mut *&raw mut Q).split() };
The queue holds 63 bytes, not 64, because the docs say a queue of N slots has capacity N minus 1. The &raw mut form is the one the 2024 edition guide recommends when you must turn a static mut into a reference. After this line, the handlers hold the prod and cons halves with no unsafe at all.
C has no marker. The line that sets up the queue, the line that writes a register and the line that adds two integers all look alike to the compiler and to the reviewer. Every line is, in Rust terms, potentially unsafe. Rust does not make hardware less dangerous. It draws a line around the dangerous part and puts a label on it.
unsafe in firmware is true?Chapter 10
Keep the numbers, the terms, the checklist, the core code and the sources on one page
Embedded Rust is C-level control with a referee. The language runs with no operating system (no_std). It makes each peripheral a value with one owner. Generated register crates and HALs build safe calls on top, and types remember the state of a pin. A shared contract, embedded-hal, lets one driver run on many chips. When code must share data, you choose a single owner, a queue, a critical section, an atomic or a framework such as RTIC or Embassy. The compiler asks you to choose. The few places that need unsafe sit deep in the stack and carry a label.
| What | Number | Why it matters |
|---|---|---|
| micro:bit v2 chip (nRF52833) | 64 MHz Cortex-M4 with FPU, 512 KB flash, 128 KB RAM | The size of a typical Rust target |
| no_std feature table | 2 of 7 rows plain yes; heap and collections need alloc | What you keep without an OS |
| USART2 on STM32F411 | base 0x4000 4400; SR 0x00, DR 0x04, BRR 0x08, CR1 0x0C | Where the registers sit |
| USART_SR flags | TXE bit 7, TC bit 6, RXNE bit 5, ORE bit 3 | Poll or enable the interrupt for these |
| USART_CR1 bits | UE 13, TXEIE 7, TCIE 6, RXNEIE 5, TE 3, RE 2; reset 0x0000 | write() returns the rest to 0 |
| CR1, working port | 0x200C; modify gives 0x202C; write gives 0x0020 | Clobbering turns the port off |
| One byte, 115,200 baud 8N1 | 10 bit times, 86.8 µs | Sizes the wait for a held UART |
| Cortex-M4 interrupt entry | 12 cycles (zero wait states) | The floor under any latency |
| Critical section cost | latency = cycles inside + 12; 2,000 cycles at 100 MHz = 20.12 µs | Why long gates break deadlines |
| Atomics by core | thumbv6: load and store only; thumbv7: compare-and-swap | Whether an atomic add is available |
| embedded-hal sharing | M × N becomes M + N | Why drivers stop being ported |
| heapless SPSC queue | N slots hold N − 1 items | Size the ISR queue for one spare |
| Unsafe powers | 5 (raw pointer, unsafe fn, static mut, unsafe trait, union) | The full list to audit |
core, not std. core: the library part that needs no OS.&T (many readers) or &mut T (one writer).Peripherals::take().unsafe block hold one fact, with a comment, in a small safe wrapper?#![deny(unsafe_code)]?This is the shape of row E from Chapter 6, with every lesson in one file. HAL names differ between chips, so read Uart and its methods as stand-ins.
rust#![no_std] #![no_main] use core::cell::RefCell; use cortex_m::peripheral::NVIC; use cortex_m_rt::entry; use critical_section::Mutex; use panic_halt as _; use pac::interrupt; // from the chip's PAC // Chapter 7: Mutex opens only inside a critical section; Option because it starts empty static UART: Mutex<RefCell<Option<Uart>>> = Mutex::new(RefCell::new(None)); #[entry] fn main() -> ! { // Chapter 1: never returns let dp = pac::Peripherals::take().unwrap(); // Chapter 2: taken once let uart = Uart::new(dp.USART2, /* pins, config, clocks */); // Chapter 3: HAL consumes it critical_section::with(|cs| { UART.borrow(cs).replace(Some(uart)); }); unsafe { NVIC::unmask(pac::Interrupt::USART2) }; // Chapter 7: only AFTER the static is filled loop { cortex_m::asm::wfi(); } // sleep until an interrupt } #[interrupt] fn USART2() { // Chapter 6: no arguments, so it reaches a static critical_section::with(|cs| { if let Some(uart) = UART.borrow(cs).borrow_mut().as_mut() { if let Ok(b) = uart.read_byte() { let _ = uart.write_byte(b); } } }); }
Count the unsafe in it: one, the call that unmasks the interrupt, which the cortex-m crate marks unsafe because enabling an interrupt can break a critical section built on masking. Everything else is checked.
Embedded Rust does not replace C overnight. The Embedded Rust Book itself shows how to mix C and Rust in one project, and most chips ship C headers and C vendor libraries. What Rust offers is a way to move the sharing rules from code review into the build. Whether that is worth the learning cost depends on how much shared state your product has. This lesson did not cover DMA ownership, Rust on Linux, or the C++ alternative to these ideas.
no_std gives up.cortex-m-rt replaces.Every number and rule above comes from a page we opened. The Embedded Rust Book (no_std, singletons, concurrency, registers, exceptions, design contracts, portability); the micro:bit v2 Discovery Book (its scope and approach; see the source note); RTIC book; Embassy book; embedded-hal 1.0.0; critical-section; heapless::spsc; cortex-m Peripherals; cortex-m-rt; Rust book, Unsafe Rust; Rust 2024 edition guide, static mut references; ST RM0383 for the STM32F411 (read through a mirror at docs.dirba.io); the Nordic nRF52833 page; and Arm’s interrupt latency blog.
Source note. The Discovery MB2 book is an introductory course that lists some topics as hopes for later, and its Background chapter gives the micro:bit v2’s data memory as 256 KB. Nordic’s product page lists 128 KB of RAM for the nRF52833, so this lesson uses 128 KB. Check your own board’s datasheet. Credit goes to the Rust Embedded Working Group authors, and to the RTIC and Embassy teams, whose documentation we re-taught in our own words and devices.
Now press Present or Teach and explain, from memory, how two interrupts and one UART break in C, what Rust demands before it builds, and which of the five designs you would choose and why. Then go back to the hero and run the three builds again.