2020-02-11 10:31 PM
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?
2020-02-11 10:55 PM
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.
2020-02-11 11:27 PM
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.
2020-02-11 11:50 PM
Sorry, forget my previous post.
How can you see time_stamp growing? Stopping the program in the debugger?
2020-02-12 12:07 AM
Yes. I have a Locals window, every time I stop at the break point I see the updated value.
2020-02-12 12:26 AM
And if you checked the hardware registers as well, you would see the timer running (CNT register changing) while program execution is stopped.
Depending on the MCU model there might be a way to stop the timer while the program is stopped by the debugger. It's in one of the last chapters of the reference manual.
2020-02-12 12:59 AM
Well. Probably the timer not synchronized with a debugger. I see no other logical explanation.