User`s manual

Dynamic C Users Manual digi.com 115
7.3.2 Example: Delay Loop
An important detail about MS_TIMER is that it overflows (“rolls over”) approximately every 49 days, 17
hours. This behavior causes the following delay loop code to fail:
/* THIS CODE WILL FAIL!! */
endtime = MS_TIMER + delay;
while (MS_TIMER < endtime) {
//do something
}
If “MS_TIMER + delay” overflows, this returns immediately. The correct way to code the delay loop so
that an overflow of MS_TIMER does not break it, is this:
endtime = MS_TIMER + delay;
while ((long)MS_TIMER - endtime < 0) {
//do something
}
The interval defined by the subtraction is always correct. This is true because the value of the interval is
based on the values of MS_TIMER and endtime” relative to one another, so the actual value of these vari-
able does not matter.
One way to conceptualize why the second code snippet is always correct is to consider a number circle like
the one in Figure 7.1. In this example, delay=5. Notice that the value chosen for MS_TIMER will “roll
over” but that it is only when MS_TIMER equals or is greater than “endtime” that the while loop will eval-
uate to false.
Figure 7.1 “delay=5”
Another important point to consider is that the interval is cast to a signed number, which means that any
number with the high bit set is negative. This is necessary in order for the interval to be less than zero
when MS_TIMER is a large number.
1
8
2
4
3
9
10
0
11
12
5
6
7
13
14
15
MS_TIMER
endtime