Page 203 - Programming Microcontrollers in C
P. 203
188 Chapter 4 Small 8-Bit Systems
/* the program gets here every millisecond */
time_count.b.hi = OCHI1;
ac = TSR; /* Arm OCF1 bit clear */
time_count.b.lo = OCLO1; /* Clear OCF1 bit */
time_count.l += 500; /* 500 counts per ms */
OCHI1 = time_count.b.hi;
OCLO1 = time_count.b.lo;
if(--count==0)
return ;
else
{
sec++; /* here every second */
count=1000;/* reset count to 1 second */
}
}
Listing 4-4: Timer Using Output Compares
The listing shows that microcontroller executing programs are
broken into three distinct sections. The first section is referred to as
the initialization section. In this case, the initialization section is the
first two lines following the main() invocation. In the initialization
section, the code executed sets up the operation of the microcontroller.
Generally, this code is executed only once. Therefore, initialization
of volatile memory values, setting up of interrupts, establishment of
I/O ports and data direction registers are all completed in the initial
ization of the program. Unless there is a pressing reason, the main
system interrupts should not be enabled during initialization.
The second section is the applications section. The applications
section is usually a loop that contains all of the code to be handled
routinely by the microcontroller. All input or output operations should
take place within the applications section.
The third section of the program is the collection of interrupt service
routines (asynchronous service section). These routines are called when
appropriate interrupts are generated. In general, interrupt service rou
tines should be short and do as little as possible to service the specified
interrupt. When an interrupt is serviced, the status register of the
microcontroller is saved and the system interrupt is disabled. Therefore,
unless the programmer takes special care to re-enable the interrupts, no