Memory Access through a structure

One of the more common things you do as an Embedded Systems programmer is accessing registers of different peripherals.

Rather than hardcoding the address to each and every register in a peripheral, I find it convenient to typedef a C-struct for easy access of these registers. Setup the struct with a layout identical to that of your hardware registers, assign a pointer to the structure to point at the (base)address of the hardware registers in question, and voila! Access each register as a regular element of the structure for read/write operations.

typedef struct {
volatile uint8_t STATUS;
volatile uint8_t TX_REG;
volatile uint8_t RX_REG;
} hw_device_t;

hw_device_t * const ptr = (hw_device_t *) 0xFF000000;

hw_device->RX_REG = 0x10;
hw_device->TX_REF = 0x03;
uint8_t current_status = hw_device->STATUS;

Note: all elements of structure should be made volatile to avoid compiler optimizations.

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *