Page 220 - Programming Microcontrollers in C
P. 220
Pulse Width Modulator System 205
OCHI2=time_cnt.b.hi;
OCLO2=time_cnt.b.lo;
return;
will be executed. This code is the “on” code for the PWM system.
The first instruction in this sequence will set the bit flag.ON, so
that this code will not be executed in the next execution of the inter
rupt service routine. The bit TCR.OLVL2 is the state that will be
transferred to TCMP2 pin when an output compare occurs.
TCR.OLVL2 is then set to 0 so that TCMP2 will be set low when the
next output compare occurs. The code sequence that follows gets the
contents of the output compare register 2, increments this value by
pwm_number, and places this new value back into output compare
register 2. Thus, the time of the output compare is established and
the interrupt service routine is exited.
Eventually, the next output compare 2 interrupt will occur. Since
the bit flag.ON has been set, the following code will be executed.
This code is the “off” code for the PWM system. The first business
to take care of is to reset the bit flag.ON so that the on portion of
PWM code will be executed the next time into the ISR. TCR.OLVO2
is set so that TCMP2 will go on when the next output compare occurs.
flag.ON=0;
TCR.OLVL2=1; /* Timer Compare 2 to turn on */
time_cnt.b.hi=OCHI2; /* get the start time */
time_cnt.b.lo=OCLO2; /* reset the OCF */
time_cnt.l +=off_count; /*complete the cycle*/
OCHI2=time_cnt.b.hi;
OCLO2=time_cnt.b.lo;
return;
The contents of OCR2 are handled as above, but this time their value
is incremented by the contents of off_count. The main line code
is then re-entered by the use of the return instruction.
There is another approach to generation of PWM signals with out
put compare systems that will materially aid this problem. However,
this approach requires two output compare systems. One output com
pare system is used to create the time base and the other is used to
generate the on or off time. Let’s examine the following interrupt
service routine. Output compare 1 is used here to generate the PWM