Skip to main content
Erenburg.Evgeny
Associate III
February 12, 2020
Question

Problem with a timer counter.

  • February 12, 2020
  • 1 reply
  • 854 views

I set a timer to count 500us ticks

TIM_InitStruct.Prescaler = (uint16_t)40000-1; //SYSCLK = 80Mhz – 80Mhz/40000 = 500us
TIM_InitStruct.CounterMode = LL_TIM_COUNTERMODE_UP;
TIM_InitStruct.Autoreload = 0xFFFFFFFF; //TIM2 – 32-bit counter
TIM_InitStruct.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1;
TIM_InitStruct.RepetitionCounter = (uint8_t)0x00;
 
LL_TIM_Init(TIM2, &TIM_InitStruct);

I get the counter in milliseconds

uint32_t TIM_GetTimeStamp_ms(TIM_TypeDef * TIMx)
{
 //timer 32-bit
 volatile uint32_t time_stamp = TIMx->CNT; 
 
 //conter counts in 500us ticks so - us/2 = ms
 timer_counter = time_stamp >> 1; 
 
 //global
 return timer_counter;
}

I test it

while (1)
{
 ts1 = TIM_GetTimeStamp_ms(TIM2);
 Delay_ms(100);
 ts2 = TIM_GetTimeStamp_ms(TIM2); 
 
 time_stamp = ts2 - ts1;
}

And I see time_stamp = 100 – so far so good.

Now I test it this way

while (1)
{
 ts1 = TIM_GetTimeStamp_ms(TIM2);
 
 if (ts1 >= script_cycle)
 {
 time_stamp = ts1 - script_cycle;
 script_cycle = ts1 + 100;
 }
}

And I see time_stamp is growing up. Do I miss something?

This topic has been closed for replies.

1 reply

berendi
Principal
February 12, 2020

The contents of the while loop take significantly less than 100 ms to complete, so the if branch is never taken after the first cycle.

time_stamp is global, it gets incremented inside the TIM_GetTimeStamp_ms() function.

Erenburg.Evgeny
Associate III
February 12, 2020

sorry. I fail to understand. time_stamp is a variable, just to get delta between two samples. I accept there is some error but why it's growing ?

Do you mean time_stamp inside the function? It's a local variable.

berendi
Principal
February 12, 2020

Sorry, forget my previous post.

How can you see time_stamp growing? Stopping the program in the debugger?