liveBook · Manning

Peripheral

As explained in Embedded Software with Rust

A peripheral is a hardware component connected to a processor that provides a specialized input, output, communication, timing, or control function.

A peripheral is a hardware resource that provides a specialized function, such as timing, serial communication, or GPIO control. On a microcontroller, its registers may be memory-mapped: ordinary loads and stores access fixed addresses, but those operations can trigger hardware side effects. section 1.4.1 section 5.1

In Rust, an owning peripheral handle gives one part of the program control over the device. Move it into the module that configures and drives the peripheral; borrow it temporarily when helpers need access. The compiler prevents overlapping shared and mutable access, helping avoid competing pointers to the same registers. section 1.4.1

Practical access patterns include:

  • Use volatile access or register wrappers for MMIO, and isolate raw pointer operations behind small, audited APIs. section 5.6
  • Prefer PACs for typed, device-specific registers and HALs for drivers that use portable embedded-hal traits. section 5.6
  • When main code and interrupt handlers must share a peripheral, protect access with a synchronization design and critical sections. section 4.6.5
use cortex_m::interrupt::{Mutex, free};
use core::cell::RefCell;
use cortex_m::peripheral::SYST;
use core::ops::DerefMut;

static G_SYST: Mutex<RefCell<Option<SYST>>> = Mutex::new(RefCell::new(None));

fn main() -> ! {
    let dp = cortex_m::Peripherals::take().unwrap();

    // Transfer ownership into the static global using .replace()
    in a critical section
    free(|cs| {
        G_SYST.borrow(cs).replace(Some(dp.SYST));
    });

    loop {
        cortex_m::asm::wfi();
    }
}

#[exception]
fn SysTick() {
    free(|cs| {
        if let Some(ref mut syst) = G_SYST.borrow(cs).borrow_mut()
        .deref_mut() {
            let _ = syst.has_wrapped();
        }
    });
}

The example moves SysTick into mutex-protected static storage inside a critical section, then accesses it mutably from the interrupt handler. section 4.6.5

How Embedded Software with Rust covers it

How deep it goes
Explains ownership, borrowing, MMIO side effects, and access patterns, without detailing a specific device's complete register map.
Examples
Uses timers, UART, GPIO, and SysTick, including a peripheral shared between main code and an interrupt handler.
What you can do after
Apply peripherals through safe drivers and HAL-based abstractions, and share them safely between main code and interrupt handlers.
How it connects
Connects peripherals to Rust ownership, borrowing, memory-mapped I/O, PACs, and hardware abstraction layers.

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.