Embedded Systems & Firmware

When the program above is compiled with optimization, led_on() may never be called even after the timer interrupt fires. Which pairs the cause with the fix correctly?

int flag = 0;
void timer_isr(void) { flag = 1; }
int main(void) {
    while (flag == 0) { }
    led_on();
}
  1. AThe compiler reads flag only once and never rereads it in the loop; declare flag volatile
  2. BThe interrupt resets flag to 0; make flag a long
  3. CAn empty loop halts the CPU; put an addition inside the loop
Show answer and explanation

Answer: A. The compiler reads flag only once and never rereads it in the loop; declare flag volatile

Looking only at main, the compiler may conclude that nothing in the loop changes flag, load it into a register once and spin on that value. Even when the interrupt handler updates flag in memory, the loop never sees it. Declaring it volatile makes every access read from or write to memory. For multi-byte variables, additional measures are needed to keep accesses from being interrupted midway.

  • A. Correct. It tells the compiler to reread memory every time.
  • B. The handler writes 1, and the type is not the cause.
  • C. An empty loop does not halt the CPU.
Practice this topic Back to topic

More Embedded Systems & Firmware questions

  1. 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?
  2. What is a characteristic of serial communication with a UART?
  3. On a 115200 bps UART using 8 data bits, no parity and 1 stop bit (8N1), roughly how many bytes can be sent per second?
  4. A small baud-rate mismatch between UART transmitter and receiver can garble characters. Why is the tolerance limited to roughly a few percent?
  5. What is a characteristic of SPI communication?