delay function based on timer, overflow safe?
Hello Everybody,
I was thinking about a flexible way to implement a µs or ms delay function with a free running timer as tick source. One of the biggest problems that comes to my mind is the overflow problem when the timer wraps around, so that some classical approaches, I have found on the Internet would lead to false behaviour.
I have thouight of the following solution for the problem and would like some feedback from the community:
I assumed using a timer with a 16-Bit counter but you could also use a 32-Bit counter.
/**
* @brief µs delay function based on Timer15.
* Maximum 65536µs delay possible.
* @param ucnt µs to delay
* @return none
*/
void delay_TIM15(uint16_t ucnt)
{
uint16_t start = TIM15->CNT;
while((start + ucnt) > tim15_tick());
}#define tim15_tick() (TIM15->CNT)in my solution an overflow or timer wrap around would be no problem since the sum of start + ucnt is stored inside an uint16_t variable and would do the same wrap around as the counter. Or am I wrong?
best regards
Benjamin