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
