Consider this embedded C code simulating writing to a hardware register. What value will be stored in REG after execution?
volatile unsigned int REG = 0x00; void write_register(unsigned int value) { REG = value | 0x0F; } int main() { write_register(0xF0); return REG; }
Remember the bitwise OR operation sets bits that are set in either operand.
The function write_register sets REG to the bitwise OR of value and 0x0F. Since value is 0xF0, OR with 0x0F results in 0xFF.
Why is the volatile keyword important when declaring hardware registers in embedded C?
Think about how hardware registers can change outside program control.
The volatile keyword prevents the compiler from optimizing away reads or writes to the variable, because the value can change at any time due to hardware events.
Examine the code below. It attempts to write to a hardware register but causes a runtime error. What is the cause?
unsigned int *REG = NULL; void write_register(unsigned int value) { *REG = value; } int main() { write_register(0xAA); return 0; }
Check the pointer initialization before dereferencing.
The pointer REG is initialized to NULL. Dereferencing it to write causes a runtime crash (segmentation fault).
Choose the correct C code snippet to write the value 0x55 to a hardware register located at memory address 0x4000.
Remember how to cast an address to a pointer and write through it.
Option A correctly casts the address to a volatile pointer and dereferences it to assign the value.
Given the following code, how many bits are set to 1 in the REG after execution?
volatile unsigned char REG = 0x00; void set_bits(unsigned char mask) { REG |= mask; } int main() { set_bits(0x0F); // sets lower 4 bits set_bits(0x33); // sets bits 0,1,4,5 return 0; }
Count the bits set after both OR operations.
After first call, REG = 0x0F (bits 0-3 set). After second call, REG |= 0x33 sets bits 0,1,4,5. Combined bits set are 0,1,2,3,4,5 = 6 bits.