GETTING STARTED WITH PICs
PR2 = [(Fosc) / ( 4 * TMR2 Prescale *
PWM Frequency)] - 1
If you use the internal oscillator set
to its default Fosc = 4 MHz, and use a
TMR2 prescaler of 1: 4, and want a PWM
with a frequency of 1 kHz, then PR2 is
calculated to be 249:
PR2 = [ 4MHz / ( 4 * 4 * 1 kHz) ]
– 1 = 249
If the number calculates to a value
larger than 255, we would have to
adjust the prescaler to a larger value or
change the oscillator speed. The Timer 2
prescaler is set in the T2CON register
and you only have three selections, so
you may have to change your oscillator
to get the PWM frequency you need.
Once you have the PR2 value, you will
use that in the next step.
SETTING THE DUTY CYCLE
The duty cycle is controlled by
setting bits in two different registers. This
is because the duty cycle is capable of
10-bit resolution or 1,024 different
settings. Since the PIC16F690 is an
eight-bit MCU, we need two registers to
store the value. The CCPR1L holds eight
bits and the CCP1CON register has the
extra two. Figure 8 shows the bit settings.
The reworked formula for the duty cycle is:
■ FIGURE 7. PIC16F690 datasheet PWM details.
Timer 2 prescaler, and sets the ECCP hardware to run in
PWM mode with the command lines below:
CCPR1L:CCP1CON = 4 * (PR2 +1) * Duty Cycle Ratio
Since we already calculated PR2 as 249, and assuming
we want a 20% duty cycle, then we get the answer:
TRISC.5 = 0
CCP1CON = %00001100
T2CON = %00000101
‘ Set PORTC.5 (CCP1) to output
‘ Set CCP1 to PWM
‘ Turn on TMR2, Presc=4
CCPR1L:CCP1CON = 4 * (249 +1) * 0.2 = 200
A 200 in binary is 0011001000 so the CCPR1L
register gets the most significant eight bits 00110010
and the CCPCON1 register bits are set to match the final
two bits, which are zero.
SAMPLE PROGRAM
If you look through the sample programs that come
with PICBASIC PRO, you will see a hardware PWM
sample program that shows all these values being set in
the PICBASIC PRO program. That program is shown in
Listing 2. You can see that the PR2 value and the duty
cycle registers are set up just the way we calculated here.
In addition to these calculations, the program in
Listing 2 makes PORTC bit 5 an output, then controls the
HPWM COMMAND
These steps were probably tough to understand for
the true beginner. I went through all of this so you know
the fundamentals of how to control the PWM hardware in
PICs. PICBASIC PRO makes this so much easier than
the sample program demonstrates, which is one of the
reasons I call PICBASIC PRO the perfect compiler for the
beginner. PICBASIC PRO takes all these set up steps and
■ FIGURE 8. Duty cycle settings registers.
September 2008 19