Question
2 mS timer immideately fires interrupt on a first run
Posted on August 10, 2016 at 04:53
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:
/***************************************************************** Start_tim6 **
** Name : Start_tim6
** Returns : none
** Args : none
** Description : timer 6 - base milliseconds timer
** Notes :
*******************************************************************************/
void Start_tim6(void)
{
TIM6->CNT = 0;
TIM6->ARR = 2000; // in mS - not needed, just in case
TIM6->SR &= ~0x0001; /* clear update flag */
/* start timer */
TIM6->CR1 |= 0x0001;
if (first_run != 0)
{
TIM6->SR &= ~0x0001;
first_run = 0;
}
__NOP();
} /* 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