Introduction
In real-time applications using FreeRTOS on STM32 microcontrollers, precise timing is crucial for tasks like sensor sampling and motor control. This tutorial will guide you through using the TIM2 interrupt to create a precise 1ms periodic task in your FreeRTOS application.
Prerequisites
- Basic knowledge of C programming
- Familiarity with STM32 microcontrollers
- STM32CubeIDE or a similar development environment installed
- Basic understanding of FreeRTOS concepts
Parts/Tools
- STM32 development board (e.g., STM32F4 Discovery)
- USB to UART converter (if not built-in)
- STM32CubeMX
- STM32CubeIDE
Steps
- Create a new STM32 project:
- Open STM32CubeIDE and create a new STM32 project.
- Select your microcontroller or board (e.g., STM32F407VG).
- Configure TIM2:
- Open STM32CubeMX within the IDE.
- Select the “Timers” tab and enable TIM2.
- Set the Prescaler and Counter Period to achieve a 1ms tick rate.
- Enable the TIM2 interrupt in the NVIC settings.
// Assuming 84MHz clock TIM2->PSC = 84 - 1; // Prescaler TIM2->ARR = 1000 - 1; // 1ms period
- Generate the code:
- Click on “Project” and then “Generate Code”.
- Open the project in STM32CubeIDE.
- Implement the TIM2 interrupt handler:
- Open
stm32f4xx_it.c
and locate the TIM2 interrupt handler. - Add the following code to handle the TIM2 interrupt:
void TIM2_IRQHandler(void) { if (TIM2->SR & TIM_SR_UIF) { // Check update interrupt flag TIM2->SR &= ~TIM_SR_UIF; // Clear the flag BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Signal the periodic task xTaskNotifyFromISR(xTaskHandle, 0, eSetValueWithOverwrite, &xHigherPriorityTaskWoken); portYIELD_FROM_ISR(xHigherPriorityTaskWoken); } }
- Open
- Create a periodic task:
- Define your task function in your main file:
- Create the task in the main function:
void vTaskPeriodic(void *pvParameters) { for (;;) { ulTaskNotifyTake(pdTRUE, portMAX_DELAY); // Wait for notification // Execute periodic task code here } }
xTaskCreate(vTaskPeriodic, "PeriodicTask", configMINIMAL_STACK_SIZE, NULL, 1, &xTaskHandle);
- Start the scheduler:
- Add
vTaskStartScheduler();
to the main function to start FreeRTOS.
- Add
Troubleshooting
- Interrupt not firing: Check if TIM2 is correctly configured with the right prescaler and counter values.
- Task not executing: Ensure the task is created successfully and the scheduler is started.
- High CPU usage: Verify that the periodic task completes quickly and does not block.
- Incorrect timing: Use an oscilloscope or logic analyzer to verify timing accuracy.
Conclusion
By following this tutorial, you have successfully configured TIM2 on an STM32 microcontroller to generate precise 1ms periodic tasks in a FreeRTOS application. This setup is essential for applications requiring accurate timing and responsiveness.