skip to content

Embedded and WebAssembly

Rust runs without an operating system through no_std, and in browsers and sandboxes as WebAssembly. Interviewers ask what core and alloc provide and how peripherals are owned.

on this pageshow

explore

questions

23

In embedded Rust, what do a peripheral access crate, a HAL crate, a board support crate and the embedded-hal traits each contribute?

level: juniorimportance: must knowfreq 34%

answer

  1. four layers above the silicon
  2. SVD file in, register API out
  3. safe peripheral types per chip family
  4. traits as the driver contract
  5. pins named after board labels

basics

~20 s

A peripheral access crate, generated from the chip's SVD file by svd2rust, exposes typed registers; a HAL crate wraps them in safe types implementing embedded-hal traits; a board support crate pre-wires one board; drivers need only the traits.

solid answer

~50 s

Firmware is layered. At the bottom, a **peripheral access crate** (PAC) is usually generated by `svd2rust` from the vendor's SVD file: one singleton per peripheral, with `read`, `write` and `modify` on every register, but no knowledge of how the peripheral should be driven. A **HAL crate** for the chip family builds on the PAC, offers safe types such as a configured I2C controller or GPIO pin, and implements the `embedded-hal` 1.0 traits (`i2c::I2c`, `spi::SpiBus`, `digital::OutputPin`, `delay::DelayNs`) for them. `embedded-hal` itself holds those traits and no chip code, so a sensor **driver** written against `I2c` works on any chip whose HAL implements it. A **board support crate** sits on top of a HAL and pre-configures the pins and peripherals of one development board. `cortex-m` and `cortex-m-rt` sit beside the PAC, covering the processor core and the startup code.

go deeper

for a junior

Name the layers in order with one job each: PAC for registers, HAL for safe peripherals, board crate for one board, embedded-hal for the traits drivers use.

for a middle

Explain that svd2rust generates the PAC from the SVD file and that a HAL takes PAC peripherals by value, so ownership stops two layers configuring the same hardware.

for a senior

Show when you drop a layer: PAC access for a peripheral the HAL lacks, HAL setup on a custom board instead of a board crate, and drivers kept generic over embedded-hal traits.

for a principal

Frame the trait layer as the M+N argument: one driver per external part and one HAL per chip family is what lets a product change microcontroller without rewriting drivers.

## Why embedded Rust is layered A microcontroller is a processor core plus dozens of **peripherals**: GPIO ports, timers, I2C and SPI controllers, ADCs. Each peripheral is controlled through **memory-mapped registers**, fixed addresses where reading or writing bits changes what the hardware does. The embedded Rust ecosystem splits the work of driving that hardware into crates with narrow jobs, so that each layer is reused by many projects above it. ## The stack, bottom to top 1. **Micro-architecture crates** such as `cortex-m` cover what every chip with that core shares: the core peripherals (SysTick as `SYST`, the interrupt controller as `NVIC`, the system control block as `SCB`), reached through `cortex_m::Peripherals`. Beside it, `cortex-m-rt` supplies the startup code, the vector table and the `#[entry]` attribute for a `fn main() -> !`, and links with a `memory.x` file that describes flash and RAM. 2. A **peripheral access crate (PAC)** covers one chip or chip family. It is normally generated by the `svd2rust` tool from the vendor's **SVD file**, an XML description of every peripheral, register and bit field. 3. A **HAL crate** is written by hand on top of the PAC for a chip family. It knows the procedures from the reference manual (enable the clock, set the pin mode, wait for a status flag) and hides them behind safe types. 4. A **board support crate** targets one board. It usually depends on a HAL crate and pre-configures pins and peripherals the way that board wires them, so an LED or a button is reachable by its board name. Device **drivers** for external parts (a temperature sensor, a display, a radio) sit to one side: they depend only on `embedded-hal`. ## What a PAC gives you - One type per peripheral, handed out once through `Peripherals::take()`, which returns an `Option`. - A method per register (`odr()`, `moder()` in current svd2rust output) with `read`, `write` and `modify` taking closures over field readers and writers. - Volatile accesses, so the compiler never caches, merges or drops a register access. - No policy: the PAC will let you write a field value the reference manual forbids, which is why raw `bits()` writes are `unsafe` in it. ## What a HAL adds A HAL constructor typically takes PAC peripherals and pins **by value**, configures the hardware and returns a type such as an I2C controller. Because the PAC value was moved in, no other code can reconfigure that peripheral behind the HAL's back. The HAL then implements the `embedded-hal` traits on that type, so its I2C controller is an `embedded_hal::i2c::I2c` and its output pins are `embedded_hal::digital::OutputPin` values. ## embedded-hal: the contract in the middle `embedded-hal` 1.0 contains **traits** plus the small types they use (error kinds, `Operation`, `PinState`), and no code for any chip. Its modules are `delay`, `digital`, `i2c`, `pwm` and `spi`. All of its traits are blocking; the companion crates `embedded-hal-async` and `embedded-hal-nb` carry async and polling versions, and serial ports moved to `embedded-io`. The embedded book states the payoff as arithmetic: with M HAL implementations and N drivers, writing every driver for every chip costs M×N implementations, while a shared trait set brings the cost close to M+N. | Crate kind | How it is produced | Knows about | Example items | |---|---|---|---| | Micro-architecture | one crate per core family | the CPU core | `cortex_m::Peripherals`, `cortex_m_rt::entry` | | PAC | generated by `svd2rust` from SVD | one chip's registers | `Peripherals::take()`, `odr().modify(...)` | | HAL | hand-written per chip family | how to drive peripherals | an I2C type implementing `I2c` | | Board support | written per board | which pins go where | an LED pin by its board label | | `embedded-hal` | trait-only crate | nothing chip-specific | `I2c`, `SpiDevice`, `OutputPin`, `DelayNs` | ## Choosing the layer to work at - Start from a board support crate on a development board; drop to the HAL when the design moves to a custom board. - Use the PAC directly for a peripheral the HAL does not cover, or for a register sequence the HAL does not expose. - Write reusable drivers against `embedded-hal` traits only, never against one HAL's concrete types, or the driver is tied to one chip family. - `cortex-m` and `cortex-m-rt` stay underneath whichever layer you pick on a Cortex-M part.

  • Can Rust firmware mix direct PAC register access with a HAL in the same program?
    Yes. A HAL constructor usually takes the PAC peripheral by value, so once a peripheral is handed to the HAL your code no longer holds it and cannot reconfigure it by accident. Peripherals the HAL never received stay in your hands and can be driven through the PAC's `read`, `write` and `modify`. Reaching a peripheral the HAL owns needs the PAC's `unsafe` `steal()`, and the HAL's assumptions may then break.
  • What do the cortex-m and cortex-m-rt crates provide that a chip's PAC does not?
    `cortex-m` covers the processor core every Cortex-M chip shares: core peripherals such as `SYST` and `NVIC` through `cortex_m::Peripherals::take()`, plus `cortex_m::delay::Delay`, a SysTick delay that implements `DelayNs`. `cortex-m-rt` supplies the reset handler, the vector table, the `#[entry]` attribute that requires `fn main() -> !`, and the `link.x` linker script, which includes the `memory.x` you write for the chip.

  • embedded-hal contains register code for each supported microcontroller family.
  • A PAC is written by hand from the reference manual for each application.
  • A sensor driver should depend on the chip's HAL crate to be efficient.
  • A board support crate replaces the HAL and writes registers itself.
  • Using a PAC means computing register addresses and calling read_volatile by hand.
open as a page

In Rust, what does `#![no_std]` take away from a crate, and what do the `core` and `alloc` crates still provide?

level: juniorimportance: must knowfreq 38%

basics

~20 s

#![no_std] stops std being linked and gives every module the core prelude. core keeps primitives, Option, Result, slices, iterators, fmt and atomics; alloc, added with extern crate alloc, brings Vec, String and Box; I/O, threads and HashMap stay in std.

open as a page

In Rust, what does `#[wasm_bindgen]` generate for an exported function, and why can a browser not load the `.wasm` that `cargo build` produces directly?

level: juniorimportance: must knowfreq 38%

basics

~20 s

#[wasm_bindgen] wraps the function in an exported shim with a numeric signature (pointers and lengths), plus descriptor functions. The wasm-bindgen CLI, usually run by wasm-pack build, reads them, rewrites the module and writes the JavaScript glue a page imports.

open as a page

In embedded Rust, how do you write a temperature-sensor driver once against embedded-hal 1.0's `I2c` trait so it runs on two different microcontrollers?

level: middleimportance: must knowfreq 40%

basics

~20 s

Make the driver generic over a type parameter bounded by embedded_hal::i2c::I2c, store the bus by value, and return I2C::Error from its methods. Each chip's HAL implements I2c for its controller, so both firmwares pass their own bus in.

open as a page

In embedded Rust, why does `cortex_m::Peripherals::take()` return an `Option`, and what does the `unsafe` `steal()` give up?

level: middleimportance: must knowfreq 37%

basics

~20 s

Peripherals are singletons: the first take() returns Some and every later call returns None, so each piece of hardware has one owner. The unsafe steal() skips that check, making exclusive access your promise instead of the compiler's.

open as a page

In Rust firmware, how do you share a button-press counter between a Cortex-M interrupt handler and the main loop using `critical_section::Mutex<RefCell<u32>>`?

level: middleimportance: must knowfreq 40%

basics

~20 s

Declare static PRESSES: Mutex<RefCell<u32>>; the handler and the main loop each enter critical_section::with(|cs| ...), which on a single-core Cortex-M disables interrupts, and borrow the counter with the cs token. Main reads and resets it with PRESSES.replace(cs, 0).

open as a page

Why does a Rust `#![no_std]` firmware binary need a `#[panic_handler]` and `#![no_main]`, while a `#![no_std]` library needs neither?

level: middleimportance: must knowfreq 32%

basics

~20 s

Without std, nothing handles panics or calls fn main. The final binary supplies exactly one #[panic_handler] fn(&PanicInfo) -> ! and uses #![no_main] so a runtime crate's entry function starts it. A library is never linked alone, so it leaves both to the binary.

open as a page

In Rust 2024 firmware, a `static mut PRESSES: u32` shared with a button interrupt compiles without warnings, yet the release build hangs; why, and what is the fix?

level: seniorimportance: must knowfreq 35%

basics

~20 s

Main and a preempting handler access it without synchronisation, a data race, so the optimiser loads PRESSES once and spins on that copy. Use a plain static PRESSES: AtomicU32: fetch_add in the handler, swap(0, ..) in main, or a critical section.

open as a page

In an svd2rust-generated peripheral access crate, how do a register's `write` and `modify` closures differ, and why are raw `bits()` writes `unsafe`?

level: middleimportance: should knowfreq 24%

basics

~20 s

write starts from the register's reset value, so unnamed fields are reset; modify reads the current value and changes only the named fields. Raw bits() is unsafe because the SVD file cannot prove every bit pattern is valid.

open as a page

In a Rust `#![no_std]` firmware binary, what must exist before `alloc::vec::Vec` links, and what happens when that allocator runs out of memory?

level: middleimportance: should knowfreq 26%

basics

~20 s

The binary needs exactly one #[global_allocator] static whose type implements GlobalAlloc, usually over a RAM region it owns. When alloc returns null, Vec calls handle_alloc_error; with no std in the program that panics and your #[panic_handler] runs.

open as a page

In Rust firmware with no heap, how does `heapless::Vec<T, N>` differ from `alloc::vec::Vec<T>`, and what does `push` do once it is full?

level: middleimportance: should knowfreq 24%

basics

~20 s

heapless::Vec<T, N> keeps its buffer inline with a capacity N fixed in the type, so it needs no allocator and never grows. push returns Result<(), T>: when full it returns Err(item), handing the value back.

open as a page

In Rust 1.99, which wasm32 targets suit a browser image filter and a WASI command-line tool, and why does `--target wasm32-wasi` fail?

level: middleimportance: should knowfreq 30%

basics

~20 s

Browsers use wasm32-unknown-unknown, which assumes no host APIs. WASI tools use wasm32-wasip1, a core module calling WASI preview 1, or wasm32-wasip2, a component (tier 2 since 1.82). The old wasm32-wasi name was removed in Rust 1.84.

open as a page

With Rust's wasm-bindgen, what is copied when JavaScript calls `label(filter_name: &str) -> String` and `blur_row(pixels: &mut [u8], kernel: &Kernel)`?

level: middleimportance: should knowfreq 32%

basics

~20 s

The string is re-encoded as UTF-8 into linear memory, the returned String is decoded into a new JavaScript string, and the pixels are copied in and back out. The #[wasm_bindgen] struct stays in wasm memory behind a handle.

open as a page

In a Rust crate using web-sys, why does `web_sys::window()?.document()` fail to compile until Cargo features are enabled, and how do js-sys and web-sys differ?

level: middleimportance: should knowfreq 25%

basics

~20 s

web-sys gates each Web API binding behind a Cargo feature named after its interface, so window() needs Window and Window::document also needs Document. js-sys binds JavaScript's built-ins, such as Array, Date and typed arrays; web-sys binds browser APIs.

open as a page

An embedded Rust flash driver on `embedded_hal::spi::SpiDevice` calls `write(&[0x9F])` then `read(&mut id)` and gets a wrong ID; why, and what fixes it?

level: seniorimportance: should knowfreq 19%

basics

~20 s

Each SpiDevice method is a complete transaction: it asserts chip-select, transfers, flushes and deasserts. The command and the read run under two separate selects, so the chip drops the command. Put both in one transaction with Operation::Write and Operation::Read.

open as a page

In a Rust HAL, why does turning a GPIO pin into an output consume the pin, and how does that make `set_high` on an input a compile error?

level: seniorimportance: should knowfreq 26%

basics

~20 s

HALs put a pin's mode in its type. The conversion takes self by value and returns the pin with its new mode, and OutputPin is implemented only for output modes, so set_high on an input pin does not compile.

open as a page

In Embassy firmware, how does a task wait for a button interrupt without polling, and which `embassy_sync` raw mutex must the shared `Signal` use?

level: seniorimportance: should knowfreq 24%

basics

~10 s

The task awaits PRESSED.wait(); the executor sleeps on WFE until the #[interrupt] handler calls PRESSED.signal(()), which wakes it. A Signal touched from a handler needs CriticalSectionRawMutex: ThreadModeRawMutex panics there and NoopRawMutex is not Sync.

open as a page

In an RTIC 2 app, how do `#[shared]` and `#[local]` resources, task priorities and `lock` stop a button task and the idle loop racing on a press counter?

level: seniorimportance: should knowfreq 25%

basics

~20 s

RTIC computes each shared resource's ceiling, the highest priority of any task using it; lock raises the system priority to that ceiling, so no task touching the counter can preempt. A #[local] resource belongs to one task and needs no lock.

open as a page

A Rust crc16 library with `#![cfg_attr(not(feature = "std"), no_std)]` builds with `--no-default-features` on a laptop yet fails for a thumbv7em-none-eabihf user; why, and how do you catch it?

level: seniorimportance: should knowfreq 20%

basics

~20 s

The laptop's sysroot has std, so a dependency that is not no_std links it silently. A target without std fails with E0463 naming that dependency, so CI must build the no-std feature sets for such a target.

open as a page

A Rust image filter's `.wasm` stays near 19 KB with `opt-level = "z"`, `lto` and `strip`, though its one export is a few lines; what is taking the space, and how do you shrink it?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Reachable panics: any unwrap() keeps std's panic runtime and core::fmt alive. Replacing two with let-else and unwrap_or cut a measured build from 19,281 to 1,131 bytes; panic = "abort" changed nothing, as wasm targets already abort. Then run wasm-opt.

open as a page

As a Rust firmware lead, how do you choose between bare interrupt handlers with critical sections, RTIC 2 and an Embassy async executor for a new product?

level: principalimportance: should knowfreq 22%

basics

~20 s

Choose by latency budget, I/O complexity and ecosystem. Bare handlers suit small firmware; RTIC 2 suits hard priorities, with hardware-scheduled tasks and compile-time lock ceilings; Embassy suits I/O-heavy products, with async drivers but cooperative scheduling within each executor.

open as a page

As maintainer of a widely used Rust checksum or parsing crate, how do you decide whether to support no_std and alloc-only users, and what does that commitment cost?

level: principalimportance: should knowfreq 16%

basics

~20 s

Support no_std when the crate is pure computation over borrowed data and firmware users depend on it, directly or through other crates. The cost is permanent: std and alloc feature tiers, no_std-capable dependencies, a heap-free core API and CI builds for a target without std.

open as a page

A Rust image filter built for `wasm32-unknown-unknown` splits work with `std::thread::spawn`; why does calling it end in a `RuntimeError: unreachable` trap, and what can you do instead?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

On wasm32-unknown-unknown std compiles but cannot create threads: thread::spawn panics, and since the target aborts on panic, the module executes unreachable with no message. thread::Builder::spawn returns an Unsupported error instead, which allows a single-threaded fallback.

open as a page