Memory-mapped I/O (MMIO) exposes hardware registers at addresses in the processor’s memory map. The processor uses ordinary loads and stores to access them, but these are not ordinary RAM locations: a write can start a timer or change a GPIO pin, and a read can return a status flag or counter value. section 5.1
On Cortex-M, device peripherals typically occupy 0x4000_0000–0x5FFF_FFFF. Each peripheral has a documented base address and registers at fixed offsets; exact addresses depend on the microcontroller. Core components such as NVIC and SysTick also have memory-mapped registers in the System region. Many core registers require privileged access. section 5.1
Writing a GPIO register
On an STM32F1, GPIOA starts at 0x4001_0800 and its output data register is at 0x4001_080C. A Rust program can represent the register as a `*mut u32` and use `unsafe { core::ptr::write_volatile(GPIOA_ODR, 1) }`. The address must be valid, accessible, aligned, and appropriate for a 32-bit register. Writing 1 replaces the entire register value, so it may disturb other pins; an atomic set/reset register or a suitable read-modify-write pattern may be preferable. section 5.1 section 5.2.2 section 5.6
const GPIOA_ODR: *mut u32 = 0x4001_080C as *mut u32;
// More code
unsafe {
*GPIOA_ODR = 0x0000_0001;
}
This direct pointer write illustrates the address and register width, but plain dereferencing is not guaranteed to perform a volatile MMIO access. Use an explicit volatile operation instead. section 5.2.2
Use `read_volatile` and `write_volatile`, or an API that performs volatile accesses internally, so the compiler does not treat register operations like ordinary memory accesses. Hardware-visible ordering or processor context changes can also require barriers such as DMB, DSB, or ISB; volatile access is not a substitute for choosing the required barrier. section 5.2.2 section 5.6
Choose the access level that fits the firmware:
- Keep raw pointer operations in small, audited APIs when direct access is needed. section 5.6
- Prefer a peripheral access crate (PAC) for typed, device-specific register access. section 5.6
- Use a hardware abstraction layer (HAL) implementing embedded-hal traits when drivers should be portable across device families. section 5.6
