the average voltage value
of the pulse DC across the
waveform period. For
example, if we have the
pulse high for 50% of the
period consistently and the
pulses are + 3.3V, then we
are supplying (on the
average) 50% of 3.3V to
the load or 1.65V. In order
to change the pulse width
while the system is
running, we simply write
into OCXRS and it
automatically loads into
OCXR on the next cycle.
We’ll look at how to apply this
idea in the following applications (all
hardware hook-ups and source code is
provided at www.nutsvolts.com).
■ FIGURE 3.
Demo 1. RGB LED color control
• Using changing PWM to
control DC level to an LED,
thereby controlling its
brightness and (in the case
of RGB) its color.
Demo 2. Running four R/C servos
• This simply provides a 1.5
msec to 2 msec pulse width
over a 50 Hz period to
control servo position.
Demo 3. Independent dual motor
• This allows for two DC
motors to be independently controlled in both
speed and direction.
■ FIGURE 4. Servo
RGB PWM Experiment
In the original introductory demo code for the
Experimenter, we had an RGB demo. This is a similar
exercise with a little more focus on the software and
hardware elements. This experiment uses three of the five
OCX modules — OC1, OC2, and OC3 — to independently
drive each LED (red, green, and blue) that is put together
in a single RGB LED package. With PWM on each of the
LEDs, we can control the individual light intensity for each
one to realize up to 16M colors. The code is contained in
RGBDEMO, and the hook-up is shown is Figure 3. There
are several key C functions:
ColorGreen_off(),ColorBlue_on (), ColorBlue_off()
— individual functions per LED type for on or off.
• Set_ColorRed (setting), Set_ColorGreen (setting),
Set_ColorBlue (setting) — Sets the PWM duty cycle
of the designated color red, green, blue, thereby
changing combined color. Designated color (or LED)
is selected via pushbutton by user. Current LED is
stored as a number 1 to 3 in variable sel_color.
We use the LCD and pushbutton C libraries for the
display and selection of the LED. We use the ADC library
to digitalize the pot value connected to pin 10 to get the
brightness value (see earlier 16-bit Experimenter articles for
explanation on these C libraries and their appropriate
• Initialize PWM () - OC1, OC2, OC3 for PWM
operation using TMR2 as common timing source.
• ColorRed_on (), ColorRed_off(),ColorGreen_on (),
This experiment uses OC1, OC2, OC3, and OC4 to
generate pulse modulated waveforms to independently
August 2010 47