The project will cover the configuration and implementation of three distinct timer modes on the STM32 microcontroller using the HAL library. The project will include practical examples to demonstrate real-world applications for each mode.
In Periodic Interrupt mode , the timer generates an interrupt at a fixed time interval (e.g., every 100ms). This allows the microcontroller to execute specific tasks periodically without blocking the main loop, ideal for time-critical operations like sensor data polling or system monitoring.
In External Event Counter mode , the timer is configured to count digital pulses (events) received on a specific external pin. This mode is highly efficient for applications like measuring the frequency of a signal, counting revolutions of a motor using an encoder, or tracking the number of times a button is pressed.
In Output Compare mode , the timer is set to change the state of an output pin when its counter matches a predefined value. This is primarily used to generate precise digital waveforms, such as Pulse Width Modulation (PWM) for controlling servo motors, LED brightness, or generating specific tones and frequencies.
STM32CubeMX Configuration- Create new STM32F103C6 project
- Set system clock to 32MHz (HSI → PLL)
- Configure Timers:
- TIM3: Set Prescaler=1000-1, Counter Period=32000-1. Enable NVIC TIM3 global interrupt.
- TIM1: Set Clock Source to "ETR2 (PA0)". Set Counter Mode="Up", Prescaler=0, Counter Period=10.
- TIM2: Set Prescaler=3200-1, Period=1000-1. Configure Channel 2 and Channel 4 in "Output Compare Toggle Mode" with Pulse values of 200 and 400 respectively.
- GPIO configuration: Ensure PA0 (TIM1_ETR) is configured as input, and the timer output pins (e.g., PA1 for TIM2_CH2) are set to alternate function output.
- Configure USART1 as Asynchronous 9600 baude-rate
- Generate initialization code
- Open generated project
- Add application logic in
main.c
(e.g., start timers withHAL_TIM_Base_Start_IT(&htim3)
,HAL_TIM_OC_Start(&htim2, TIM_CHANNEL_2)
) - Implement the TIM3 periodic interrupt service routine (ISR) in
stm32f1xx_it.c
- Build and debug
- Add STM32F103C6 to schematic
- Connect test components: LEDs to the TIM2 output pins, a pulse generator or button to the TIM1 event input (PA0), and a virtual terminal for debugging.
- Load compiled .hex file
- Start simulation
If you have any questions or suggestions don't hesitate to leave a comment below
Comments