STM32 Timer Interrupts: A Practical Guide to Timers, Button Interrupts

STM32 Timer Interrupts

In embedded systems, timing is everything. Whether you are blinking an LED every second, reading a sensor at fixed intervals, or reacting instantly to a button press, STM32 timer interrupts are one of the most important concepts you must master.

STM32 microcontrollers are widely used in automation, IoT, robotics, automotive electronics, and industrial control because of their rich peripheral ecosystem. Among these peripherals, STM32 timers and interrupts form the backbone of real-time processing.

If you have ever used blocking delays like HAL_Delay() and noticed your microcontroller becoming unresponsive, this guide will show you a much better approach. Here, you will learn STM32 timer configuration, stm32 button interrupt, stm32 external interrupt, timer overflow behavior, interrupt priorities, and practical real-world examples that developers actually use in 2026.

STM32 timer interrupts are hardware-based events that allow STM32 microcontrollers to perform precise time-controlled tasks without using blocking delays. They are commonly used for LED blinking, PWM generation, sensor polling, timeout detection, and real-time scheduling. When combined with STM32 external interrupts for button presses or GPIO events, they create fast and efficient embedded systems. Understanding timer overflow, NVIC priority, and ISR handling is essential for modern STM32 programming.

Why STM32 Timer Interrupts Matter in Real Projects

In many beginner projects, developers use software delays to control timing. While this works for simple LED blinking, it becomes a serious problem in real applications.

For example:

  • A motor controller needs precise PWM timing
  • A sensor must be sampled every 10 ms
  • A communication timeout must be detected accurately
  • A button press should be captured instantly
  • Multiple tasks must run without blocking the CPU

This is where STM32 timer interrupts become essential.

Instead of wasting CPU cycles in a loop, the timer peripheral counts in the background. Once the counter reaches a preset value, it triggers an interrupt and the CPU runs the corresponding Interrupt Service Routine (ISR).

This method improves:

  • CPU efficiency
  • responsiveness
  • power optimization
  • multitasking behavior
  • timing precision

    Start Your Training Journey Today

Understanding STM32 Timers Explained Simply

Before jumping into interrupts, it helps to understand how STM32 timers explained at the hardware level.

A timer mainly consists of:

Timer Component

Function

Prescaler

Divides input clock frequency

Counter

Counts timer ticks

Auto Reload Register (ARR)

Sets overflow value

Compare Register

Triggers compare events

Capture Unit

Measures input signal timing

How Timer Overflow Works

A stm32 timer overflow interrupt occurs when the counter reaches the ARR value and resets to zero.

For example:

  • MCU clock = 72 MHz
  • Prescaler = 7200 – 1
  • ARR = 10000 – 1

This creates a 1-second interrupt event.

That is the foundation of almost every stm32 timer interrupt example.

Types of STM32 Timers

STM32 microcontrollers provide different types of timers for various applications:

1. Basic Timers (TIM6, TIM7)

  • Used for simple time base generation
  • No input/output features

2. General Purpose Timers (TIM2–TIM5)

  • Support input capture and output compare
  • Used in most applications

3. Advanced Timers (TIM1, TIM8)

  • Used for motor control and PWM
  • Support dead-time insertion and complementary outputs

Key Insight:

Choosing the right timer type is important for performance and scalability in embedded systems.

STM32 Timer Configuration Step by Step

A correct stm32 timer configuration follows a clear workflow.

1) Enable Timer Clock

First enable the peripheral clock for TIM2.

__HAL_RCC_TIM2_CLK_ENABLE();

2) Configure Prescaler and Period

This decides interrupt frequency.

htim2.Instance = TIM2;

htim2.Init.Prescaler = 7199;

htim2.Init.Period = 9999;

htim2.Init.CounterMode = TIM_COUNTERMODE_UP;

HAL_TIM_Base_Init(&htim2);

3) Start Interrupt Mode

HAL_TIM_Base_Start_IT(&htim2);

4) Handle Timer Callback

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)

{

   if(htim->Instance == TIM2)

   {

       HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);

   }

}

This is the most common stm32 timer interrupt example code used for LED blink projects.

Practical STM32 Timer Example: LED Blink Without Delay

Let’s convert the theory into a practical stm32 timer example.

Problem

Blink LED every 1 second without blocking delay.

Why This Matters

Using interrupt-driven timing allows the CPU to simultaneously:

  • read sensors
  • process UART data
  • handle communication
  • monitor button events

Workflow

  1. Timer counts in hardware
  2. Overflow occurs every 1 second
  3. Interrupt triggers callback
  4. LED toggles instantly

This is much more scalable than HAL_Delay().

Real Industry Use Case

This same structure is used in:

  • RTOS task scheduling
  • industrial PLC timing
  • battery monitoring systems
  • automotive diagnostics
  • IoT heartbeat signals

STM32 Button Interrupt and External Interrupt Setup

Now let’s combine timers with stm32 button interrupt logic.

A button press is typically handled using stm32 external interrupt through EXTI lines.

Example Use Case

  • PA0 → button input
  • PA5 → LED output

When the button is pressed, the LED toggles immediately.

GPIO External Interrupt Configuration

GPIO_InitTypeDef GPIO_InitStruct = {0};

GPIO_InitStruct.Pin = GPIO_PIN_0;

GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;

GPIO_InitStruct.Pull = GPIO_PULLUP;

HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

Callback Function

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)

{

   if(GPIO_Pin == GPIO_PIN_0)

   {

       HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);

   }

}

This is one of the most searched beginner-friendly stm32 external interrupt examples.

Button Debouncing in STM32 Interrupts

Mechanical buttons do not generate a clean signal. When pressed, they produce multiple rapid transitions due to physical bouncing.

This can cause multiple unwanted interrupts.

Software Debouncing Example:

static uint32_t last_interrupt_time = 0;

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)

{

  if(GPIO_Pin == GPIO_PIN_0)

  {

     if(HAL_GetTick() - last_interrupt_time > 200)

     {

        HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);

        last_interrupt_time = HAL_GetTick();

     }

  }

}

Why It Matters:

  • Prevents false triggering
  • Improves system reliability
  • Essential for real-world products

    Explore Courses - Learn More

STM32 Timer Interrupt vs External Interrupt

A common beginner confusion is choosing between timer and GPIO interrupts.

Feature

Timer Interrupt

External Interrupt

Trigger Source

Internal timer event

GPIO pin event

Best For

periodic tasks

button/sensor trigger

Precision

extremely high

depends on external signal

CPU Usage

low

low

Example

LED blink

push button

Expert Tip

In real products, both are often combined.

For example:

  • timer interrupt → periodic sensor read
  • button interrupt → manual trigger
  • timer overflow → timeout recovery

This hybrid design is common in smart devices.

Understanding STM32 Interrupt Priority

When multiple interrupts occur together, stm32 interrupt priority decides which ISR runs first.

For example:

  • UART receive interrupt
  • Timer overflow interrupt
  • Button press interrupt

NVIC handles the order.

HAL_NVIC_SetPriority(TIM2_IRQn, 1, 0);

HAL_NVIC_EnableIRQ(TIM2_IRQn);

Best Practice

Use higher priority for:

  • motor control
  • communication safety
  • emergency stop
  • critical timing loops

Use lower priority for:

  • status LEDs
  • logging
  • debug UART

Good interrupt design prevents latency issues.

Common Mistakes to Avoid

Even experienced developers sometimes make these mistakes.

  • Wrong Prescaler Calculation

This causes incorrect timing intervals.

  • Heavy ISR Code

Avoid long calculations inside interrupt callbacks.

Bad:

for(int i=0;i<100000;i++);

Good:
Set a flag and process in main loop.

  • Missing Interrupt Flag Handling

Uncleared flags may repeatedly trigger the ISR.

  • Ignoring Button Debounce

A stm32 button interrupt may trigger multiple times because of switch bounce.

  • Poor Priority Design

Improper stm32 interrupt priority can break communication and control loops.

Trends: Where STM32 Timer Interrupts Are Used

In 2026 and beyond, timer-driven architectures are becoming even more important.

Major Growth Areas

  • Industrial IoT edge controllers
  • Robotics timing loops
  • EV battery systems
  • Smart medical devices
  • AI-enabled embedded systems
  • autonomous drones
  • predictive maintenance devices

Precise interrupt timing is a foundational skill for these industries.

Future STM32 projects increasingly rely on:

  • DMA + timer triggers
  • ADC synchronized sampling
  • advanced PWM motor control
  • low-power wake-up timers
  • hardware event chaining

So mastering STM32 timer interrupts directly improves your embedded systems career.

Best Practices for Reliable STM32 Timer Projects

Follow these expert recommendations:

  • Keep ISR code minimal
  • Use flags for heavy processing
  • calculate prescaler carefully
  • debounce external interrupts
  • document timer frequencies
  • use CubeMX for visualization
  • validate overflow intervals on oscilloscope
  • prioritize critical interrupts properly

These practices make firmware production-ready.

Talk to Academic Advisor

Conclusion

Understanding STM32 timer interrupts is one of the most valuable skills in embedded systems development. From simple LED blinking to advanced motor control and industrial IoT timing loops, timers and interrupts define how efficiently your firmware responds to real-world events.

By learning stm32 timers, stm32 timer interrupt example code, stm32 button interrupt, and stm32 external interrupt workflows, you build the foundation required for high-performance real-time applications.

If you want to grow into advanced embedded firmware roles in 2026, mastering timer interrupts, overflow logic, and NVIC priority management is non-negotiable.

Start with a simple LED blink project, combine it with a button interrupt, then scale toward PWM, DMA, and RTOS scheduling.

Frequently Asked Questions

A timer interrupt occurs when the STM32 timer counter reaches its overflow or compare value and triggers an ISR.

It is the interrupt generated when the timer counter exceeds the ARR value and resets.

A GPIO pin is configured in EXTI mode so a rising or falling edge triggers an ISR.

Interrupts are better for real-time responsiveness and CPU efficiency.

LED blinking every 1 second using TIM2 is the best starting project.

Author

Embedded Systems trainer – IIES

Updated On: 11-04-26


10+ years of hands-on experience delivering practical training in Embedded Systems and it's design