Embedded Systems & Firmware
While the main code updates a register bit with "reg |= mask;" (read-modify-write), an interrupt handler changes a different bit of the same register. Which pairs the possible problem with a fix correctly?
- AThe handler's change is lost when main writes back; disable interrupts during the update or use dedicated per-bit set/clear registers
- BThe register is permanently damaged; replace the microcontroller
- CNothing happens; no fix is needed
Show answer and explanation
Answer: A. The handler's change is lost when main writes back; disable interrupts during the update or use dedicated per-bit set/clear registers
"reg |= mask" is three operations: read the register, OR, and write back. If an interrupt arrives right after the read and the handler changes another bit, main writes back a value based on the stale read, wiping out the handler's change. Disabling interrupts during the operation, or using set and clear registers where only the bits written as 1 change, makes it a single write and avoids the problem.
- A. Correct. The cause is an interrupt between the read and the write.
- B. The hardware is not damaged; only a value is lost.
- C. A value can be lost.