Page 222 - Programming Microcontrollers in C
P. 222
Other Program Items 207
mine if the PWM signal is to be turned on. If flag.PWM is set, the
PWM code will be executed. When this routine is entered, TCMP2
will be reset to zero. The first instruction sets TCR.OLVL2 so that
TCMP2 will be on at the next output compare. The next instruction,
TCR.FOVL2=1 , sets the force overflow bit for TCMP2 which will
cause this bit to be turned on since TCR.OLVL2 is set. This time is
the beginning of the on period of the PWM signal.
The next instruction
TCR.OLVO2=0;
is so that TCMP2 will go off or be reset at the next output compare 2.
Control is then passed to the main line of code. When TCMP2 oc
curs, the output will return to 0 and an interrupt will occur. This
interrupt is detected by the first lines of the interrupt service routine.
One could write a code sequence that would generate the mirror
image signal to that above. That is, the off time would be controlled
by TCMP2 and the on time would be the difference between the time
of TCMP2 and the main time base.
Other Program Items
Several other small programs come to mind that are very useful
in programming microcontrollers. With these small parts, it is usu
ally desirable to avoid library functions and, if possible, use a bag of
tricks to arrive at the desired results. For example, dealing with num
bers for either input or output offers a good place to exercise some
experience over expedience. One case where it is often important to
minimize code space is in generating binary coded decimal (BCD)
numbers from integer numbers to output from a computer. Perhaps
the most direct approach to accomplish this conversion is as follows:
/* convert a binary number less than 100 to BCD */
unsigned char convert_bcd(unsigned char n)
{
unsigned int result;
if(n>99) return 0xff;
result=n/10<<4;
result += n%10;