Premature TIM2 interrupt happening immediately on timer start
Hi folks,
I'm having an issue with the TIM2 interrupt firing as soon as I start the timer rather than when the timer overflows -- was hoping someone could help me. I've set up TIM2 to interrupt once every 860 milliseconds or so, but am finding that the timer immediately interrupts about 75 microseconds after I activate it. I'm using the ST peripheral driver library for the STM8S on the STM8s Value Line Discovery board with IAR as the compiler.
Initialization code (slightly modified for clarity):
Note, timer_period = 836
void timebase_init(uint16_t timer_period)
{ /* Set the step time TIM2 Clock = 16 Mhz TIM2 Prescaler = 16384 TIM2 Counter Clock = 16 MHz / 16384 = 967 Hz TIM2 Period range = 0.001 sec - 1 sec */GPIO_WriteLow(GPIOD, GPIO_PIN_2); // For testing with logic analyzer
TIM2_DeInit();
TIM2_TimeBaseInit( TIM2_PRESCALER_16384, timer_period); TIM2_ITConfig( TIM2_IT_UPDATE, ENABLE ); TIM2_Cmd( ENABLE );}
Interrupt handler from stm8s_it.c:
INTERRUPT_HANDLER(TIM2_UPD_OVF_BRK_IRQHandler, 13)
{ GPIO_WriteHigh(GPIOD, GPIO_PIN_2);time_event(); // User app function - change displayed value
GPIO_WriteLow(GPIOD, GPIO_PIN_2);
} /* Clear Interrupt Pending bit */ TIM2_ClearITPendingBit(TIM2_IT_UPDATE);}
I've set up the interrupt handler to toggle a debug pin when it runs. The timer period is set up for approx. 0.86 seconds, however the interrupt happens 75 microseconds after I enter the function that sets up the timer:
After this, it happens every 0.86 seconds as expected (can't see the above pulse in the following image, which is zoomed out a lot):
If I put a breakpoint on the entry to the interrupt handler, the first time it hits (the undesired interrupt), IAR reports the TIM2 registers as this:
I've seen a couple references saying the timer update will cause an interrupt when you change some of the timer's registers, but it seem silly to me that if you set a timer it goes off as soon as you press start rather than at the time you've set the timer for.
Thanks for any help or insight!
