We write to hardware registers to control devices like LEDs, motors, or sensors directly from our program.
0
0
Writing to a hardware register in Embedded C
Introduction
Turning an LED on or off by changing its control register.
Setting the speed of a motor by writing to its speed register.
Configuring a sensor by writing settings to its control register.
Starting or stopping a hardware timer by writing to its control register.
Syntax
Embedded C
*(volatile uint32_t *)REGISTER_ADDRESS = VALUE;
REGISTER_ADDRESS is the memory address of the hardware register.
volatile tells the compiler the value can change anytime outside the program.
Examples
Write the value 0x01 to the hardware register at address 0x40021018.
Embedded C
*(volatile uint32_t *)0x40021018 = 0x01;
Define a name for the register and write 0xFF to it.
Embedded C
#define LED_REG (*(volatile uint32_t *)0x50000000) LED_REG = 0xFF;
Sample Program
This program writes the value 1 to the LED register to turn it on.
Embedded C
#include <stdint.h> #define LED_REGISTER (*(volatile uint32_t *)0x50000000) int main() { // Turn on the LED by writing 1 to the register LED_REGISTER = 1; // Normally embedded programs run forever, but here we just return return 0; }
OutputSuccess
Important Notes
Always use volatile when accessing hardware registers to prevent unwanted compiler optimizations.
Be careful with the register address; writing to the wrong address can cause unexpected behavior.
Hardware registers often require specific values or bit patterns; check the device manual.
Summary
Writing to hardware registers lets your program control physical devices.
Use pointers with volatile to access registers safely.
Always check the correct address and value before writing.