Detailed explanation of TIM timed interrupt in STM32
A TIM timed interrupt in STM32 (using a general-purpose timer) is one of the most powerful features in real-time embedded systems. It allows the microcontroller to perform specific tasks at precise time intervals, independent of main code execution.
What Is a TIM Timed Interrupt?
A TIM interrupt is an event triggered by a timer peripheral (e.g., TIM2, TIM3, etc.) when it counts to a specified value. You can configure this to fire periodically, for example, every 1 ms or every 1 second.
Use Cases
-
Blinking LEDs at a fixed rate
-
Running a real-time scheduler
-
Sampling sensors at fixed intervals
-
Generating PWM signals (with interrupts)
Key Registers in TIM
| Register | Role |
|---|---|
PSC | Prescaler (divides timer clock) |
ARR | Auto-reload register (sets period) |
CNT | Current counter value |
DIER | Interrupt enable register |
SR | Status register (flags) |
CR1 | Control register (start/stop) |
Basic Timing Formula
To generate an interrupt every T seconds:
So:
How to Set Up a TIM Timed Interrupt
Here’s how to configure it step-by-step using STM32CubeIDE:
1. Enable Timer in STM32CubeMX
-
Open your project in STM32CubeMX or STM32CubeIDE
-
Enable
TIM2(or any general-purpose timer) -
Mode: Internal Clock
-
Enable Update Event Interrupt (UIE)
2. Set Timer Prescaler and Period
In the configuration panel:
-
Prescaler (PSC):
7199(if APB1 clock is 72 MHz) -
Counter Period (ARR):
999
This gives an interrupt every 100 ms.
3. Generate Code
Click Project > Generate Code. Now move to main.c.
4. Enable Timer and Interrupt
In main.c:
5. Write Interrupt Callback Function
In stm32f1xx_it.c or stm32xx_it.c:
Now implement the callback in main.c:
Bare Metal (Register-Level) Example
In interrupt handler:
Debugging Tips
| Issue | Fix |
|---|---|
| Timer not counting | Check RCC clocks and prescaler |
| No interrupt | Check NVIC settings and UIE bit |
| Interrupt too fast/slow | Adjust PSC and ARR |
| ISR not executing | Confirm function signature and HAL usage |
Summary
| Step | Action |
|---|---|
| 1 | Configure timer (PSC, ARR) |
| 2 | Enable update interrupt |
| 3 | Start timer in interrupt mode |
| 4 | Write ISR or callback |
| 5 | Place time-dependent code inside ISR |

评论
发表评论