liveBook · Manning

Typed register overlay

As explained in Embedded Software with Rust

A struct overlay represents a hardware register block as a typed structure whose fields correspond to registers at fixed memory offsets.

A typed register overlay models a memory-mapped peripheral as a struct whose named fields occupy the hardware registers’ fixed offsets. This replaces numeric offsets with fields that can match the hardware reference manual. section 5.2.4

The overlay makes register access clearer, but does not remove the need for care:

  • RO, WO, and RW wrappers distinguish read-only, write-only, and read-write fields, with access restrictions checked at compile time. section 5.2.4
  • Creating the register-block reference still requires unsafe pointer casts; the compiler cannot verify the address or that the struct layout matches the hardware. section 5.2.4
  • The wrappers do not validate bitfield meanings, reserved bits, or required write sequences. section 5.2.4
use volatile_register::{RW, RO, WO};

#[repr(C)]
struct GpioPort {
    crl:  RW<u32>, // 0x00
    crh:  RW<u32>, // 0x04
    idr:  RO<u32>, // 0x08
    odr:  RW<u32>, // 0x0C
    bsrr: WO<u32>, // 0x10
    brr:  WO<u32>, // 0x14
    lckr: RW<u32>, // 0x18
}

const GPIOA_BASE: usize = 0x4001_0800;
let gpioa = GPIOA_BASE as *const GpioPort;

unsafe {
    (*gpioa).odr.write(0x0000_0001);
}

This GPIO example uses a C-layout struct with typed fields at documented offsets, then writes the output register through an unsafe pointer. section 5.2.4

The pattern is a middle ground between raw MMIO and higher-level abstractions. Peripheral Access Crates can take it further by generating register blocks from SVD descriptions and providing typed field-level APIs. section 5.2.4 section 5.2.5

How Embedded Software with Rust covers it

How deep it goes
Explains volatile RO/WO/RW access and compile-time checks, but leaves address validity, layout matching, bitfields, reserved bits, and write sequences unchecked.
Examples
Uses a GPIO register block with RO, WO, and RW fields, then writes the output register through an unsafe pointer.
What you can do after
Apply the pattern via volatile_register wrappers to access named GPIO registers while retaining explicit unsafe pointer casts.
How it connects
Connects MMIO and volatile access to Peripheral Access Crates (PACs) and Hardware Abstraction Layers (HALs).

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.