Specifications
BASIC Stamp II
Parallax, Inc. • BASIC Stamp Programming Manual 1.8 • Page 293
2
PWM
PWM
pin, duty, cycles
Convert a digital value to analog output via pulse-width modulation.
•
Pin
is a variable/constant (0-15) that specifies the I/O pin to use.
This pin will be placed into output mode during pulse generation
then switched to input mode when the instruction finishes.
•
Duty
is a variable/constant (0-255) that specifies the analog
output level (0 to 5V).
•
Cycles
is a variable/constant (0-65535) specifying an approximate
number of milliseconds of PWM output.
Explanation
Pulse-width modulation (PWM) allows the BS2—a purely digital de-
vice—to generate an analog voltage. The basic idea is this: If you make
a pin output high, the voltage at that pin will be close to 5V. Output
low is close to 0V. What if you switched the pin rapidly between high
and low so that it was high half the time and low half the time? The
average voltage over time would be halfway between 0 and 5V—2.5V.
This is the idea of PWM; that you can produce an analog voltage by
outputting a stream of digital 1s and 0s in a particular proportion.
The proportion of 1s to 0s in PWM is called the duty cycle. The duty
cycle controls the analog voltage in a very direct way; the higher the
duty cycle the higher the voltage. In the case of the BS2, the duty cycle
can range from 0 to 255. Duty is literally the proportion of 1s to 0s
output by the PWM instruction. To determine the proportional PWM
output voltage, use this formula: (duty/255) * 5V. For example, if duty
is 100, (100/255) * 5V = 1.96V; PWM outputs a train of pulses whose
average voltage is 1.96V.
In order to convert PWM into an analog voltage we have to filter out
the pulses and store the average voltage. The resistor/capacitor com-
bination in figure I-12 will do the job. The capacitor will hold the volt-
age set by PWM even after the instruction has finished. How long it
will hold the voltage depends on how much current is drawn from it
by external circuitry, and the internal leakage of the capacitor. In order
to hold the voltage relatively steady, a program must periodically










