I need to implement a delay function with a hardware timer. The timer value is incremented each millisecond.
The usual approach is to use the width of the timer register and use the modulo behavior corresponding to the
volatile int TimerReg;
void Delay(int amount)
{
int start = TimerReg;
int elapsed;
do
{
eleapsed = TimerReg - start;
} while (elapsed < amount);
}
This works when the TimerReg has the width of int. The difference now - start
is a steadily increasing value in that case.
But when the width of TimerReg is less than the width of int, or (as in my case) the timer counts only from 0..1000, you get a problem when the timer wraps from 999 over 1000 to 0.
What is a good approach to use such a timer? I would like to avoid the modulo operation because this is expensive on the microcontroller.
The division module is not included in the microcontroller code yet.
I figured it out. It's done implicitly when the width of the timer register is identical to the width of an int. It's sufficient to add the number circle of the timer to the elapsed
value, when it is negative, to get it in the valid range.
volatile int TimerReg; /* Value range: 0..999 */
const int TimerMaxValue = 999;
void Delay(int amount)
{
int start = TimerReg;
int elapsed;
do
{
elapsed = TimerReg - start;
if (elapsed < 0)
elapsed += (TimerMaxValue + 1);
} while (elapsed < amount);
}