Timer as milliseconds counter

1

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

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?

stm32
asked on Stack Overflow Feb 12, 2020 by john7

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0