I have in a project of mine a small delay function that I have written myself by making use of a timer peripheral of my MCU:
static void delay100Us(void)
{
uint_64 ctr = TIMER_read(0); //10ns resolution
uint_64 ctr2 = ctr + 10000;
while(ctr <= ctr2) //wait 100 microseconds(10000)
{
ctr = TIMER_read(0);
}
}
The counter is a freerunning hw counter with 10ns resolution so I wrote that function as to give approximately 100us delay. I think this should work in principle however there could be the situation where the timer is less than 10000 from overflowing and so ctr2 will get assigned a value which is more than ctr can actually reach and therefore I would end up getting stuck into an infinite loop.
I need to generate a delay using this timer in my project so I need to somehow make sure that I always get the same delay(100us) while at the same time protect myself from getting stuck there.
Is there any way I can do this or is this just a limitation that I can't get passed?
Thank you!
Edit:
ctr_start = TimerRead(); //get initial value for the counter
interval = TimerRead() - ctr_start;
while(interval <= 10000)
{
interval = ( TimerRead() - ctr_start + countersize ) % countersize;
}
Where countersize = 0xFFFFFFFFFFFFFFFF;
interval = (timer - ctr + countersize) % countersizeIf it's a 64-bit counter theninterval = timer - ctr. Do the arithmetic before checking the interval (to allow the arithmetic to wrap). - Weather Vane0xFFFFFFFFFFFFFFFF. IMO it's best to use a free-run counter with a total period in excess of the max you'll ever need. If the counter is 64-bit it is simple. Mark the start value, then compute the elapsed interval and compare it. Use>=so you don't need to catch an exact value. If it is a 32-bit counter then useuint32_ttypes, etc. - Weather Vane