Page 207 - Programming Microcontrollers in C
P. 207
192 Chapter 4 Small 8-Bit Systems
there was a function called delay. A delay function can be integrated
into a time interrupt service routine easily. The interrupt service rou
tine above is entered every millisecond. We specified a function delay
that had an unsigned long argument that corresponds to the required
delay in milliseconds. Such a function could be implemented as:
void delay(unsigned long);
unsigned long time=0;
void delay(unsigned long del)
{
time = del; /* place the delay time in the global
memory */
while(time>0);
}
Now we must add one code sequence to the interrupt service routine
above:
if(--count==0)
{
if(time>0)
--time;
return ;
}
The function delay() places the value of the required delay in
the unsigned long location time. The program then hangs on the
while statement so long as time is greater than 0. Every time the
ISR is entered—which is every millisecond— the long unsigned
value time will be decremented. When the proper time has passed,
the delay() function will return to the calling program.
The function delay() does something that many programmers
do not like: the program hangs in a loop until a specified time has
passed. This operation may seem to waste the microcontroller re
source. Note, however, that the program does not spend all of the
time in the loop; interrupts are being serviced during this time. We
will see that the timer interrupt is only one of many potential inter
rupts that will be working on the part at all times. Placing the device
into a wait loop for a few milliseconds may stop the main program in