3

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.

Edit: The division module is not included in the microcontroller code yet.

5
  • 2
    Worrying about expense when you delay code doesn't make much sense. Nor does such a timer. Apr 27, 2012 at 12:40
  • If your device is portable, avoid long busy loop delays, because those busy loops may drain batteries faster than other ways.
    – SKi
    Apr 27, 2012 at 12:54
  • @User1 Only if the alternative is to put the MCU in a power-saving sleep mode and have the timer to wake it up. Otherwise, delay loops consume as much power as running any other code.
    – Lundin
    Apr 27, 2012 at 13:48
  • @HansPassant You're right, the CPU runs at 100%. But the modulo division is a larger block of code (not included yet). Further you have a an additional up to the time that the calculation takes for processing.
    – harper
    Apr 27, 2012 at 14:17
  • what microcontroller are you using, specifically?
    – old_timer
    Apr 28, 2012 at 16:41

6 Answers 6

3

How about something like this:

volatile int TimerReg;

void Delay(int amount)
{
  int start = TimerReg;
  int elapsed;
  int rolled_over = 0;
  int last_time = start;

  do
  {
    int timer_reg = TimerReg;
    // Check for rollover
    if(last_time > timer_reg) {
      // ROLLOVER_INTERVAL is the magic number at which the timer rolls over to 0
      rolled_over += ROLLOVER_INTERVAL - start;
      start = 0;
    }
    last_time = timer_reg;
    if(rolled_over == 0) {
      elapsed = timer_reg - start;
    } else {
      elapsed = timer_reg + rolled_over;
    }
  } while (elapsed < amount);
}

Granted, there's two more if-tests, and two more variables, so there's probably a more efficient solution.

4
  • In addition to leaving out the secret sauce of what ROLLOVER_INTERAVAL should be (it can't be a simple number macro - it needs to depend on start), this answer has the more serious problem of reading TimerReg several times - it could be different each time it's read which would lead to difficult to debug problems. Apr 27, 2012 at 17:46
  • There, fixed it (by introducing another variable, but still, good catch), and made the ROLLOVER_INTERVAL magic number more clear, it's the limit at which the timer rolls over to 0. Apr 27, 2012 at 18:20
  • 1
    I still don't think the rollover handling is right. Assuming the timer goes to 0 after 999 If you start at 998 then rollover to 0 the elapsed time calculation will be 999 when it should be 2. Apr 27, 2012 at 18:37
  • Another good catch, I also wasn't updating last_time, so elapsed would grow enormously fast after the first rollover. Apr 27, 2012 at 18:57
1

Who controls that timer rollover? If you could change it for example to 0xFFF rolls over to 0x000 instead of 999 to 000 then you could use a simple mask

elapsed = (TimerReg - start)&0xFFF;

Which is very cheap

elapsed = (TimerReg - start)%1000; 

is where you are at now which is very expensive.

the alternative which is not as bad is What Edvard posted, basically check for the roll over

nowtime = TimerReg;
if(nowtime < start)
{
   elapsed = (1000 - start) + nowtime;
}
else
{
   elapsed = nowtime - start;
}

All of the above assumes an upcounting timer.

Microcontrollers often contain more than one timer, it is nice to leave one that counts to max count (0xFFFF or 0xFFFFFFFF or whatever) and rolls over to zero, so that you can use now - last anytime you want to measure time (shorter than a rollovers worth of time).

3
  • The rollover is by hardwared design.
    – harper
    Apr 27, 2012 at 14:19
  • I mean what software has programmed the timer to rollover at 999 or 1000? Is that software you have control over or software that you cannot touch? Is there a reason for that timer to be set that way or can you change it?
    – old_timer
    Apr 27, 2012 at 14:57
  • The only software that defined the max. value was the circuit desgined of the chip developer. It's a microsecond counter the rolls over from 999 to 0 each millisecond. Nothing can be programmed here.
    – harper
    Apr 28, 2012 at 16:08
0

If you have a real hardware timer you do like this:

start_timer();
while ( (timer_flag_register & bitmask)==0 )
{
  do_stuff();
}

where start_timer() sets a hardware timer counter to [main timer counter] + [delay time]. When the time has elapsed, the hardware sets a flag (or calls interrupt service routine). Pretty much every hardware timer on every MCU works in this manner.

4
  • The microcontroller has as real set of hardware register. The microseconds register is the reqister in question.
    – harper
    Apr 27, 2012 at 14:21
  • @harper Then use its flagging mechanism.
    – Lundin
    Apr 27, 2012 at 19:14
  • not all timers have that, and it sounds like the poster doesnt have control over the rollover value, nor stop/start of the timer. with control now-start on a freerunning timer is simple and clean (and more accurate).
    – old_timer
    Apr 28, 2012 at 4:04
  • Additonally the hardware register is not a programmable timer. It can't be started or stopped. It's just counting microseconds.
    – harper
    Apr 28, 2012 at 16:07
0

You can use an interrupt when the timer reach its value to increment a global counter (for every 1000 ms for example).

0

I figured it out. It's done implicitely when the width of the timer register is identical to the width of int. It's suffcient to add the number circle of the timer to the elapsed value, when it is negativ 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 
    { 
        eleapsed = TimerReg - start;
        if (elapsed < 0) eplapsed += (TimerMaxValue + 1);
    } while (elapsed < amount); 
} 
2
  • Isn't this an infinite loop if amount > TimerMaxValue? Apr 27, 2012 at 18:25
  • Yes. The function can only handle any value that is less then one timer turn around. But because its a function that stalls at full CPU load it should be used only for small values. It's part of the contract with the caller.
    – harper
    Apr 28, 2012 at 16:05
-1

Your 1ms timer (Nyquist frequency) is much slower than your polling code. Hence, you can simply use the uqual operator '=':

volatile int TimerReg;

void Delay(int amount)
{
    int future = TimerReg + amount;

    while (TimerReg != future);
}

This is an elegant solution, in my humble opinion, but it only works if 'TimerReg' is free to run over its full range, e.g. '0xffff'.

1
  • -1 The TimerReg does not have the same numerical range than the future variable this version would stall forever if the future value is greater than the numerical range. -- Why is this "community wiki"?
    – harper
    May 2, 2012 at 7:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.