Timer Configuration & Interrupts
1. Introduction to STM32 Timers
Timers are one of the most important peripherals in STM32 microcontrollers. They are used for generating delays, PWM signals, measuring time intervals, handling interrupts, generating periodic events, motor control, communication timing, and real-time embedded applications.
STM32 timers are highly flexible and powerful, supporting advanced features such as periodic interrupts, PWM generation, input capture, output compare, encoder interface, one-pulse mode, dead-time insertion, and DMA triggering.
Common STM32 timer applications include:
- LED blinking
- PWM motor control
- Frequency measurement
- Sensor timing
- Real-time scheduling
- Servo control
- RTOS tick generation
2. Why Timers are Important
Timers provide precise timing independent of CPU execution. When hardware manages timing, the CPU can perform application tasks, increasing system efficiency.
- Accurate timing with microsecond resolution
- Reduced CPU load for periodic operations
- Real-time behavior for deterministic systems
- Hardware event generation and synchronization
3. STM32 Timer Types
STM32 MCUs contain multiple timer categories optimized for different applications.
| Timer Type | Purpose |
|---|---|
| Basic Timers | Simple timing and waveform generation |
| General Purpose Timers | PWM, interrupts, input capture, output compare |
| Advanced Timers | Motor control, complementary outputs, dead-time insertion |
| Low Power Timers | Low-energy timing in sleep modes |
| Watchdog Timers | System recovery and fault detection |
4. Common STM32 Timers
On an STM32F407, timer peripherals are grouped into:
- TIM1 and TIM8: Advanced timers with complementary outputs
- TIM2–TIM5: General-purpose timers for PWM, capture, compare, and interrupts
- TIM6 and TIM7: Basic timers often used as time bases
5. Timer Clock Source
Timers use internal or external clock sources. They can be driven by:
- Internal APB clock
- External trigger input
- External pin input
6. Timer Counter Concept
A timer counts clock pulses. When the counter reaches a predefined value, an event occurs: overflow, interrupt, PWM update, or output compare signal.
- Overflow occurs when the counter passes ARR
- Interrupt can trigger at each update event
- PWM outputs change according to CCR values
- Hardware events can be generated to trigger other peripherals
7. Timer Registers
Key STM32 timer registers include:
- PSC - Prescaler
- ARR - Auto-reload register
- CNT - Counter value
- CCRn - Capture/compare registers
- DIER - Interrupt enable register
- SR - Status register
8. Timer Prescaler
The prescaler divides the input clock frequency, slowing the timer counter.
9. Auto Reload Register (ARR)
ARR defines the maximum counter value. When the counter reaches ARR, the timer resets and generates an update event.
- Defines period for periodic interrupts
- Determines PWM frequency
- Used with one-pulse mode for pulse length
10. Timer Frequency Calculation
Timer overflow frequency is determined by the timer clock and ARR:
11. STM32 Timer Modes
STM32 timers can be configured in several counting modes:
- Up counter: standard counting from 0 to ARR
- Down counter: reverse counting from ARR to 0
- Center-aligned: useful for motor control and PWM with reduced harmonics
- One-pulse: generate a single pulse and stop automatically
12. Timer Interrupts
Timer interrupts are used for periodic tasks, RTOS scheduling, sensor sampling, and software timers.
- Update interrupt when counter overflows
- Capture/compare interrupts for output compare and input capture
- Trigger interrupts for chained peripheral events
13. STM32 Interrupt System
STM32 uses the Nested Vectored Interrupt Controller (NVIC) to manage interrupts.
- Interrupt prioritization
- Nested interrupts
- Fast interrupt response with minimal latency
14. Creating Timer Project in STM32CubeIDE
Follow these steps to create a timer-based STM32CubeIDE project:
- Open STM32CubeIDE and create a new STM32 project.
- Select your target MCU, such as STM32F407VG.
- Enable TIM2 in the Pinout & Configuration tab.
- Set the timer clock source to Internal Clock.
- Configure Prescaler and Counter Period parameters.
- Enable the TIM2 global interrupt in NVIC settings.
15. Timer Initialization Code
CubeMX generates HAL initialization code similar to this:
16. Starting Timer with Interrupt
Start the timer and enable periodic interrupts using:
This begins timer counting and allows update events to generate interrupts.
17. Timer Interrupt Callback
HAL provides a callback function called when the timer elapses:
18. Understanding Timer Interrupt Flow
The interrupt workflow is:
19. Interrupt Service Routine (ISR)
STM32CubeIDE also generates the ISR that forwards the interrupt to HAL:
20. LED Blink Using Timer Interrupt
Timer interrupts are ideal for blinking LEDs without blocking the CPU. Configure TIM2 to toggle a GPIO pin every second.
- No blocking `HAL_Delay()` required
- Other tasks can run concurrently
- Reliable timing independent of program flow
21. Timer Delay vs HAL_Delay
| HAL_Delay | Hardware Timer |
|---|---|
| Blocking | Non-blocking |
| CPU waits | CPU free for other work |
| Simple | Efficient and professional |
22. PWM Generation Using Timers
Timers generate PWM signals for motor control, LED dimming, and servo control.
- Timer compare output drives PWM output pins
- Pulse width is set by CCR values
- Period is set by ARR
23. PWM Configuration Example
24. PWM Duty Cycle
Duty cycle determines how long the PWM signal stays high:
25. Changing PWM Duty Cycle
26. Input Capture Mode
Input capture measures frequency, pulse width, and external signals using a timer channel.
- Capture the counter value on external edge
- Calculate period from captured values
- Useful for RPM measurement, ultrasonic sensors, and signal analysis
27. Input Capture Example
28. Output Compare Mode
Output compare generates actions when the timer matches a compare value. It is used for waveform generation and precise timing events.
- Trigger external pins
- Generate periodic toggles
- Create timed output signals
29. Encoder Interface Mode
STM32 timers can interface directly with rotary encoders for motor position and speed control.
- Count quadrature encoder pulses
- Determine direction and speed
- Common in robotics, CNC, and motion systems
30. One Pulse Mode
One-pulse mode generates a single pulse automatically and then stops.
- Used for trigger circuits
- Useful in ultrasonic ranging and one-shot drives
- Good for precise control of single events
31. Advanced Timers
Advanced timers support complementary PWM, dead-time insertion, break inputs, and motor control.
- Complementary outputs for H-bridges
- Hardware dead-time between high and low side switches
- Break input for fault protection
32. Dead Time Insertion
Dead time prevents simultaneous conduction of MOSFETs in half-bridge circuits. Proper dead time avoids shoot-through and reduces power losses.
- Crucial for motor drives and inverters
- Configured on advanced timers such as TIM1 and TIM8
- Ensures safe switching of complementary outputs
33. Timer Synchronization
Multiple timers can be synchronized for multi-phase PWM, motor drives, or complex timing systems.
- Master-slave timer relationships
- Coordinated capture and compare events
- Useful for multi-phase converters and synchronized sampling
34. DMA with Timers
Timers can trigger DMA transfers to move data without CPU intervention.
- Reduces CPU usage for waveform generation
- Enables high-speed data capture
- Ideal for digital-to-analog conversion and signal generation
35. Real-Time Clock (RTC)
The RTC provides accurate date/time tracking, calendar support, and alarm generation.
- Used for data logging
- Enables scheduled wake-ups
- Typical in IoT gateways and time-stamped applications
36. Watchdog Timers
Watchdog timers reset the system if software hangs or fails to service the watchdog.
| Watchdog | Description |
|---|---|
| Independent Watchdog | Runs from its own clock and recovers from software faults |
| Window Watchdog | Enforces a timing window for refresh operations |
37. Timer-Based Applications
- LED blinking using periodic interrupts
- Motor control with PWM and encoder feedback
- Servo control with precise pulse timing
- Frequency counting with input capture
- RTOS tick generation and software timers
38. Interrupt Priorities
NVIC supports interrupt priority levels, which are essential for real-time systems and RTOS integration.
- Assign higher priority to critical timers
- Lower priority for non-critical housekeeping tasks
- Avoid priority inversion with careful design
39. Nested Interrupts
Nested interrupts allow higher-priority handlers to preempt lower-priority ones, improving responsiveness for urgent events.
- Supports fast response to critical sensors
- Maintains deterministic behavior when used correctly
40. Timer Interrupt Best Practices
- Keep ISRs short and efficient
- Avoid blocking functions inside interrupts
- Use `volatile` for shared variables updated in ISRs
- Minimize processing inside interrupt context
41. Common Timer Problems
| Problem | Cause |
|---|---|
| Wrong timing | Incorrect prescaler or ARR values |
| Interrupt not working | NVIC not enabled or DIER bit missing |
| PWM incorrect | Wrong CCR or channel configuration |
| Timer not running | Clock disabled or `HAL_TIM_Base_Start()` not called |
42. Debugging Timer Applications
- Use an oscilloscope to verify PWM frequency and pulse width
- Use a logic analyzer for capture edge timing
- Toggle GPIO pins in ISRs to trace execution timing
- Use STM32CubeIDE debugger to inspect timer registers
43. Measuring Frequency Using Timer
Frequency is the inverse of period:
Use input capture to measure two consecutive edges and compute signal frequency.
44. STM32 HAL Timer APIs
Common HAL APIs for timer control include:
- HAL_TIM_Base_Start() - Start base timer
- HAL_TIM_Base_Start_IT() - Start timer with interrupts
- HAL_TIM_PWM_Start() - Start PWM output
- HAL_TIM_IC_Start() - Start input capture
- HAL_TIM_Encoder_Start() - Start encoder interface
45. Timer Applications in Robotics
Timers are heavily used in robotics for motor PWM, servo control, encoder reading, and periodic sensor sampling.
- Precise motor speed control with PWM
- Position control with encoder interface
- Real-time sensor polling
46. Industrial Applications
Timers are used in PLC systems, automation controllers, power electronics, and CNC machines.
- Precise timing for machine cycles
- Pulse generation for stepper drives
- Interlock and safety timing
47. Timer Integration with RTOS
RTOS uses timers for task scheduling, delays, and timeouts. Hardware timers can provide system ticks or signal software timer callbacks.
- Use timer interrupts to update RTOS tick counts
- Implement software timers on top of hardware timers
- Assign priorities for timer-based tasks
48. Power Optimization with Timers
Timers help reduce CPU load and support low-power operation by allowing sleep modes between timed events.
- Wake up periodically from sleep mode
- Keep the CPU idle while timer hardware runs
- Use low-power timer modes for energy efficiency
49. Best Practices for STM32 Timer Design
- Use hardware timers instead of software delays
- Select proper prescaler and ARR values for accuracy
- Use interrupts efficiently and keep ISRs short
- Use DMA for high-speed signal generation or capture
50. Conclusion
STM32 timer peripherals are among the most powerful features of STM32 microcontrollers. They enable accurate timing, efficient interrupt handling, PWM generation, motor control, frequency measurement, and real-time embedded applications.
By understanding timer configuration, prescaler calculations, interrupt handling, PWM generation, input capture, and advanced timer features, developers can design highly reliable and efficient embedded systems for robotics, industrial automation, IoT devices, motor control systems, and real-time applications.
Mastering STM32 timers and interrupts is an essential skill for embedded systems engineers working with ARM Cortex-M microcontrollers and advanced real-time systems.