
Recall first from core, alloc, and heapless
- The core crate provides common types, traits, and operations without requiring a heap.
- The alloc crate supplies types such as Vec, String, and Box that use a global allocator when they need memory.
- A heapless container stores its buffer inline and reports a full buffer through its fallible methods.
GPIO and timing contracts
3 min readThe last lesson used core and heapless. This lesson answers how embedded-hal and the cortex-m and riscv crates drive real hardware.
The Linux SPI userspace documentation describes a problem that also matters in bare-metal firmware. A device can require chip select to stay asserted while the controller sends a command and then reads the reply. Separate Linux read and write calls deassert chip select between operations. The documented SPI_IOC_MESSAGE(N) interface can group the operations so they run together. The same requirement applies when a Rust driver uses a microcontroller's SPI peripheral. The driver needs an interface that can express the whole transaction, and the implementation needs to preserve its boundaries.
code that presents operations such as setting a pin or transferring bytes and performs those operations through a specific hardware interface is often shortened to HAL. The embedded-hal crate defines common Rust traits for those operations. A chip HAL can implement them using peripheral registers. On Linux, a userspace adapter can implement suitable traits through a kernel device interface. In either case, the application selects and configures the concrete object before passing it to the driver.
In embedded-hal 1.0, the GPIO traits live in embedded_hal::digital. InputPin gives you is_high and is_low to sample the input. OutputPin gives you set_high and set_low to request an output level. These methods return a Result because some implementations can fail. A pin on a GPIO expander, for instance, can require a bus transaction just to read a level. The concrete implementation supplies the error type, which generic driver code can propagate.
StatefulOutputPin extends OutputPin with is_set_high, is_set_low, and toggle. The state queries report the configured output state. An input reading, where supported, samples the electrical level. That distinction matters if an output releases a line and another device pulls it low. It also matters when reading old code. The embedded-hal 0.2 API had a separate ToggleableOutputPin trait. With 1.0, a generic function that calls toggle asks for StatefulOutputPin.
The time interface changed too. In 0.2, embedded_hal::blocking::delay::DelayUs expressed a blocking delay in microseconds. In 1.0, embedded_hal::delay::DelayNs defines delay_ns and provides delay_us and delay_ms methods. The contract is to delay for at least the requested duration. The implementation can round up to its available resolution, and an interrupt can extend the time before the caller resumes. A nanosecond argument therefore expresses a duration in a particular unit. The effective resolution still depends on the implementation and its clock.
use embedded_hal::{delay::DelayNs, digital::OutputPin};
pub fn pulse<P, D>(pin: &mut P, delay: &mut D, width_us: u32)
-> Result<(), P::Error>
where
P: OutputPin,
D: DelayNs,
{
pin.set_high()?;
delay.delay_us(width_us);
pin.set_low()
}
pulse needs only the ability to set an output high and low. It returns immediately if setting the output high reports an error. After a successful high request it waits, then returns the result of the low request. The requested width applies to the delay call. The call overhead and any interrupt or transport latency can affect the physical pulse. For a waveform with a strict timing tolerance, the application can use a hardware timer configured to drive an output directly.
The trait also leaves the board's signal polarity to its caller. An LED wired active-low lights at a low output level. The same set_low call could turn on one board's LED and turn off another board's LED. A function that promises to turn on an LED needs to know that wiring or receive a type that already expresses the intended polarity.
Bus transactions and byte streams
3 min readIn embedded_hal::i2c, the I2c trait provides read, write, write_read, and transaction. A typical register read first writes a register selector, then reads the register contents. If the device calls for a repeated start between those operations, use write_read with the device address, a slice containing the selector, and a mutable slice for the reply. For a nonempty write followed by a nonempty read, the combined operation changes direction with a repeated start before ending with a stop. Two separate calls to write and read have separate transaction boundaries. Linux expresses the combined operation through I2C_RDWR, as documented in the kernel's I2C userspace interface.
SPI distinguishes the controller's bus from an individual device. embedded_hal::spi::SpiBus exposes operations on the bus wires, including transfer and transfer_in_place. SpiDevice represents a device selected on a bus. Its transaction method groups operations under one chip-select assertion, and its convenience methods let you request an individual operation as a transaction. A driver that needs to issue a command and read the reply with chip select held uses one SpiDevice::transaction containing a write followed by a read. Two convenience calls represent two transactions. If other devices share the bus, the device implementation coordinates access so their operations do not interleave with the transaction.
The bus traits leave the electrical configuration with the application and HAL. The board setup chooses the SPI mode and clock rate required by the peripheral and configures the controller and pins. The device driver supplies the bytes in the order the peripheral expects. A correct trait bound gives a driver the operations it needs. Reading the peripheral documentation still tells you how to use them, including which command precedes a read and whether the device requires a delay.
For UART-style serial, older embedded-hal 0.2 code can use embedded_hal::serial::Read and Write. Those interfaces operate on individual words and can report WouldBlock when the peripheral cannot make progress immediately. embedded-hal 1.0 has no serial module. For a blocking byte-stream interface, use embedded_io::Read and embedded_io::Write with a UART implementation that supports them. Firmware still sets details such as baud rate and parity through the concrete UART interface. Code that needs peripheral-specific operations, such as changing the line configuration, needs an interface that exposes them.
A stream write can accept fewer bytes than the supplied buffer contains, and a stream read can return a short count. Use write_all when the operation needs to submit the entire slice, or read_exact when it needs to fill the entire buffer and should report an error if the stream ends early. flush is a separate operation for pending output. A protocol that needs to know when the physical UART has finished transmitting should consult the implementation's guarantees for that event. A timestamp taken as soon as write returns may only record when the implementation accepted bytes.
embedded-hal-async provides async peripheral traits, including I2c, SpiDevice, and DelayNs. It also provides digital::Wait for waiting on input levels or edges. Async byte streams use embedded_io_async::Read and embedded_io_async::Write. When an operation is pending, the executor can run another ready task. For example, a UART implementation might arrange for a receive interrupt to wake the task waiting for bytes. The trait defines the callable operation. The driver implementation, hardware setup, and executor determine when the task can yield and how it resumes.
CPU support, startup, and interrupts
3 min readOn Arm Cortex-M, the cortex-m crate exposes core facilities such as the SysTick timer and the Nested Vectored Interrupt Controller, or NVIC. Its API lets firmware work with CPU features that are common across Cortex-M chips. The device description supplies chip-specific details such as which interrupt line corresponds to a given UART. A UART HAL can implement a portable stream trait while using those chip-specific details internally to receive bytes.
cortex-m-rt supplies startup support, including a reset handler, vector table support, and the #[entry] attribute for identifying the Rust firmware entry function. It provides a linker script named link.x. A typical firmware build selects it with the linker argument -Tlink.x and supplies a memory.x file describing the target's FLASH and RAM regions. The linker uses that layout to place the program's sections. Startup initializes writable static data by copying the initial .data contents to RAM and zeroing .bss before calling the entry function. The memory description must match the actual image placement on the target.
For bare-metal RISC-V firmware, the corresponding crates are riscv and riscv-rt. The riscv crate provides access to architecture facilities, including control and status registers. The riscv-rt runtime provides startup code, trap entry support, and its own #[entry] attribute. Its linker setup likewise needs a memory layout for the platform and the way the image is loaded. Entry and startup details depend on the RISC-V target and the privilege mode in which the runtime is configured to execute.
During Cortex-M interrupt delivery, a peripheral such as a UART can assert its interrupt request when a receive condition occurs. The NVIC tracks pending requests and uses enable and priority settings to determine which external interrupt can run. When the core accepts one, it uses the corresponding vector table entry to reach the handler. The handler should service the receive condition or acknowledge it as the peripheral requires. If the source continues asserting its request, the interrupt can become pending again even if software clears the NVIC pending bit.
On RISC-V, a hart is a hardware thread that can take a trap. Timer, software, and external interrupts are different interrupt classes. Pending and enable state, privilege, and delegation affect whether the hart takes an interrupt and which privilege level handles it. Trap entry directs execution according to the trap-vector configuration for that level. The handler can inspect the trap cause to identify the interrupt class. For an external interrupt, identifying and acknowledging the particular device can also require platform-specific interrupt controller operations. A platform with a Platform-Level Interrupt Controller (PLIC), for example, uses its claim and completion operations in servicing external sources. The platform determines which controller is present.
These roles matter when moving code between a Linux board and a bare-metal target. A userspace program on a Raspberry Pi 4 or 5 can use an adapter backed by the Linux I2C or SPI device interface when the relevant kernel driver exposes it. Linux handles CPU interrupt delivery and program startup there. Cortex-M and bare-metal RISC-V runtime setup belongs to firmware built for the matching CPU and boot environment. The portable driver can keep its trait bounds whenever the new implementation supports the same operations and the attached device has the same protocol.
When reviewing a firmware design, identify who configures the physical device, who executes the trait method, and who handles a hardware event when the device needs attention. The next lesson, PACs, critical sections, and zero-cost abstractions, looks below those interfaces to answer how a HAL accesses registers and coordinates access when ordinary code and interrupt handlers use the same hardware.
Key takeaways
- embedded-hal traits specify operations that a concrete hardware implementation performs.
- In embedded-hal 1.0, StatefulOutputPin provides toggle and DelayNs provides delay_us.
- embedded-io defines blocking byte streams, and embedded-io-async defines their async counterparts.
- CPU support crates expose architecture facilities, while runtime crates supply startup and entry support.
Reflect
- Explain to a colleague, in two sentences: select an embedded-hal 1.0 trait for a GPIO, SPI, I2C, or delay operation.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Kernel documentationI2C device interface: userspace access and combined transactions
- Kernel documentationSPI userspace API: chip select and composite transfers
Official documentation first. Links checked when the lesson was published.