Runover when not reach the limit

Hello everyone,

My variable had a Runover even before it reached its range.

Currently, I am working with timer 2 with a frequency of 90MHz. When I retrieved the current time by __HAL_TIM_GET_COUNTER() and printed it by printf("receive_time: %lu\n", (unsigned long)receive_time), the maximum the receive_time get is 16 bits although I declared it as 32 bits. I observed the printed value and it never exceeded 2^16 -1.
I also tried to print with printf("%" PRIu32 "\n",a); but it also returned the same.
I had another 32-bit variable send_time which is used later to subtract with receive_time. However, it gave me something in the order of 2*10^9 (2147482170 for example) besides some common values.

I want to ask what happen and if I do something wrong. If everything is correct, is there any way to handle the rollover besides having 2 timers starting at different times?

The code is here:

Radio::radio.tx_buf[0] = seq++;  /* set payload */
    printf("send a ready message\r\n");
    Radio::Send(1, 0, 0, 0);   /* begin transmission */
    send_time = __HAL_TIM_GET_COUNTER(&htim2);
.
.
.
if (Radio::radio.rx_buf[0] == 100)
    {
        receive_time = __HAL_TIM_GET_COUNTER(&htim2);
        printf("receive_time: %lu\n", (unsigned long)receive_time);
        printf("send_time: %lu\n", (unsigned long)send_time);
        time_difference = (receive_time - send_time)/2;
        printf("time_difference: %lu\n", (unsigned long)time_difference);
        uint32_t distance = time_difference * 10 / 3;
        printf("Distance: %lu\n", (unsigned long)distance);
    }```

Thank you in advanced,
Huy Nguyen.

What processor are you working with? Maybe TIM2 on this processor is only 16 bits

Hello @MultipleMonomials
Sorry, I forgot to mention that. The board I am using is STM32446RE and before using timer 2, I checked the manual in the datasheet as below:


And the Counter of timer 2 can be up to 32 bits.

That is why I got confused.

Is it possible the max count value (ARR) for TIM2 is set to 65536?

I just did some research and indeed that is possible too. I will check, modify it, and update.

Thank you for your response.

Indeed it is the ARR value. I just set the Period (ARR) value to be maximum and now the counter can return 32-bit values.

1 Like