Try Embedded

Interrupts, timing and concurrency

How interrupts work on a Cortex-M, priorities, latency, races, rollover-safe time, non-blocking code and debouncing.

What an interrupt is

An interrupt is the hardware's way of saying "something happened, now". The CPU finishes the current instruction, saves enough state to resume, and jumps to the handler (the ISR, interrupt service routine) for that source. When the handler returns, the interrupted code continues as if nothing happened.

The alternative is polling: checking a status flag in a loop. Polling is simple and fine for slow things, but it wastes CPU time and its reaction time depends on how long the rest of the loop takes. Interrupts give a bounded, short reaction time.

What the Cortex-M does on entry

  1. The peripheral sets a pending flag in the NVIC (Nested Vectored Interrupt Controller).
  2. If the interrupt is enabled and its priority is higher than whatever is running, the core stacks eight registers (R0 to R3, R12, LR, PC, xPSR) automatically, plus the FPU registers if needed (often lazily).
  3. It loads the handler's address from the vector table and jumps, with LR set to a special EXC_RETURN value.
  4. The handler is an ordinary C function. Returning to EXC_RETURN makes the core unstack and resume.

Because the hardware saves the caller-saved registers, an ISR on Cortex-M needs no special keyword. Entry takes 12 cycles on Cortex-M3/M4 with zero-wait-state memory.

Two optimisations follow from the automatic stacking:

  • Tail-chaining: if another interrupt is pending when one handler returns, the core skips the unstack/restack and goes straight to the next handler (6 cycles).
  • Late arrival: if a higher-priority interrupt arrives during stacking, it takes the slot and runs first.

Priorities and nesting

Each interrupt has a priority number. Lower number means higher priority. A higher-priority interrupt can preempt a running lower-priority handler: that is nesting.

The NVIC implements only the top few bits of the 8-bit priority field: 4 bits on most STM32s (Cortex-M3, M4, M7, M33), so 16 levels, written as n << 4, and 2 bits (4 levels, n << 6) on the Cortex-M0 and M0+ parts such as the STM32F0, G0 and L0. On Cortex-M3 and up the bits can be split into:

  • group (preemption) priority: decides whether one interrupt can interrupt another
  • subpriority: only breaks ties between pending interrupts of the same group priority; it never causes preemption

The Cortex-M0 and M0+ have no such split: every priority bit is a preemption priority.

SituationResult
A (priority 1) arrives while B (priority 3) runsA preempts B
A (priority 3) arrives while B (priority 1) runsA waits until B returns
Two pending with equal group priorityLower subpriority, then lower IRQ number, goes first

Masking registers:

  • PRIMASK (__disable_irq()): blocks all configurable interrupts.
  • BASEPRI (Cortex-M3 and up; the M0 and M0+ have only PRIMASK): blocks only interrupts at or below a priority level, leaving urgent ones running. RTOSes use this for critical sections so a high-priority motor-control interrupt is never delayed by the kernel.

Rules for writing interrupt handlers

An interrupt handler can run at any point in your main code, including halfway through a statement, and while it runs, others of equal or lower priority wait. So:

  1. Be short. Read the data, clear the flag, record what happened, return. Long processing belongs in the main loop or a task.
  2. Clear the source. If the peripheral's flag is not cleared, the interrupt fires again immediately after return, forever. On some parts the clear must happen a few cycles before return because of bus write buffering; read the flag back or add a __DSB() if you see double interrupts.
  3. Never block. No delays, no waiting on a flag that another interrupt would set, no printf to a slow UART, no mutex.
  4. Avoid non-reentrant functions. printf, malloc, strtok and many HAL functions use shared state and are not safe to call from a handler.
  5. Share data safely. Variables written by a handler and read elsewhere are volatile (see the registers guide), and any access of more than one step needs protection, as the next sections show.

Sharing data between a handler and main

#include <stdio.h>
#include <stdint.h>

static volatile uint32_t tick_ms;              /* written only by the timer ISR */
static volatile uint8_t  rx_byte, rx_ready;    /* written by the UART ISR */

static int irq_enabled = 1;                    /* stands in for the CPU's interrupt mask */
static void irq_disable(void) { irq_enabled = 0; }
static void irq_enable(void)  { irq_enabled = 1; }

void SysTick_Handler(void)  { tick_ms++; }
void USART2_IRQHandler(void) { rx_byte = 'k'; rx_ready = 1; }

/* A 32-bit read is atomic on a 32-bit core, but a two-variable snapshot is not. */
static int take_byte(uint8_t *out) {
  int got = 0;
  irq_disable();
  if (rx_ready) { *out = rx_byte; rx_ready = 0; got = 1; }
  irq_enable();
  return got;
}

int main(void) {
  for (int i = 0; i < 5; i++) SysTick_Handler();   /* five ticks happen */
  USART2_IRQHandler();                             /* a byte arrives */

  uint8_t b;
  printf("uptime %u ms\n", tick_ms);
  if (take_byte(&b)) printf("got '%c'\n", b);
  if (!take_byte(&b)) printf("nothing more\n");
  return 0;
}

The pattern: the ISR only produces; main takes a consistent snapshot with interrupts briefly off. For a stream of bytes, use a single-producer, single-consumer ring buffer, where the ISR writes only the head index and main writes only the tail, so no lock is needed.

Latency

Interrupt latency is the time from the event to the first useful instruction of the handler. It is the sum of:

  • the hardware entry time (12 cycles on M3/M4, more with wait states or FPU stacking)
  • any time the interrupt is masked: critical sections, PRIMASK, a higher-priority handler running
  • the time the handler spends before doing the urgent part

The worst case is what matters, and it is usually dominated by the longest critical section or the longest higher-priority ISR. Keep both short, and give the truly time-critical source the highest priority.

Pitfall: Calling an RTOS API from an ISR with a priority above the RTOS's configMAX_SYSCALL_INTERRUPT_PRIORITY corrupts the kernel. FreeRTOS checks this with configASSERT when it is enabled. Interrupts that call ...FromISR functions must sit at or below that level.

Race conditions

volatile makes the compiler re-read a variable. It does not make an update atomic. counter++ is three steps: load, add, store. If an interrupt modifies counter after the load and before the store, its change is overwritten and lost.

The window is a few instructions wide, so the bug shows up once in millions of iterations, never in the debugger and always in the field.

There are three ways to make shared data safe:

TechniqueHowCost
Critical sectionDisable interrupts around the access, then restoreAdds to worst-case interrupt latency
Single-writer designEach variable is written by only one context, such as the head and tail of a ring bufferNone, if it fits the problem
Atomic accessUse a type the CPU reads and writes in one instruction, or an atomic instructionOnly works for a single read or write, not read-modify-write

A critical section must restore the previous interrupt state, not simply enable interrupts. Otherwise a function that is called with interrupts already disabled would turn them back on.

#include <stdio.h>
#include <stdint.h>

// Stand-ins for the CPU's interrupt mask.
static uint32_t irq_disabled;
static uint32_t irq_save(void) { uint32_t old = irq_disabled; irq_disabled = 1; return old; }
static void irq_restore(uint32_t state) { irq_disabled = state; }

static volatile uint32_t shared_counter;

static void counter_add(uint32_t amount) {
  uint32_t state = irq_save();            // remember how things were
  shared_counter += amount;               // read-modify-write, now uninterruptible
  irq_restore(state);                     // put them back exactly
}

int main(void) {
  counter_add(5);
  printf("counter %u, interrupts disabled afterwards: %u\n", shared_counter, irq_disabled);

  irq_disabled = 1;                        // the caller is already in a critical section
  counter_add(5);
  printf("counter %u, interrupts disabled afterwards: %u\n", shared_counter, irq_disabled);
  return 0;
}

The same problem applies to reading a value wider than the CPU's word. On an 8-bit MCU, reading a 32-bit tick counter takes four instructions, and an interrupt between them yields a value that never existed. Either disable interrupts around the read, or read it twice and retry until both readings agree.

Time is a counter that wraps

Firmware measures time by counting ticks: a hardware timer raises an interrupt every millisecond, and the handler increments a counter. That counter has a fixed width, so it wraps. A 32-bit millisecond counter returns to zero after about 49.7 days; a 16-bit one after 65 seconds.

Code that compares timestamps directly works in every test and fails in the field, weeks later. The fix is one rule.

Compare durations, not timestamps. now - start is the elapsed time, and unsigned subtraction gives the right answer even when the counter has wrapped in between, as long as less than one full wrap has passed.

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

static bool expired_wrong(uint32_t now, uint32_t start, uint32_t timeout) {
  return now >= start + timeout;          // the deadline can wrap past zero
}

static bool expired_right(uint32_t now, uint32_t start, uint32_t timeout) {
  return now - start >= timeout;          // elapsed time, correct across rollover
}

int main(void) {
  uint32_t start = 0xFFFFFF00;            // 256 ms before the counter wraps
  uint32_t timeout = 0x200;               // 512 ms
  uint32_t now = 0xFFFFFFFF;              // only 255 ms later

  printf("elapsed: %u ms\n", now - start);
  printf("wrong test says expired: %d\n", expired_wrong(now, start, timeout));
  printf("right test says expired: %d\n", expired_right(now, start, timeout));
  return 0;
}

The wrong version computes a deadline of 0x100, which has wrapped to a small number, so the timeout appears to fire immediately.

Do not block

delay(500) is the first thing most people write and the first thing to remove. While the CPU sits in a delay loop it cannot read a button, service a protocol or feed a watchdog. Firmware that does several things at once is written so that nothing waits.

The pattern is a main loop that runs continuously, where each activity checks whether it is time to act and returns immediately if not.

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

typedef struct { uint32_t start, period; } soft_timer_t;

static bool timer_poll(soft_timer_t *t, uint32_t now) {
  if (now - t->start < t->period) return false;
  t->start += t->period;                 // advance by the period: no drift
  return true;
}

int main(void) {
  soft_timer_t blink = { 0, 250 }, report = { 0, 400 };

  for (uint32_t now = 0; now <= 1000; now += 50) {   // stands in for the main loop
    if (timer_poll(&blink, now)) printf("%4u ms: toggle LED\n", now);
    if (timer_poll(&report, now)) printf("%4u ms: send report\n", now);
  }
  return 0;
}

Two activities with different periods share one loop and neither delays the other.

Pitfall: Rescheduling with start = now adds every bit of lateness to the next period, so the rate drifts. start += period keeps the long-term rate exact.

Debouncing

A mechanical switch does not change state cleanly. Its contacts bounce for a few milliseconds, producing a burst of edges. Counting those as presses is the classic beginner bug.

The software fix is to sample the pin on a timer and accept a new state only after it has been seen for several consecutive samples.

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

typedef struct { bool stable; uint8_t count; } debounce_t;

static bool debounce(debounce_t *d, bool raw, uint8_t threshold) {
  if (raw == d->stable) d->count = 0;
  else if (++d->count >= threshold) { d->stable = raw; d->count = 0; }
  return d->stable;
}

int main(void) {
  debounce_t button = { false, 0 };
  const char *raw = "0010110111111100101000000";   // one sample every 5 ms
  printf("raw:       %s\ndebounced: ", raw);
  for (const char *p = raw; *p; p++) putchar(debounce(&button, *p == '1', 4) ? '1' : '0');
  putchar('\n');
  return 0;
}

Sampling every 5 ms with a threshold of 4 gives a 20 ms debounce time. Sampling on a timer, instead of interrupting on every edge, also protects the CPU from an interrupt storm while the contact bounces. An edge interrupt is still useful to wake the device and start sampling.

Hardware debounce is the alternative when software sampling is not possible, such as a wake-up pin: an RC low-pass filter feeding a Schmitt-trigger input.

Super-loop or RTOS

A cooperative scheduler is a table of tasks and a loop that runs whichever are due, built from the soft timers above. Each task runs to completion, so there is no preemption and almost no shared-data problem. Its limit is that one slow task delays all the others.

A preemptive RTOS gives each task its own stack and switches between them, so a high-priority task runs on time regardless of what the others are doing. The cost is RAM for the stacks and a new class of bugs: races between tasks, deadlock and priority inversion. The RTOS module (stage 5) covers tasks, scheduling and synchronisation in depth; the watchdog lesson in the peripherals module covers how to keep either design from hanging silently.

Common mistakes

  • Comparing now with a stored deadline instead of comparing elapsed time with a duration.
  • delay() in a loop that should be doing other things.
  • An interrupt handler that does not clear its source, so it re-enters forever.
  • Forgetting volatile on a variable shared with an interrupt, so a waiting loop is optimised into an infinite one.
  • Assuming volatile makes x++ safe.
  • A critical section that enables interrupts unconditionally on exit.
  • Calling printf or malloc from an interrupt handler.

Interview question: What should and should not be done inside an ISR?

Answer: Do the minimum that must happen immediately: read or write the hardware, clear the interrupt source, timestamp the event, put data in a buffer or set a flag, and signal a task with an ISR-safe primitive. Do not block or wait, call delay functions, print to a slow device, allocate memory, take a mutex, or call non-reentrant library functions. Defer the processing to the main loop or a task so the ISR stays short and latency for other interrupts stays low.

Interview question: Explain preemption priority versus subpriority on the NVIC.

Answer: The implemented priority bits are split by the priority grouping setting. The preemption (group) priority decides whether an interrupt can interrupt a running handler: only a strictly higher group priority (lower number) preempts. The subpriority only orders pending interrupts that share a group priority, deciding which runs first; it never causes preemption. If both are equal, the lower exception number wins.

Interview question: How do you debounce a button, and why is an edge interrupt alone not enough?

Answer: Contacts bounce for several milliseconds, so one press produces many edges; an edge interrupt alone would count each. Sample the pin periodically (for example every 5 to 10 ms from a timer) and accept a new state only after it has been the same for several consecutive samples (roughly 20 to 50 ms total). An edge interrupt can be used to wake up and start sampling. In hardware, an RC low-pass filter feeding a Schmitt-trigger input does the same job.

In the product: Anti-lock brakes (ABS)

ABS compares each wheel's speed with the car's every few milliseconds. The comparison must use elapsed time computed safely, so it still works when the millisecond counter wraps round after weeks of uptime.

#include <stdio.h>
#include <stdint.h>

int main(void) {
  uint32_t last_check = 0xFFFFFFF0u;   // just before the counter wraps
  uint32_t now = 0x00000010u;          // just after
  uint32_t elapsed = now - last_check; // unsigned subtraction: correct across the wrap
  printf("elapsed: %lu ms\n", (unsigned long)elapsed);

  int wheel_kmh = 20, car_kmh = 60;
  if (elapsed >= 5 && wheel_kmh * 100 < car_kmh * 80) printf("wheel locking: release pressure\n");
  return 0;
}

Build it: a clock that never jumps backwards

This is step 4 of the module project. The ESC measures time between motor commutations with a 16-bit hardware timer, which wraps every 65,536 ticks. Software counts the wraps in the timer's interrupt to make a 32-bit clock. The trap: if the timer wraps while interrupts are briefly disabled, the clock can read a value 65,536 ticks in the past, and the speed calculation goes wild.

Lab: Extend a 16-bit timer to 32 bits without a race

TIM3 counts from 0 to 0xFFFF and wraps, setting its update flag UIF (bit 0 of SR) on each wrap. It is started for you.

  • timer_isr() is the overflow interrupt: count one overflow and clear UIF (write ~UIF to SR; writing 0 clears a flag, 1 leaves it).
  • ticks() returns the 32-bit time, overflows << 16 | CNT. It may be called while an overflow is pending: the counter has wrapped, so CNT is small, but the interrupt has not run yet, so overflows is one short. Detect that case by checking UIF: if it is set, the wrap has happened, so read CNT again (after the flag check) and add one overflow.

The checks call ticks() in a loop and play an interrupt that is sometimes held off for a while, as when other code disables interrupts. They report if your clock ever goes backwards, or drifts from the CPU's cycle counter.

Going deeper

Interview question: How would you guarantee an ABS controller's reaction time?

Answer: Put wheel-speed capture in hardware timers (input capture), run the slip control at a fixed rate from a timer interrupt or the highest-priority task, and prove the deadline with worst-case execution time measurements and response-time analysis, including interrupt latency and blocking. Keep shared data between the ISR and tasks race-free, monitor the control loop with a watchdog that checks it runs on time, and fall back to plain braking (no ABS) on any fault, telling the driver.

Interview question: How do you safely read a 64-bit timestamp counter that an interrupt increments, on a 32-bit CPU?

Answer: A 64-bit read takes two instructions, so an interrupt between them can update the counter and the halves come from different values. Either read it with interrupts briefly disabled, or read the high word, the low word and the high word again, retrying until both high reads match. For hardware counters split across two registers the same retry pattern applies.

Interview question: Why do NVIC priority numbers on STM32 look like 0x10, 0x20 and so on?

Answer: The NVIC priority field is 8 bits wide, but STM32 parts implement only the top 4 bits. The values used are therefore the priority level shifted left by 4: level 1 is 0x10, level 2 is 0x20. CMSIS's NVIC_SetPriority takes the unshifted level and shifts it for you, which is why mixing raw register writes and CMSIS calls causes confusion.

Explain it: In your own words, explain why now - start >= timeout works across a timer rollover when now >= start + timeout does not.

Answer: With unsigned arithmetic, subtraction wraps modulo the counter size, so now - start always gives the true number of ticks elapsed, even if the counter overflowed and now is numerically smaller than start, as long as less than one full wrap has passed. Adding the timeout to start instead can itself overflow to a small number, making the deadline appear to have passed immediately or never. Comparing the elapsed time with the duration avoids ever computing a deadline that can wrap.