Skip to main content
Graduate
January 3, 2025
Solved

Handling Multiple Timer Interrupts with HAL_TIM_PeriodElapsedCallback() in STM32L562CET6

  • January 3, 2025
  • 3 replies
  • 1170 views

Hello ,

I am working on a project with the STM32L562CET6 microcontroller and have encountered an issue with the timer interrupt callback function.

   1. I configured TIM6 as the clock source for the microcontroller. Consequently, the HAL_TIM_PeriodElapsedCallback() function is automatically triggered whenever the TIM6 interrupt occurs.

   2. Now, I have configured TIM2 for a different purpose, but I noticed that when the TIM2 interrupt occurs, the same HAL_TIM_PeriodElapsedCallback() is triggered.

Since the HAL_TIM_PeriodElapsedCallback() is defined with the weak attribute, I understand that I can redefine it in my user code. However, this causes conflicts when multiple timers (like TIM6 and TIM2) trigger this callback.

Questions:

  1. Is there a way to alias or redirect the HAL_TIM_PeriodElapsedCallback() to separate functions for different timers (e.g., one for TIM6 and another for TIM2)?
  2. Is there any other specific callback function available for timers in STM32 HAL that can help separate the interrupt handling for different timers?
   3. What is the recommended approach to handle multiple timers efficiently without such conflicts?
Thank you !

    This topic has been closed for replies.
    Best answer by Saket_Om

    Hello @Sankar_Eswaran 

    You can configure the register callback to call the user defined callback function.

     

    HAL_TIM_RegisterCallback(&htim2, HAL_TIM_PERIOD_ELAPSED_CB_ID, User_TIM2PeriodElapsedCallback);
    HAL_TIM_RegisterCallback(&htim6, HAL_TIM_PERIOD_ELAPSED_CB_ID, User_TIM6PeriodElapsedCallback);
    

    To use this feature, you should set the flag USE_HAL_TIM_REGISTER_CALLBACKS to 1.

     

    3 replies

    ST Employee
    January 3, 2025

    Hello @Sankar_Eswaran

    Generally, this is how we handle multiple interrupts: 

    void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
    {
    	if (htim->Instance == TIM2) {
    		code
    	}
    	if (htim->Instance == TIM6) {
    		code
    	}
    }

     

    Saket_OmAnswer
    Technical Moderator
    January 3, 2025

    Hello @Sankar_Eswaran 

    You can configure the register callback to call the user defined callback function.

     

    HAL_TIM_RegisterCallback(&htim2, HAL_TIM_PERIOD_ELAPSED_CB_ID, User_TIM2PeriodElapsedCallback);
    HAL_TIM_RegisterCallback(&htim6, HAL_TIM_PERIOD_ELAPSED_CB_ID, User_TIM6PeriodElapsedCallback);
    

    To use this feature, you should set the flag USE_HAL_TIM_REGISTER_CALLBACKS to 1.

     

    Graduate
    January 6, 2025

    Thank you...