Skip to content
Tactiverge

Interrupts and event-driven code

How interrupts let a microcontroller react to events the moment they happen, why handlers must be short, and how volatile and critical sections keep shared variables safe.

Lesson 5 of 6 · 30 min · Self-paced · Free

Don't miss the moment

A wheel encoder on a mobile robot produces a pulse every time the wheel turns a small fraction of a revolution. At speed, pulses can arrive thousands of times per second, and missing even a few means the robot loses track of how far it has travelled. Meanwhile, the main program is busy computing, talking to other chips and updating motors. How can it catch every pulse without staring at the pin continuously? The answer is the interrupt.

Polling versus interrupts

There are two ways to notice an event.

Polling means checking repeatedly: "is the pin low yet? Is it low yet?" It is simple and perfectly fine when the loop is fast and events are slow. But if the loop sometimes takes 20 ms and a pulse lasts 1 ms, you will miss pulses.

Interrupts reverse the arrangement. You tell the hardware, "when this pin goes from high to low, interrupt me." The CPU carries on with normal work, and when the event happens, the hardware forces it to pause and run a special function, the interrupt service routine (ISR) or handler. Think of waiting for a parcel: polling is opening the front door every minute; an interrupt is a doorbell.

Many peripherals can raise interrupts: a pin changing level, a timer reaching its compare value, a byte arriving over a serial link, or an analog-to-digital conversion finishing.

What happens when an interrupt fires

  1. The event sets a flag inside the peripheral.
  2. If that interrupt is enabled, the CPU finishes its current instruction.
  3. It saves enough of its state (where it was in the program and some registers) to resume later.
  4. It looks up the handler's address in the vector table, a list in flash with one entry per interrupt source.
  5. It runs the handler.
  6. When the handler returns, the CPU restores its saved state and carries on exactly where it left off. The main program never notices, except that time has passed.

The delay between the event and the start of the handler is the interrupt latency, typically a handful to a few dozen clock cycles plus any time spent waiting for another handler to finish. Chips usually let you give interrupts priorities, so an urgent one can be handled first.

Rule one: keep handlers short

While a handler runs, the main program is frozen, and often other interrupts must wait too. A slow handler delays everything. So handlers should do the minimum: record that something happened, grab a timestamp, copy a received byte into a buffer, increment a counter. Then return.

Never put a delay_ms, a long calculation or a print statement inside a handler. Printing over a serial link can take milliseconds, during which further events may be lost. The common pattern is: the handler sets a flag; the main loop sees the flag and does the slow work.

Rule two: mark shared variables volatile

Here is a subtle bug. The handler sets a variable press_flag = 1. The main loop checks if (press_flag) over and over. An optimising compiler, looking only at the main loop, sees that nothing in the loop changes press_flag. It may load the value into a CPU register once and keep checking the register, never reading memory again. The handler's change is invisible and the loop never responds.

The keyword volatile tells the compiler: "this variable can change in ways you cannot see; read and write the real memory every time." Every variable shared between a handler and the main program should be volatile. Hardware registers are declared volatile for the same reason.

Rule three: protect multi-byte data

volatile is necessary, but not sufficient. On an 8-bit microcontroller, reading a 32-bit counter takes several instructions, one byte at a time. If the interrupt fires halfway through, you can read a value that never existed.

Worked example: a torn read

A 16-bit counter on an 8-bit chip holds 255, which is 0x00FF in hexadecimal: high byte 0x00, low byte 0xFF.

  1. The main program reads the low byte: 0xFF.
  2. An interrupt fires and increments the counter to 256, which is 0x0100.
  3. The main program reads the high byte: 0x01.

It combines them into 0x01FF, which is 511. The true value was 255 a moment ago and 256 now; 511 was never correct. This kind of bug is rare, perhaps one read in thousands, which makes it maddening to track down.

The fix is a critical section: briefly disable interrupts, copy the value, re-enable them. Any interrupt that arrives in that window waits a few cycles and then runs normally.

Putting it together

The code below is illustrative: attach_pin_interrupt, interrupts_disable, interrupts_enable, gpio_set_mode and handle_press stand in for your board's library and your own code. Real libraries name these differently, but the shape is the same.

/* Illustrative only: these functions stand in for your board's library. */
#define BUTTON_PIN 2

volatile uint8_t  press_flag = 0;   /* set by the handler, cleared by main */
volatile uint32_t press_count = 0;  /* 32 bits: may take several instructions to read */

void on_button_falling(void) {      /* the interrupt handler: short and quick */
    press_count++;
    press_flag = 1;
}

int main(void) {
    gpio_set_mode(BUTTON_PIN, GPIO_INPUT_PULLUP);
    attach_pin_interrupt(BUTTON_PIN, EDGE_FALLING, on_button_falling);

    while (1) {
        if (press_flag) {
            interrupts_disable();       /* start of critical section */
            press_flag = 0;
            uint32_t n = press_count;   /* copy safely, all 4 bytes at once */
            interrupts_enable();        /* end of critical section */

            handle_press(n);            /* slow work happens here, not in the handler */
        }
    }
}

Notice how all three rules appear: the handler is two lines long, both shared variables are volatile, and the main loop copies the multi-byte counter inside a critical section. Keep critical sections as short as the handlers themselves, because while interrupts are off, nothing else can respond.

One warning connects to the previous lesson: a bouncing button generates several edges per press, so an interrupt on a raw button pin fires several times. Debounce in hardware, or use the interrupt only to wake the main loop and debounce there.

Recap

Interrupts let hardware events pause the main program and run a handler, so nothing is missed while the CPU is busy. Keep handlers short: set a flag, record data, return. Declare every shared variable volatile so the compiler always reads real memory. Protect multi-byte shared data with a brief critical section, because volatile does not make a read happen all at once.

Project

Paper trace: find the lost update

Draw a timeline with two rows, main and handler. The handler does count = count + 1. The main program does count = count - 5 (it has just processed five events). On this chip, each of those lines compiles into three steps: load count into a register, change the register, store it back.

  1. Start with count = 10. Trace the case where the handler fires between main's load and main's store. What is the final value? What should it be?
  2. Find a second interleaving that gives a different wrong answer, or explain why there is none.
  3. Rewrite main's line using a critical section, and show on your timeline that the problem disappears.

No hardware is needed for this activity.

Deliverables

  • A labelled two-row timeline for the faulty interleaving and its final value
  • Your answer to question 2 with reasoning
  • The corrected code and a timeline showing it working

Knowledge check

Check your understanding

  1. 1. Which of these belongs inside an interrupt handler?
  2. 2. Why must a variable shared between a handler and the main loop be declared volatile?
  3. 3. An 8-bit chip reads a 16-bit counter one byte at a time. The counter is 0x00FF, and an interrupt increments it between reading the low and high bytes. What value is assembled?
  4. 4. When is simple polling a perfectly reasonable choice?

Go further