`core::ptr::write_volatile` writes a value through a raw pointer using volatile semantics. It makes the compiler preserve the store, which matters for memory-mapped I/O: a write to a hardware register can have an effect even when the program never reads the value back. Ordinary pointer dereferencing does not inherently make the access volatile. section 5.2.3 section 5.2.5
use core::ptr;
const SYST_CSR: *mut u32 = 0xE000_E010 as *mut u32; // Control & Status
const SYST_RVR: *mut u32 = 0xE000_E014 as *mut u32; // Reload
const SYST_CVR: *mut u32 = 0xE000_E018 as *mut u32; // Current
unsafe {
// example: max reload (24-bit field)
ptr::write_volatile(SYST_RVR, 0x00FF_FFFF);
// writing any value to CVR clears the counter and COUNTFLAG
ptr::write_volatile(SYST_CVR, 0);
// ENABLE (bit0) | TICKINT (bit1) | CLKSOURCE=Core (bit2)
ptr::write_volatile(SYST_CSR, 0x0000_0007);
}
This SysTick setup writes the reload value, clears the current counter, and enables the timer. Each register access uses a raw address and an explicit volatile store inside an `unsafe` block. section 5.2.5
The value and access pattern must match the register’s behavior. For example, the NVIC interrupt set-enable register is write-one-to-set: write a 1 to the desired bit rather than using a read-modify-write sequence. section 5.2.5
use core::ptr;
const NVIC_ISER0: *mut u32 = 0xE000_E100 as *mut u32;
unsafe {
ptr::write_volatile(NVIC_ISER0, 1 << 6); // enable IRQ #6
}
A single volatile write enables interrupt line 6. section 5.2.5
When a location is represented by `static mut` rather than a constant raw pointer, obtain its address with `addr_of_mut!` for a write. In the Rust 2024 edition, forming a reference to `static mut`, even temporarily, is a compile error. section 5.2.3
use core::ptr::{addr_of, addr_of_mut, read_volatile, write_volatile};
static mut DEVICE_REGISTER: u32 = 0;
fn write_device_register(val: u32) {
unsafe { write_volatile(addr_of_mut!(DEVICE_REGISTER), val) };
}
fn read_device_register() -> u32 {
unsafe { read_volatile(addr_of!(DEVICE_REGISTER)) }
}
The write and read helpers obtain raw addresses without first creating references to the mutable static. section 5.2.3
Volatile is a compiler-level guarantee, not a hardware ordering or completion guarantee. It does not ensure that CPU or DMA accesses are observed in the intended order, complete buffered writes, or perform cache maintenance. Use an appropriate architectural barrier when the wider system requires ordering or completion: DMB enforces memory-access ordering, while DSB waits for outstanding memory operations to complete. section 5.2.3 section 5.6
Keep raw-pointer operations behind small, audited APIs. For higher-level register access, volatile wrapper types or device-specific PACs can make intent clearer and reduce direct manipulation of addresses and bit patterns. section 5.2.5 section 5.6
