Memory-mapped IO registers in zig

submited by
Style Pass
2024-04-23 11:00:05

Kevin Lynagh and I spent some time playing around with zig on nrf52 boards. He's written about the experience here. I wanted to additionally highlight the api we used for memory-mapped IO registers because it shows off some nice features of zig.

An MMIO register is just an address in memory where reads and writes are interpreted specially by the hardware. For example, on the nRF52833 board writing the value 0b11 to address 0x708 will set the 3rd GPIO pin to output mode and disconnect the input buffer.

The list of available registers is documented in a massive pdf for each board. The same information also exists in an accompanying xml file which we can use to generate a nice typed api. So the question is what do we want the api to look like?

It's important though that all reads and writes to the pointer happen in a single instruction so that the hardware doesn't see half a write. We also have to be careful that reads and writes are never optimized away by the compiler because it thinks that they don't affect the rest of the program. We can guarantee both of these with the volatile keyword.

Leave a Comment