AnsweredAssumed Answered

Premature TIM2 interrupt happening immediately on timer start

Question asked by Todd Phelps on Jan 15, 2018
Latest reply on Jan 17, 2018 by Todd Phelps

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 = 976.67 Hz
   TIM2 Period range = 0.001 sec - 67.1 sec
GPIO_WriteLow(GPIOD, GPIO_PIN_2); // For testing with logic analyzer
TIM2_TimeBaseInit( TIM2_PRESCALER_16384, timer_period);
Interrupt handler from stm8s_it.c:
     GPIO_WriteHigh(GPIOD, GPIO_PIN_2);
     time_event();  // User app function - change displayed value
     GPIO_WriteLow(GPIOD, GPIO_PIN_2);
 /* Clear Interrupt Pending bit */
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!