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?

  1. AThe handler's change is lost when main writes back; disable interrupts during the update or use dedicated per-bit set/clear registers
  2. BThe register is permanently damaged; replace the microcontroller
  3. 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.
Practice this topic Back to topic

More Embedded Systems & Firmware questions

  1. A switch alone is connected to a microcontroller input pin, with no pull-up or pull-down resistor. What can happen while the switch is open?
  2. When using a microcontroller GPIO (general-purpose input/output) pin, what must be configured first?
  3. What is the phenomenon called in which a mechanical switch's contacts bounce, turning on and off many times in a short period when pressed?
  4. Which is the most suitable way to remove switch bounce in software?
  5. A timer counts a 16 MHz clock divided by 16 with a prescaler and raises an interrupt every 1000 counts. What is the interrupt interval?