STM32 Timer Interrupts Explained

In the previous article, STM32 Timer Prescaler, Counter and ARR Explained, we saw how the timer clock, the prescaler, the counter, and the auto-reload register work together to produce an update event at a fixed rate. We also calculated the pair PSC = 89 and ARR = 999 for a period of 1 ms. A timer that only counts is of limited use on its own, because the program still needs a way to find out when a period has ended. The timer interrupt provides this connection, since it lets the timer request the attention of the CPU each time the update event happens.

In this article, we will first look at what a timer interrupt is and how it differs from a blocking delay. Then we will follow the update event through the interrupt flag, the interrupt enable bit, and the NVIC, so that it is clear which part of the system is responsible for each step. After that, we will configure TIM3 in STM32CubeMX, start it with the HAL library, handle the callback, and finish with a complete example that toggles an LED at a fixed interval.

The examples in this article use the NUCLEO-F446RE board, with the same clock setup as in the previous article. The same approach applies to other STM32 families, but interrupt names, vector sharing, and timer clocks can differ, so anything that is not the same everywhere is marked as device-dependent. This article is part of the STM32 timer tutorial series.

What Is an STM32 Timer Interrupt

A timer interrupt is a request that a timer sends to the CPU when a chosen event happens inside the timer. The timer counts in hardware, so it keeps running without any help from the program. When the event occurs, for example when the counter passes the auto-reload value, the timer can signal the interrupt controller. The CPU then pauses the code that it is running, executes a short function called the interrupt service routine (ISR), and returns to the interrupted code at the exact point where it stopped.

This is the same mechanism that is used for pin interrupts, which we covered in GPIO Interrupts and EXTI. The only difference is the source of the request, which is an edge on a pin in that article and an event inside a timer in this one. A timer can produce several kinds of events, such as the update event, a capture or compare match, a trigger from another timer, or a break input on advanced-control timers. The available events are device-dependent. In this article, we will use only the update event, because it is the one that marks the end of a timer period and it is the basis of every periodic interrupt.

Interrupts vs Blocking Delays

The simplest way to wait in a program is a blocking delay such as HAL_Delay(). During the delay, the CPU does nothing except wait, so no other work can be done in the main program until the time has passed. The interval is also not exact when the delay is used in a loop with other code. The other code takes time to run, and this time is added to every cycle, so the real period is longer than the one you wanted.

A timer interrupt removes both problems. The hardware counts the time, so the interval stays exact no matter how long the main program takes to run its other tasks. The CPU is free between two interrupts, and it is only interrupted for the short time that the ISR needs. The diagram below compares the two approaches on a time axis.

Timeline comparing a blocking delay where the CPU waits with a timer interrupt that runs short ISRs between main program code

STM32 Timer Update Interrupt

In up-counting mode, the counter increases by one with each tick of the counter clock until it reaches the value in the auto-reload register. On the next tick, it returns to 0 and the timer generates an update event, which is often written as UEV. This is the same overflow that defines the update frequency in the previous article. The update event can also be created by software through the UG bit in the event generation register, and some devices allow it through the slave mode controller. On advanced-control timers, the repetition counter must reach 0 before an update event is generated, so we assume a repetition value of 0 throughout this article.

The update event does two things inside the timer. It moves the buffered values of the prescaler and the auto-reload register into their active registers, and it sets the update interrupt flag (UIF) in the status register of the timer. Whether this flag actually leads to an interrupt depends on two more switches, which we will look at next.

Event, Flag, and Enable Bit

The UIF bit in the status register TIMx_SR is set by the hardware at every update event, even when interrupts are not used at all. For this reason, the flag can be read in a polling loop to detect the end of a period without any interrupt. To turn the flag into an interrupt request, the update interrupt enable bit (UIE) in the DMA/interrupt enable register TIMx_DIER must be set. When both bits are 1, the timer sends an interrupt request to the interrupt controller.

The flag stays set until software clears it. If the ISR does not clear the flag, the request remains active, and the CPU enters the ISR again as soon as it returns. The HAL library clears the flag inside its interrupt handler, so the generated code takes care of this step, but it is important to know that it happens there.


Timer Flag vs NVIC Enable

There are two separate levels of control in the path from the timer to the CPU. The first level is inside the timer, and it consists of the UIF flag and the UIE enable bit. The second level is inside the Cortex-M core, where the NVIC decides whether the interrupt line of the timer is allowed to interrupt the CPU and with which priority. Both levels must be open for the ISR to run. A set UIF flag with a disabled NVIC line is never served, and an enabled NVIC line with a cleared UIE bit never receives a request.

LevelLocationRole
Timer eventCounter overflowCreates the update event
Timer flagUIF bit in TIMx_SRRecords that the update event has happened
Timer enableUIE bit in TIMx_DIERAllows the flag to raise an interrupt request
Core enableNVIC line, for example TIM3_IRQnAllows the request to interrupt the CPU, with a priority

On the STM32F446, TIM3 has its own interrupt line called TIM3_IRQn, which serves all interrupt sources of this timer. Some timers share a vector with another peripheral, for example TIM1 with TIM10 on TIM1_UP_TIM10_IRQn and TIM6 with the DAC on TIM6_DAC_IRQn. These assignments are device-dependent, and the vector table in the reference manual shows the correct names for your device. The diagram below shows the full path.

STM32 timer interrupt path from update event to UIF flag, UIE enable bit, NVIC enable, and the TIM3 interrupt handler

STM32 Timer Interrupt in CubeMX

In this section, we will configure TIM3 in STM32CubeMX so that it generates an update interrupt every 500 ms. We will create the project for the NUCLEO-F446RE board and accept the default peripheral settings that CubeMX offers when the board is selected. With this option, the green user LED LD2 on pin PA5 is already configured as a GPIO output, so we do not need to set up the LED pin by hand. If you want to review how a push-pull output works, the article GPIO Push-Pull vs Open-Drain explains it.

Select the Timer Clock and Period

The first step is to check the clock. Open the Clock Configuration tab and confirm that HCLK is 180 MHz and that the APB1 timer clocks are 90 MHz, which is the same setup that we used in the previous article. TIM3 is connected to APB1, so its timer clock is twice the 45 MHz APB1 peripheral clock. If you need a reminder of the clock tree, the article STM32 Clock System Explained covers it.

STM32CubeMX Clock Configuration tab for NUCLEO-F446RE showing HCLK at 180 MHz and APB1 timer clocks at 90 MHz

Next, open Pinout & Configuration, select Timers, and click TIM3. Set Clock Source to Internal Clock. In the Parameter Settings, we enter the values that give a period of 500 ms. A timer clock of 90 MHz divided by a prescaler factor of 9000 gives a counter clock of 10 kHz, and an auto-reload period of 5000 ticks at this rate lasts 500 ms. The register values are one less than these factors, as explained in the previous article.

ParameterValueReason
Prescaler (PSC โ€“ 16 bits value)8999Divides 90 MHz by 9000 to give a 10 kHz counter clock
Counter ModeUpThe counter runs from 0 to ARR
Counter Period (AutoReload Register โ€“ 16 bits value)4999A period of 5000 ticks, which is 500 ms at 10 kHz
Internal Clock DivisionNo DivisionDoes not affect the update rate
auto-reload preloadEnableThe value is loaded at the next update event

The update frequency is 90,000,000 / (9000 ร— 5000) = 2 Hz, which is a period of 500 ms. Both values fit easily into the 16-bit registers of TIM3. The preload setting only matters when ARR is changed while the timer is running, so either choice works for this example.

STM32CubeMX TIM3 parameter settings with prescaler 8999, up counter mode, and counter period 4999 for a 500 ms update interrupt

Enable the Timer Interrupt in the NVIC

The timer parameters in CubeMX do not contain a separate checkbox for the update interrupt enable bit. Instead, CubeMX prepares the interrupt line in the NVIC. Open the NVIC Settings tab, and tick the Enabled box in the row TIM3 global interrupt. CubeMX then generates the code that sets the priority and enables the interrupt line in the NVIC, and it also generates the handler function in the interrupt source file. The default priority of 0 is sufficient for this example. In projects with several interrupts, the priorities should be chosen on purpose, because a lower number means a higher priority.

STM32CubeMX NVIC Settings tab for TIM3 with the TIM3 global interrupt enabled

Generate and Review the HAL Code

Save the project to generate the code, and then look at the three places where CubeMX writes timer-related code. In main.c, the function MX_TIM3_Init() fills the initialization structure with the values from the table and calls HAL_TIM_Base_Init().

In stm32f4xx_hal_msp.c, the function HAL_TIM_Base_MspInit() enables the TIM3 peripheral clock, sets the interrupt priority, and enables the interrupt line with HAL_NVIC_EnableIRQ(TIM3_IRQn). In stm32f4xx_it.c, the function TIM3_IRQHandler() calls HAL_TIM_IRQHandler(&htim3), which is the entry point of the interrupt.

It is worth noticing what the generated code does not contain. It configures the timer and the interrupt line, but it does not start the counter, so nothing happens until we add the start call ourselves.


HAL Timer Interrupt Callback

The timer configuration is complete, so we can now write the part that the program has to do itself. It consists of starting the timer in interrupt mode and writing the function that reacts to each update event.

Start the Timer in Interrupt Mode

The HAL library offers two start functions for a timer in base mode. The function HAL_TIM_Base_Start() only starts the counter, and the function HAL_TIM_Base_Start_IT() also sets the UIE bit, so that the update flag creates an interrupt request. If the first function is used by mistake, the counter runs and the flag is set at each period, but the ISR never runs.

The initialization code of HAL generates one update event, which moves the prescaler value into its active register. As we saw at the end of the previous article, this event sets the update flag before the timer is started. When the interrupt is enabled afterward, it fires immediately, so the first callback occurs right after the start instead of after a full period. Clearing the flag before the start call avoids this extra interrupt. Both lines belong into the user code section of main(), after the initialization functions.


Handle the Callback

When the update interrupt occurs, the CPU runs TIM3_IRQHandler(), which calls HAL_TIM_IRQHandler(). This HAL function checks the UIF and UIE bits, clears the flag, and then calls the function HAL_TIM_PeriodElapsedCallback(). The library provides this function with the attribute __weak, which means that we can define our own version in the user code and the linker will use it instead of the empty default.

The same callback is used for every timer in the program that has an update interrupt. For this reason, the function receives a pointer to the timer handle, and we must compare its Instance member with the timer that we want to serve. Without this check, the code would run for the update event of any timer.

There is one case where this function already exists in the project. When a timer is selected as the HAL time base instead of SysTick, which is common in projects with an RTOS, CubeMX generates its own HAL_TIM_PeriodElapsedCallback() at the end of main.c. It contains a check for the time base timer and a call to HAL_IncTick(). Defining a second copy would cause a duplicate-definition error, so in this case we add another if branch to the existing function.


Keep the Callback Short

The callback runs inside an interrupt, which means that it has priority over the main program and over every interrupt with a lower priority. The longer it runs, the longer the rest of the system is delayed. For this reason, the callback should only do the work that must happen at the exact moment of the event, such as toggling a pin or updating a counter.

Blocking calls must not be used inside the callback. The most important example is HAL_Delay(), because it waits for the SysTick interrupt to increase the tick counter. If the timer interrupt has a higher priority than SysTick, the tick counter can never advance while the callback is running, and the program stops there forever. Other calls to avoid are printf(), long loops, and blocking transmit functions of serial peripherals. When more work is needed, a common pattern is to set a flag in the callback and to do the work in the main loop.

The variable is declared volatile because it is changed inside the interrupt and read in the main loop. Without this keyword, the compiler may keep the value in a register and the main loop would never see the change.


STM32 Timer Interrupt LED Example

We can now combine all steps in one complete example. The program toggles the green LED LD2 of the NUCLEO-F446RE every time TIM3 produces an update event, and it counts the toggles in a variable that can be watched in the debugger. The main loop stays empty, which shows that the blinking does not depend on the CPU being busy with a delay.

  1. Create a new STM32CubeIDE project for the NUCLEO-F446RE board and accept the default peripheral initialization.
  2. In the Clock Configuration tab, confirm that HCLK is 180 MHz and that the APB1 timer clocks are 90 MHz.
  3. Set TIM3 to the Internal Clock source with Prescaler 8999, Counter Mode Up, and Counter Period 4999.
  4. Enable the TIM3 global interrupt in the NVIC Settings tab of TIM3.
  5. Generate the code and add the user code shown below.

The update frequency of TIM3 is 2 Hz, so the callback runs every 500 ms. Each call toggles the LED once, which means that the LED stays on for 500 ms, then off for 500 ms, and the complete blink cycle lasts 1 s. The blink frequency is therefore 1 Hz, which is half of the update frequency. In general, when the LED is toggled once per interrupt, the relation is LED frequency = update frequency / 2. If we want a blink frequency of 5 Hz, we need an update frequency of 10 Hz, which is reached with PSC = 8999 and ARR = 999.

Counter ramp from 0 to ARR with an update event every 500 ms and an LED that toggles at each event, giving a 1 s blink period

STM32 Timer Interrupt Not Working

Most timer interrupt problems are caused by a small number of setup mistakes. Because the timer and the interrupt controller have separate switches, a single missing step is enough to stop the callback from running, and the program usually gives no error message.

NVIC Interrupt Not Enabled

When the TIM3 global interrupt is not enabled in the NVIC, the timer still counts and the UIF flag is still set at every period, but the CPU never enters the ISR. This is the most common reason for a callback that never runs. In the debugger, the CNT register of the timer changes and the UIF bit stays set, which shows that the timer side works. The fix is to enable the interrupt in the NVIC Settings tab of the timer and to check that HAL_NVIC_EnableIRQ() appears in HAL_TIM_Base_MspInit().


Wrong Timer Instance in the Callback

The callback is shared by all timers, so the instance check must name the timer that we configured. If the code checks for TIM2 while the interrupt comes from TIM3, the callback is called but the body is never executed, and the LED does not change. This mistake often happens after code is copied from another project. It is also the reason why a timer that is used as the HAL time base needs its own branch in the same function.


Wrong Clock or PSC and ARR Values

When the LED blinks at a wrong speed, the cause is usually the timer clock or a register value. The two common mistakes are using the APB peripheral clock instead of the timer clock, which leads to a result that is off by a factor of two, and entering the division factors 9000 and 5000 instead of the register values 8999 and 4999. The update frequency formula from the previous article, update frequency = timer clock / ((PSC + 1) ร— (ARR + 1)), should be used to verify the numbers before the code is run.


Timer Started Without Interrupt Mode

If the program calls HAL_TIM_Base_Start() instead of HAL_TIM_Base_Start_IT(), the counter runs but the UIE bit stays cleared, so no interrupt request is created. The fix is to use the _IT variant. This mistake is easy to miss because the timer registers look correct in the debugger, with the counter changing and the flag being set.


Toggling Halves the Frequency

Toggling an output once per interrupt creates a square wave whose frequency is half of the update frequency, because one full cycle of the output needs two toggles. A timer with an update frequency of 2 Hz produces an LED blink of 1 Hz, and a timer with an update frequency of 1 kHz produces a square wave of 500 Hz. To reach a target output frequency, the update frequency must be set to twice this value.


Interrupt Fires Immediately After Start

When the callback runs once right after the start instead of after the first full period, the update flag was already set before the interrupt was enabled. The initialization code causes this, as described in the section about starting the timer. Clearing the flag with __HAL_TIM_CLEAR_FLAG(&htim3, TIM_FLAG_UPDATE) before calling HAL_TIM_Base_Start_IT() removes the extra interrupt.


Conclusion

A timer interrupt turns the update event of a timer into a function call. The counter reaches the auto-reload value and the update event sets the UIF flag. The UIE bit lets this flag raise a request, the NVIC line lets the request reach the CPU, and the HAL handler clears the flag and calls HAL_TIM_PeriodElapsedCallback(). Since the hardware does the counting, the interval stays exact, and the main program is free to do other work between two interrupts.

The most important points are to keep the two levels of control separate, and to check each of them when the callback does not run. The timer needs the UIE bit, which HAL_TIM_Base_Start_IT() sets, and the NVIC needs the interrupt line to be enabled. The callback must check the timer instance and must stay short, and a toggled output runs at half of the update frequency. In the next articles of the timer series, we will build on the same update event and use the timer for other tasks.


Download the Project Here

Download the CubeMX project files and HAL source code โ€” all tested on real hardware.

If you find this useful, you can support us with a Donation as well.

Article by Yashmiti

Yashmiti is a technical writer at STM32Guide, where she creates tutorials and guides that help embedded-systems learners and developers work confidently with STM32 microcontrollers. Her writing covers tools like STM32CubeIDE and STM32CubeMX, along with peripherals and communication protocols โ€” always with an emphasis on clear explanations and hands-on examples that take readers from concept to working project.

She's also part of the effort to build STM32Guide into an organized, easy-to-navigate resource for the STM32 community.

Leave a Comment