IAE Academy

FOR CORE AND IT JOBS · CHAPTER 4 OF 7

Interrupts and program structure

This chapter explains how a microcontroller reacts to events without wasting time asking about them. You learn what an interrupt does, how to write a service routine that shares data safely, how a timer tick drives a simple task loop, and why a watchdog is fed only by healthy code.

Updated 30 Oct 2026

What you will be able to do

You will compare polling with interrupts and trace what the processor does from request to return. You will write a short routine that shares data safely and work out its latency and load. You will build a timer-driven task loop that fits its tick and set a watchdog that catches a hang.

Before you start

  1. Chapter 3, GPIO, timers and PWM (compare match, the periodic tick)

  2. A processor's registers, program counter and stack (push and pop)

  3. Short C programs with global variables; a compiler turns each statement, even x++, into one or more machine instructions

  4. Hexadecimal such as 0x00FF; a byte is 8 bits

  5. Time from clock cycles:

  6. Percentages, remainder on division (modulo), sums with

Polling, interrupts and what happens on one

Polling means the program asks again and again whether an event has happened. Each check costs time, event or not, and an event can wait a whole polling period. With an interrupt, the hardware raises a request; the processor leaves its work, runs a short routine for the event and returns. You pay only when events happen.

COST AND DELAY OF POLLING

Holds when a check starts every and nothing else delays it; worst case, the event comes just after a check. : fraction of processor time spent checking; : one check (s); : time between checks (s); : handling (s); : response time, event to end of handling (s), used throughout this chapter.

On an interrupt, a typical microcontroller does the following, in order. The vector table, a fixed area of memory, holds each source's routine address or a jump to it.

  1. The peripheral sets its request flag, a bit in one of its registers. If the source and interrupts as a whole are enabled, the processor finishes the current instruction.

  2. Hardware pushes the return address on the stack; some processors also push the status register (condition bits such as carry and zero) and a few working registers. It then blocks further interrupts: all, or those of equal or lower priority, depending on the processor.

  3. The program counter is loaded from this source's vector table entry. This jump is vectoring.

  4. The prologue saves the registers the routine will change that hardware did not save: the context.

  5. The body does the work for the event.

  6. The epilogue restores the context. A return-from-interrupt instruction pops what hardware pushed, unblocks interrupts and resumes the main program.

INTERRUPT LATENCY

Holds when interrupts are enabled and no routine of equal or higher priority runs; otherwise add the blocked time. : request to the body's first instruction (s); : worst-case cycles to finish the current instruction; : hardware save and vector cycles; : prologue cycles; : clock (Hz).

PROCESSOR LOAD OF AN INTERRUPT

Holds when each routine ends before the next event: . : events per second (Hz); : time per event, hardware save to return (s). The main program keeps .

WORKED EXAMPLE

An 8 MHz microcontroller takes an interrupt 2,000 times per second. Finishing the current instruction takes at most 4 cycles, hardware save and vector 8, the prologue 8, the body 128 and the epilogue with return 16. Find the latency, the response time and the processor load. Compare with polling every 100 µs, each check costing 2 µs, where handling takes the same 128 cycles as the body.

Solution
  1. One cycle is µs. Latency counts the cycles before the body: , so µs.

  2. The event is handled when the body ends, so response is latency plus body: µs. The epilogue and return come after the event has been handled.

  3. Load counts the cycles taken from the main program, save to return: cycles µs. The 4 finishing cycles are the main program's own work, so they are left out.

  4. : 4 %, so the main program keeps 96 %.

  5. Polling: %, lower, but paid even when nothing happens. With µs, response can reach µs.

Answer: Latency 2.5 µs, response 18.5 µs, interrupt load 4 %. Polling costs 2 % but its response can reach 118 µs.

Writing a safe interrupt routine

An interrupt routine steals time from everything else, so keep it short: record the event, clear the request flag if hardware does not clear it on entry, and leave. Slow work goes to the main program. The two share variables, which brings two hazards: the compiler may keep a stale copy, and an access may be split in the middle.

Shared flag in C:

#include <stdint.h>

volatile uint8_t tick_flag = 0;
void do_work(void);

/* tied to the timer's vector in a compiler-specific way */
void timer_isr(void) { tick_flag = 1; }

int main(void) {
    for (;;) {
        if (tick_flag) { tick_flag = 0; do_work(); }
    }
}

If nothing in the loop changes a variable, the compiler may keep it in a register. volatile forces a fresh read on every test. Clearing the flag before do_work() catches a tick during the work on the next pass. Two ticks before the clear merge into one; to count every tick, the routine adds 1 to a counter instead.

volatile does not fix the second hazard. An 8-bit microcontroller moves 8 bits per instruction, so reading a 16-bit counter takes two instructions, and the routine can run between them. Say the counter holds 0x00FF when the main program starts to read it.

Step

Who acts

Counter after the step

Main program holds

1

main reads high byte

0x00FF

high = 0x00

2

routine adds 1

0x0100

high = 0x00

3

main reads low byte

0x0100

low = 0x00

Main assembles 0x0000, a value the counter never had. The cure is a critical section: block interrupts, copy the variable, then restore interrupts as they were. Keep it short, because it delays every other interrupt.

When several sources request at once, priorities set the order. With nesting enabled, a higher-priority request may interrupt a running lower-priority routine; an equal or lower one waits until that routine returns. Each level pushes another context and its local variables, so the deepest nesting plus the main program's stack use must fit in the stack.

WORST RESPONSE OF ONE INTERRUPT SOURCE

Holds when each source in , the higher-priority sources, fires at most once meanwhile; the sum is an upper bound, safe where terms overlap. : latency of (s); : longest time is held off by a critical section or a running routine it cannot interrupt (s); : routine , save to return (s); : body of (s).

WATCH OUT FOR

Believing volatile makes a shared variable safe. It only stops the stale copy. Test: read the compiled code; if a shared read, write or update such as x++ takes more than one instruction, wrap it in a critical section.

Program structure and the watchdog

After setup, a super-loop calls each job in turn, forever, so a polled event waits at most one pass: every job at its worst-case run time, plus interrupt time. A cooperative scheduler adds a timer tick: the tick routine only sets a flag or counts ticks, and the main loop runs each task whose period has elapsed. A task must return quickly, because no other task runs until it does; only interrupts can break in.

TICK PERIOD

For a timer counting 0 to and restarting on compare match (Chapter 3). : prescaler; : compare value; : clock (Hz); : tick (s). A task of period runs every ticks ( whole), on ticks with modulo equal to its offset (0 to ).

A TICK MUST HOLD ITS TASKS

Needed on every tick; leave room for interrupt time if it is large. : tasks released on that tick; : their run times (s). If it fails, the next tick's tasks start late, and a tick that only sets a flag can be lost.

WORKED EXAMPLE

A tick comes from an 8 MHz clock, prescaler 64, compare value 124. Task 1 (0.2 ms) runs every 10 ms, task 2 (0.5 ms) every 50 ms, task 3 (0.4 ms) every 100 ms, all with offset 0. Ignore interrupt time. Does every tick hold its tasks? If not, fix it.

Solution
  1. s ms, so tasks 1, 2 and 3 run every 10, 50 and 100 ticks.

  2. Every 100th tick is a multiple of 10 and 50, so all three run: ms, over the 1 ms tick by 0.1 ms.

  3. Give task 3 an offset of 1 tick. Ticks are not multiples of 10, so only task 3 runs there: 0.4 ms.

  4. The other ticks run tasks 1 and 2 (0.7 ms) or task 1 alone (0.2 ms), all within 1 ms.

Answer: Not as first set (1.1 ms in a 1 ms tick). With task 3 offset by one tick the worst tick is 0.7 ms.

A watchdog is a counter, usually on its own clock, that resets the processor at its limit unless the program restarts (feeds) it first, so a hang ends in a reset. Feed it in one place in the main loop: each task sets its own flag when it completes, and the loop feeds and clears all flags once every one is set. A feed in the tick routine proves nothing: that routine keeps running while the main loop is stuck, as long as interrupts stay enabled.

WATCHDOG TIMEOUT

Holds when each feed restarts the count from 0. : count that triggers the reset; : watchdog clock (Hz); : timeout (s); : longest healthy gap between feeds (s), a little over the slowest task's period. The watchdog clock is often inaccurate, so check the margin at the fastest rate it can run (the shortest timeout).

Check yourself

CHECK YOURSELF 1

A program waits with while(!flag); and an interrupt routine sets flag. The flag is declared without volatile and the loop never ends, although the routine ran. What is the most likely cause?

  1. (A)

    The compiler read the flag once into a register and never read memory again

  2. (B)

    A routine cannot write to a global variable

  3. (C)

    A flag must be stored in program memory

  4. (D)

    Interrupts are turned off while a loop runs

Answer and solution

Answer: (A)

  1. Nothing in the loop changes flag, so the compiler may keep it in a register.

  2. The routine writes memory, but the loop never reads memory again; volatile would force a fresh read.

  3. B, C and D are false statements.

CHECK YOURSELF 2One or more options are correct

Which are good practice for an interrupt service routine?

  1. (A)

    Set a flag, clear the request flag if the hardware does not, and leave the slow work to the main loop

  2. (B)

    Wait inside the routine with a delay loop until a button is released

  3. (C)

    Keep its run time far below the shortest gap between events

  4. (D)

    Send a long text string through a blocking serial call

Answer and solution

Answer: (A), (C)

  1. A keeps the routine short.

  2. C keeps the load small and avoids missed events.

  3. B and D hold the processor for a long time and delay every other interrupt.

CHECK YOURSELF 3

A 4 MHz microcontroller needs at most 6 cycles to finish the current instruction, 8 cycles for hardware save and vector, and 12 cycles for the prologue. Interrupts are enabled and no other routine is running. Find the interrupt latency in microseconds.

Answer and solution

Answer: (accepted range )

  1. Total cycles: .

  2. One cycle at 4 MHz is 0.25 µs.

  3. µs.

CHECK YOURSELF 4

An interrupt arrives 5,000 times per second and each one takes 40 µs from hardware save to return. No other interrupt runs. What percentage of processor time is left for the main program?

Answer and solution

Answer: (accepted range )

  1. .

  2. The main program keeps , that is 80 %.

Used in these GATE topics