microcontroller - STM32: Timer interrupt works immediately - Electrical Engineering Stack Exchange
c - How can I start and stop a timer on STM32? - Stack Overflow
HW timer configuration using FreeRTOS
Correct way of setting a 1μs timer on a STM32 MCU with HAL
Videos
I ran into this with an STM32F105. The STM32F1xx Standard Peripheral Library functions are a bit different than what you are using, but the idea should be the same.
Issuing the TIM_TimeBaseInit() function caused the TIM_SR_UIF flag to become set. I haven't gone back yet to figure out why. Once this bit is set, the interrupt will trigger as soon as it is enabled.
To fix it, after calling TIM_TimeBaseInit(), I immediately called TIM_ClearITPendingBit(). Then I would enable the interrupt with TIM_ITConfig(). This fixed the problem.
My complete initialization routine looks like this:
// Enable the peripheral clock
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE);
// Configure the timebase
TIM_TimeBaseInitStructure.TIM_Prescaler = 1;
TIM_TimeBaseInitStructure.TIM_Period = 35999;
TIM_TimeBaseInit(TIM5, &TIM_TimeBaseInitStructure);
// That last function caused the UIF flag to get set. Clear it.
TIM_ClearITPendingBit(TIM5, TIM_IT_Update);
// Configure so that the interrupt flag is only set upon overflow
TIM_UpdateRequestConfig(TIM5, TIM_UpdateSource_Regular);
// Enable the TIM5 Update Interrupt type
TIM_ITConfig(TIM5, TIM_IT_Update, ENABLE);
Based on the solution from programmersought.com
Clear TIM_SR_UIF flag before every HAL_TIM_Base_Start_IT() call
#define FIX_TIMER_TRIGGER(handle_ptr) (__HAL_TIM_CLEAR_FLAG(handle_ptr, TIM_SR_UIF))
...
void myfunc(){
FIX_TIMER_TRIGGER(&htim7);
HAL_TIM_Base_Start_IT(&htim7);
}
Tested on STM32F407 Discovery board.
I think “NVIC_DisableIRQ(TIM7_IRQn);” just disable the timer's interrupt but not stop the timer. You may need: "TIM_Cmd(TIM7, DISABLE);" instead of “NVIC_DisableIRQ(TIM7_IRQn);”
Using [HAL][1], start:
HAL_TIM_Base_Start(&htim);
HAL_TIM_Base_Start_IT(&htim);
Stop:
HAL_TIM_Base_Stop(&htim);
HAL_TIM_Base_Stop_IT(&htim);
Where _IT is for timer interrupt mode. And you can reconfigure timer after stopping it.
[1]: http://www.disca.upv.es/aperles/arm_cortex_m3/llibre/st/STM32F439xx_User_Manual/stm32f4xx__hal__tim_8c.html