STM32F411 Timer Interrupt for Micromouse - Basic Timer Operation, Timer Clock Calculation, Interrupt Generation Process, Important Timer Registers,Types of Timer Interrupts, Timer Interrupt vs Delay Function, Best Practices

 

STM32F411 Timer Interrupt for Micromouse - Basic Timer Operation, Timer Clock Calculation, Interrupt Generation Process, Important Timer Registers,Types of Timer Interrupts, Timer Interrupt vs Delay Function, Best Practices

Timer interrupts are one of the most important features of the STMicroelectronics STM32F411 microcontroller. They allow the CPU to execute specific tasks automatically at precise time intervals without continuously checking the timer status.

Timer interrupts are widely used in:

  • Robotics
  • Micromouse systems
  • Motor control
  • Real-time operating systems
  • Sensor sampling
  • Communication protocols
  • Embedded automation

A timer interrupt helps embedded systems perform periodic tasks accurately and efficiently.


What Is a Timer Interrupt?

A timer interrupt occurs when a hardware timer reaches a specific condition.

Common interrupt events include:

  • Counter overflow
  • Counter match
  • Input capture event
  • PWM update event

When the interrupt occurs:

  1. Timer sends an interrupt request
  2. CPU temporarily pauses current execution
  3. Interrupt Service Routine (ISR) executes
  4. CPU returns to the previous program

This mechanism enables precise real-time control.


Basic Timer Operation

A timer continuously counts clock pulses.

he counter increases like this:

0123...0 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow ...

When the counter reaches the Auto-Reload Register (ARR) value:

  • Counter resets
  • Interrupt event can occur

This creates periodic timing events.


Timer Clock Calculation

The timer frequency depends on:

  • System clock
  • Prescaler
  • Auto-reload register

The timer update frequency equation is:

fupdate=ftimer(PSC+1)(ARR+1)f_{update}=\frac{f_{timer}}{(PSC+1)(ARR+1)}

Where:

  • fupdatef_{update} = interrupt frequency
  • ftimerf_{timer} = timer input clock
  • PSC = prescaler
  • ARR = auto reload register


Example Timer Interrupt Calculation

Suppose:

  • Timer clock = 84 MHz
  • PSC = 8399
  • ARR = 9999

Then:

fupdate=84000000(8399+1)(9999+1)f_{update}=\frac{84000000}{(8399+1)(9999+1)}

Result:

fupdate=1Hzf_{update}=1Hz

This means:

  • Interrupt occurs once every second


Interrupt Generation Process

The complete interrupt sequence works like this:


MicromouseInterruptProcess

Step 1 — Timer Counts

The counter increments continuously.

Step 2 — Counter Reaches ARR

When CNT = ARR:

  • Update event occurs

Step 3 — Interrupt Flag Is Set

The timer sets an interrupt flag internally.

Step 4 — NVIC Receives Interrupt

NVIC stands for:
Nested Vector Interrupt Controller

It manages all interrupts in STM32.

Step 5 — CPU Executes ISR

The processor jumps to the interrupt function.

Example ISR:

void TIM2_IRQHandler(void)
{
    HAL_TIM_IRQHandler(&htim2);
}
Step 6 — Callback Function Executes

HAL library usually calls:

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    // User code
}

This function contains user-defined tasks.

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {


if (htim == &htim9) {

mice->miceUpdate();

}


}


Important Timer Registers

PSC — Prescaler Register

Divides the timer clock frequency.

Equation:

fcounter=fclockPSC+1f_{counter}=\frac{f_{clock}}{PSC+1}

Larger PSC: Slower counting

ARR — Auto Reload Register

Defines maximum counter value.

When counter reaches ARR:  Update event occurs

CNT — Counter Register

Stores current timer count.

DIER — DMA/Interrupt Enable Register

Controls interrupt enabling.

Important bit:  UIE = Update Interrupt Enable

SR — Status Register

Contains interrupt flags.

Important flag: UIF = Update Interrupt Flag


Types of Timer Interrupts

STM32 timers support multiple interrupt types.

   1. Update Interrupt

   Occurs when:

  • Counter overflows
  • Counter underflows

   Most common interrupt type.

   Applications:

  • Periodic tasks
  • Time scheduling

   2. Capture Compare Interrupt

   Triggered when:

  • CNT matches CCR value

   Applications:

  • PWM timing
  • Event synchronization

   3. Input Capture Interrupt

   Triggered by external signal edges.

   Applications:

  • Frequency measurement
  • Pulse timing

   4. Trigger Interrupt

   Generated by synchronization events.

   Applications:

  • Timer synchronization


Configuring Timer Interrupts

Following example for 500Hz timer


/* TIM9 init function */

void MX_TIM9_Init(void)

{


/* USER CODE BEGIN TIM9_Init 0 */


/* USER CODE END TIM9_Init 0 */


TIM_ClockConfigTypeDef sClockSourceConfig = {0};


/* USER CODE BEGIN TIM9_Init 1 */


/* USER CODE END TIM9_Init 1 */

htim9.Instance = TIM9;

htim9.Init.Prescaler = 1000;

htim9.Init.CounterMode = TIM_COUNTERMODE_UP;

htim9.Init.Period = 200;

htim9.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;

htim9.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;

if (HAL_TIM_Base_Init(&htim9) != HAL_OK)

{

Error_Handler();

}

sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;

if (HAL_TIM_ConfigClockSource(&htim9, &sClockSourceConfig) != HAL_OK)

{

Error_Handler();

}

/* USER CODE BEGIN TIM9_Init 2 */

HAL_TIM_Base_Start(&htim9);

TIM9->DIER |= TIM_DIER_UIE;


/* USER CODE END TIM9_Init 2 */


}


STM32 HAL Interrupt Workflow

Typical STM32 HAL timer interrupt structure:

HAL_TIM_Base_Start_IT()
        ↓
Timer overflow occurs
        ↓
TIMx_IRQHandler()
        ↓
HAL_TIM_IRQHandler()
        ↓
HAL_TIM_PeriodElapsedCallback()

This layered structure simplifies development.


Example: LED Blinking Using Timer Interrupt

A timer interrupt can toggle an LED every second.

Basic logic:

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13);
}

Micromouse update logic:

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {


if (htim == &htim9) {

mice->miceUpdate();

}


}

Advantages:

  • Precise timing
  • Non-blocking operation
  • CPU free for other tasks


Timer Interrupt vs Delay Function

   Delay Function

   HAL_Delay(1000);

   Problems:

  • Blocks CPU
  • Poor multitasking
  • Inefficient

   Timer Interrupt

   Advantages:

  • Non-blocking
  • Real-time operation
  • Better system responsiveness

   Timer interrupts are preferred in professional embedded systems.


Applications of Timer Interrupts

   Robotics

   Used for:

  • Sensor updates
  • Motion control
  • PID loops
  • Encoder calculations

   Micromouse robots heavily depend on timer interrupts.


Real-Time Operating Systems

Timer interrupts provide:

  • Task scheduling
  • System tick generation


Communication Protocols

Used in:

  • UART timing
  • SPI synchronization
  • Software protocols


Data Acquisition

Periodic sensor sampling:

  • ADC triggering
  • Signal processing


Interrupt Priority

STM32 supports interrupt priority management.

Higher priority interrupts:

  • Execute first

Lower priority interrupts:

  • Wait until higher priority tasks finish

Proper priority design is essential in complex systems.


Interrupt Latency

Interrupt latency is the delay between:

  • Interrupt occurrence
  • ISR execution

Factors affecting latency:

  • CPU speed
  • Interrupt priority
  • ISR complexity

STM32F411 provides very low interrupt latency.


Best Practices

   Keep ISR Short

   Avoid heavy processing inside interrupts.

   Good ISR:

  • Fast execution
  • Minimal operations

   Avoid Delays Inside ISR

   Never use:

  HAL_Delay()

   inside interrupt functions.

  Use Volatile Variables

   Shared variables should use:

  volatile

   to prevent compiler optimization issues.

  Use Flags

   Instead of heavy processing:

  • Set a flag in ISR
  • Process in main loop 

  Efficient approach:

volatile uint8_t timerFlag = 0;

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    timerFlag = 1;
}

Common Problems

   Interrupt Not Triggering

   Possible causes:

  • NVIC disabled
  • Interrupt source disabled
  • Wrong timer configuration

   Wrong Timing

   Causes:

  • Incorrect prescaler
  • Wrong ARR calculation
  • Clock configuration issues

   Interrupt Flooding

   Occurs when:

  • Interrupt frequency too high
  • ISR too slow

This can overload CPU performance.


Timer Interrupt in Micromouse Robots

Micromouse systems commonly use timer interrupts for:

  • PID motor control
  • Sensor polling
  • Encoder updates
  • Motion timing

Typical interrupt frequencies:

  • 1 kHz control loop
  • 10 kHz motor PWM
  • Periodic sensor reading

Accurate interrupts are essential for stable navigation.


Conclusion

STM32F411 timer interrupts are a core feature for real-time embedded system development. They allow precise periodic execution of tasks without blocking the CPU. By using hardware timers together with interrupt mechanisms, developers can build efficient, responsive, and accurate systems for robotics, automation, motor control, and communication applications.

Understanding timer interrupts is essential for advanced STM32 programming and professional embedded system design.

Comments

Popular posts from this blog

How to Build a Micromouse Robot - Mechanical, Hardware, Software

Micromouse Competitions - Types, Overview, Comparison, Advantages, Worldwide

Complete Guide to Micromouse Maze - Dimensions, Structure and Components, Building