resolution of 10 bits. (It takes a 10-bit number to
represent 800, the top value). Let’s check this against
Formula 7. My calculator shows about 9. 64, which
rounds up to 10 as expected. For certain frequencies, you
may wind up with lesser resolution, but remember it can
never be greater than 10.
If mathematics isn’t your cup of tea, don’t let that
logarithm in Formula 7 rile you. In the final analysis,
logarithms are really not much more than digit counters.
Pulling It All Together
Throughout my years in the classroom, I’ve always
followed the “forest for the trees” model when teaching.
You should have the forest plainly in view now and are
finally ready to see the trees up close and personal.
Here goes with a detailed step-by-step procedure for
cranking out PWM on a PIC.
1. Decide on your desired frequency and duty cycle.
2. With a prescaler of one, compute PR2 using
Formula 3. If the result is out of bounds (larger
than 255), repeat again with a prescaler of four,
and if still needed, then try 16.
3. Compute the value of duty using Formula 4.
4. If desired, compute the maximum duty number,
the percent change, and the resolution, using
Formulas 5, 6, and 7, respectively.
5. Specify which CCP1 pin to use in the CONFIG1
6. Store the value of Step 2 in the register PR2.
7. Store the value of Step 3 in
8. Make the CCP1 pin an output by means of the
9. Load the prescaler value code into T2CON<1:0>.
The codes are given in Figure 2.
10. Enable Timer2 by setting T2CON< 2>.
11. Indicate PWM mode to the
Capture/Compare/PWM module by setting
both bits of CCP1CON<3: 2>.
This may look like a lot of work, but do it once or
twice and it becomes second nature. It’s probably
obvious, but a programmable calculator or spreadsheet
can lessen the tedium.
To conclude your PWM education, be sure to
download the four demonstrations available at the
article link. These are written in the free open source
language Great Cow Basic, and are heavily
documented and commented throughout. Begin by
studying the code to see how the steps described
above have been implemented. Finish off by running
the demos at the workbench, confirming your
If you’d simply like to try something practical and
colorful, skip ahead to the fourth demonstration which
shows how to pulse a bicolor LED from red to orange
to green and back again. Figure 3 shows how simple
the circuit is; PWM takes care of everything else!
So, don’t let that datasheet baffle you anymore.
Using the straightforward approach described here,
you should now be ready to tackle your next robot
project involving pulse width modulation! SV
56 SERVO 05.2014