Level 3 · Systems· Lesson 11 of 11 · 25 min
no_std and embedded Rust
Rust without an operating system — core and alloc, panic handlers, memory-mapped registers, HALs, and async on microcontrollers.
The layers of the standard library
| Crate | Needs | Provides |
|---|---|---|
core |
nothing | primitives, Option, Result, iterators, slices, str, atomics, Cell, traits, fmt |
alloc |
a global allocator | Box, Vec, String, Rc, Arc, BTreeMap |
std |
an operating system | files, networking, threads, HashMap, time, processes |
#![no_std] at the crate root links only core. The language itself — ownership, traits, generics, closures, async — is entirely intact. Many libraries are no_std-compatible and offer std and alloc as optional features; writing your own libraries that way widens where they can run.
A bare-metal program
With no OS there is nobody to call main, print panics, or provide a heap. You supply those pieces:
// src/main.rs — for a Cortex-M microcontroller (thumbv7em-none-eabihf)
#![no_std]
#![no_main]
use core::panic::PanicInfo;
use cortex_m_rt::entry;
#[entry]
fn main() -> ! {
// `!` — this function never returns. There is nothing to return to.
let mut counter: u32 = 0;
loop {
counter = counter.wrapping_add(1);
}
}
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
// Decide what a panic means on your device: halt, reset, blink an LED, log over a debug probe…
loop {}
}
The cortex-m-rt crate provides the reset vector, initialises RAM and calls your #[entry] function; a linker script (memory.x) describes where flash and RAM are. Build with cargo build --target thumbv7em-none-eabihf and flash with probe-rs.
Talking to hardware
Peripherals are controlled through memory-mapped registers: fixed addresses where reading and writing have side effects.
use core::ptr::{read_volatile, write_volatile};
/// A stand-in for a real device register so this example runs anywhere.
static mut FAKE_GPIO_ODR: u32 = 0;
struct Register(*mut u32);
impl Register {
fn read(&self) -> u32 {
// SAFETY: the pointer refers to a valid, aligned u32 for the program's lifetime.
unsafe { read_volatile(self.0) }
}
fn modify(&self, f: impl FnOnce(u32) -> u32) {
// SAFETY: as above.
unsafe { write_volatile(self.0, f(read_volatile(self.0))) }
}
}
fn main() {
// On a real chip this would be a fixed address from the datasheet, e.g. 0x4002_0014.
let odr = Register(&raw mut FAKE_GPIO_ODR);
odr.modify(|v| v | (1 << 5)); // set pin 5 high
odr.modify(|v| v | (1 << 13)); // set pin 13 high
odr.modify(|v| v & !(1 << 5)); // set pin 5 low
println!("{:#018b}", odr.read());
}
Nobody writes register addresses by hand. The ecosystem is layered:
- Peripheral access crates (PACs) — generated by
svd2rustfrom the vendor’s description files; a typed API for every register and bit field. - HAL crates — safe drivers per chip family:
stm32f4xx-hal,rp2040-hal,esp-hal,nrf52840-hal. embedded-hal— traits (OutputPin,SpiBus,I2c,DelayNs) that HALs implement, so a driver for a sensor or display works on any chip.
Ownership as a hardware safety tool
This is where Rust’s type system pays off most visibly. Peripherals are singletons you can take once; configuring a pin consumes it and returns a different type. The following runs on your computer but has the shape of every HAL:
use core::marker::PhantomData;
struct Input;
struct Output;
struct Pin<Mode> {
number: u8,
_mode: PhantomData<Mode>,
}
struct Peripherals {
pin5: Pin<Input>,
}
impl Peripherals {
/// In a real HAL this returns `Some` exactly once.
fn take() -> Peripherals {
Peripherals { pin5: Pin { number: 5, _mode: PhantomData } }
}
}
impl Pin<Input> {
fn is_high(&self) -> bool { false }
fn into_output(self) -> Pin<Output> {
println!("configuring pin {} as output", self.number);
Pin { number: self.number, _mode: PhantomData }
}
}
impl Pin<Output> {
fn set_high(&mut self) { println!("pin {} high", self.number); }
}
fn main() {
let p = Peripherals::take();
println!("input reads high? {}", p.pin5.is_high());
let mut led = p.pin5.into_output(); // moves pin5: nothing else can use it now
led.set_high();
// p.pin5.is_high(); // ❌ would not compile: pin5 was moved
// led.is_high(); // ❌ would not compile: no such method on Pin<Output>
}
Driving an input pin, sharing one pin between two drivers, using a peripheral before enabling its clock — a whole class of electrical bugs become type errors. PhantomData<Mode> records the state without occupying any memory. Level 4 generalises this as the typestate pattern.
Concurrency without an OS
Interrupt handlers pre-empt your main loop at any instruction, which is exactly a data-race hazard. The same Send/Sync rules apply:
- Critical sections:
critical_section::with(|cs| …)disables interrupts briefly; aMutex<RefCell<T>>from thecritical-sectioncrate makes shared state accessible only inside one. - Atomics for flags and counters.
- RTIC: a framework that analyses task priorities at compile time and grants lock-free access wherever pre-emption cannot occur.
- Embassy: an async executor for microcontrollers.
async/awaitturns out to be an excellent fit — each task is a state machine with a statically known size, no heap, no per-task stack, and the CPU sleeps whenever every task is waiting.
// crate: embassy (runs on a microcontroller)
#[embassy_executor::task]
async fn blink(mut led: Output<'static>) {
loop {
led.toggle();
Timer::after_millis(500).await; // the core sleeps here
}
}
Working without a heap
- Fixed-capacity collections:
heapless::Vec<T, N>,heapless::String<N>, ring buffers and queues. core::fmt::Writeworks without allocation;defmtprovides very compact logging over a debug probe.- If you do want
alloc, register a#[global_allocator]such asembedded-alloc— and decide what out-of-memory means. - Check stack usage; recursion and large stack arrays are hazards when you have a few kilobytes.
Level 3 checkpoint
You are ready for Level 4 if you can:
- Explain
SendandSyncand say whyRc<RefCell<T>>is neither. - Write an async program with spawned tasks, a timeout and a
select!, and explain cancellation. - Write a
macro_rules!macro with repetition, and outline how a derive macro works. - Wrap an unsafe operation in a safe function and argue that it is sound.
- Expose a Rust function to C or JavaScript, with a clear ownership story for every pointer.
Exercises
- Make a small library crate
#![no_std]with an optionalstdfeature (#![cfg_attr(not(feature = "std"), no_std)]). What breaks when you useVec? Fix it withextern crate alloc;. - Extend the typestate pin with
Pin<Analog>and aninto_analogconversion valid only fromInput. - Write a fixed-capacity ring buffer
struct Ring<T, const N: usize>withpushreturningErr(T)when full, using onlycore. - If you have a development board (a Raspberry Pi Pico or an STM32 Nucleo is ideal), work through The Embedded Rust Book and blink an LED with
embassy.
Check your understanding
Pick an answer to see the explanation.
1.What does
#![no_std]remove?2.Why must hardware registers be accessed with
read_volatileandwrite_volatile?3.How do embedded HAL crates use ownership to prevent two drivers from using the same pin?