Foundations · Lesson 5 of 11 · about 15 min

Timers and interrupts

Exact timing without wasting the CPU

A delay loop keeps the whole CPU busy doing nothing, and its timing is a guess. Two hardware features fix this: timers and interrupts.

Timers: a counter that counts by itself

The prescaler (PSC) slows the clock down, and the counter starts again from 0 every time it reaches the reload value (ARR). Each restart is an update event.

Interrupts: the hardware taps the CPU on the shoulder

When an event happens, the CPU pauses your code, runs a short function called an interrupt service routine (ISR), then continues exactly where it stopped. For a software developer: an event callback, triggered by hardware.

The BoardPilot Learn screen: a lesson with its 3D board preview
Try it live

The real app, running in your browser: this lesson with its 3D preview on a simulated Raspberry Pi Pico. No install, nothing to plug in.

void TIM2_IRQHandler(void) {           // the name comes from the vector table
    if (TIM2->SR & (1 << 0)) {         // update event flag
        TIM2->SR &= ~(1 << 0);         // clear it, or the ISR runs again forever
        GPIOA->ODR ^= (1 << 5);        // toggle the LED
    }
}

// in main(): 16 MHz / 16000 = 1 kHz ticks, 1000 ticks = 1 second
TIM2->PSC = 15999;
TIM2->ARR = 999;
TIM2->DIER |= (1 << 0);                // interrupt on update
TIM2->CR1  |= (1 << 0);                // start counting
NVIC_EnableIRQ(TIM2_IRQn);             // let the CPU accept it

Interview questions

  1. What is the difference between polling and interrupts?
  2. Why should an interrupt routine be short?
  3. How do you choose PSC and ARR for an interrupt every second?

No answers here on purpose: try answering out loud first. In the BoardPilot app, the interview coach reads your own answer and tells you what was right, what is missing and what a senior interviewer would ask next (it uses the AI provider you choose in the app). Embedded systems interview questions →

Key terms

In the app, the lessons come alive

The lessons have interactive demos and hands-on labs checked on your board in the app. These pages are the readable version: the demos are described in words, and the labs need the app.

Download BoardPilot Try the lessons in your browser