How to correctly chain 3 timers and fix the overflow and wraparound issues.
I have to implement a lifetime counter with microseconds granularity using a STM32L432KC to control an AFBR-S50 sensor. The timer has to count "forever" and this board only has 1 32bit timer, so this timer is for the seconds, i think is the only way. So this timer could count several years. Problem is i also need microseconds.
In the sensor documentation they chain 2 32bits counters, but i need three. one 16 bit for microseconds, one 16 bit for miliseconds and 1 32bits for the seconds. The prescaler for the first one is "SystemCoreClock / 1000000 -1" and the counter period is "1000", the second is chained to this, prescaler is 0 and counter period is also "1000". And the third is chained to the second, prescaler also 0 and counter period 0xffff.
The first issue with this is i have done a test waiting for 5 minutes and comparing the result with mi cronograph and it has too much delay. The MCU has counter 36 seconds (in 5 minutes) more than the cronograph. How can be this possible?
The second problem is with the wraparound issue of the counters. to resolve this, they read the timers in a loop and iterate the loop while in two consecutive read of the timer, the first is bigger than the second. So the timer goes up direction, the second read always has to be bigger than the first except when counter resets, so thats fine.
I have two possible wraparounds so i added other condition to the loop. second read of both timers have be bigger than first. I think this is ok, but not completely sure.
The main issue is program is failing because the calc of total microseconds for which i use this formula:
ltc= msTimerValue * 1000 + usTimerValue
exceeds 999.999 and if both timers has counter periods of 1000 i dont know how this could happen. The max value of both timers should be 999.
I'm really new to electronics and this kind of controllers, and dont have a lot of experience with glitches and other things.
I really appreciate some help.
Thanks