Embedded Systems & Firmware
On an 8-bit microcontroller, a timer interrupt increments the 32-bit variable ticks, and the main code reads ticks to compute elapsed time. Why is a wildly wrong value occasionally read?
- A8-bit microcontrollers cannot use 32-bit variables
- BThe timer interrupt period changes randomly every time
- CThe 32-bit read takes four separate byte accesses, and an interrupt in between can leave some bytes old and some new
Show answer and explanation
Answer: C. The 32-bit read takes four separate byte accesses, and an interrupt in between can leave some bytes old and some new
An 8-bit microcontroller reads one byte at a time, so a 32-bit value takes four reads. If, as the value changes from 0x000000FF to 0x00000100, an interrupt arrives after the low byte has been read, the result combines the old low byte (0xFF) with the new upper byte (0x01), giving something like 0x000001FF. It is prevented by disabling interrupts during the read, or by reading twice until two consecutive reads match.
- A. They can be used, but not read in one access.
- B. The period is constant.
- C. Correct. Disabling interrupts during the read prevents it.