AnsweredAssumed Answered

2 mS timer immideately fires interrupt on a first run

Question asked by palitsky.gennady on Aug 10, 2016
Latest reply on Aug 19, 2016 by palitsky.gennady
I am using Timer6 on STM32L051 as a base 2 S timer with overflow interrupt.
By some reason on a first run interrupt fires immediately,
and I can't figure out the reason for this behavior.

Here are my initialization and timer start functions.
Initialization:
/**************************************************************** Timer6_init **
** Name        : Timer6_init()
** Returns     : none
** Args        : none
** Description : configure timer6 as a base timer
** Notes       : auto-reload register is loaded with amount for 2S
**               Timer6 is fed by 16 MHz clock
**               timer is used as upcounter (DIR=0).
**               Only overflow generates an update event (URS=1),
**               update event generates interrupt
*******************************************************************************/
void Timer6_init(void)
{
  /* enable TIM6 clock */
  RCC->APB1ENR |= RCC_APB1ENR_TIM6EN; /* init timer 6 */
  /* time base:
   TIM6_Prescaler = 15999 (count frequency is 1 KHz)
   TIM_ClockDivision = 0
   TIM_CounterMode = 0 (up counter */
  /* update on overflow only */
  /* time base is 1mS - 1 KHz */
  TIM6->PSC = 15999;
  TIM6->ARR = 2000;  // in mS
 TIM6->SR &= ~0x0001;
 TIM6->CR1 |= 0x0004;    // update source regular
  /* enable overflow interrupt */  
  TIM6->DIER |= 0x0001;
     
} /* end Timer6_init() */

Timer start:
01./***************************************************************** Start_tim6 **
02.** Name        : Start_tim6
03.** Returns     : none
04.** Args        : none
05.** Description : timer 6 - base milliseconds timer
06.** Notes       :
07.*******************************************************************************/
08.void Start_tim6(void)
09.{
10.  TIM6->CNT = 0;
11.  TIM6->ARR = 2000;  // in mS - not needed, just in case  
12. TIM6->SR &= ~0x0001; /* clear update flag */
13.  /* start timer */
14.  TIM6->CR1 |= 0x0001;
15.  if (first_run != 0)
16. {  
17.    TIM6->SR &= ~0x0001;
18.  first_run = 0;
19. }  
20.  __NOP();
21.         
22.} /* end Start_tim6() */

When timer runs for the first time, interrupt is fired immediately.
I tried to set breakpoints in a timer start routine to see when the overflow flag is set.
In the above  Start_tim6 snippet it worked as follows:
- Breakpoint at line 14 - SR is 0,
- Breakpoint at line15 (after timer start) - SR is 1.

I tried to clear flag on first run (lines 15-19). Flag is not cleared, it stays set. And, of coarse, interrupt is fired.

This happens only on a first run. Every time after that interrupt occurs after 2 S.

I wonder what could I overlook.
Please help me to figure it out.

Thank you,
Gennady   

Outcomes