Pulse Width Modulation
Technique used in motor speed control, lighting, sound generation, and servo positioning.

Since getting analog voltages out of a binary device requires extra hardware, sometimes just sending out a stream of pulses with the percentage of on-time correct will work.
For example, to get an output voltage of 3 volts from a pin that can be either at 0 or 5 volts, having the pin at 5 volts 60% of the time (plus a filter capacitor) gets you close to 3V.

For all the elegance and thrift of this approach, there is a lot of processor overhead in deciding exactly when to switch while doing other tasks. Some microcontrollers have special hardware to do PWM in the background.

A simple way to do pulse width modulation at about 1kHz on a 10MHz chip: It requires one Output compare interrupt for each output, and one timer interrupt to act as the sync pulse. It is used like so:
  1. For each output, keep an integer static variable to reflect the duty cycle. It should be equal to (100-%output)*100.
  2. Set your sync interrupt to activate every 10,000 cycles.
  3. Every time your sync interrupt activates, set all outputs low, unless an input's static varialble is equal to zero.
  4. For each output, set its timer for its static variable, unless the value is equal to 10,000, in which case don't set it.
  5. The result should be a square wave for each output with a base frequency of 1kHz.
There are a few problems with this system. First of all, interrupts may be at a premium on your microcontroller, and you may want to use some more math to try to schedule all your outputs and sync off of one interrupt. Second of all, in this case, all outputs are turned off at the same time. If several outputs control electric motors, you should be prepared for a nasty voltage spike. YMMV.

If you are designing a system that will be used around humans, then the frequency of your pulse should also be taken into consideration. Pulse width modulation at 1kHz will cause an annoying 1kHz whine when it is used to drive an electric motor, even with the filter capacitor. This is why I have my doubts about bonnet's assertion that it can be used in sound generation. Even driving a system above 20 kHz is bound to produce some overtones in the audible spectrum. If minimizing annoyance is an issue, you may want to scrap the PWM scheme and just shell out the extra bucks for a D/A converter.

Log in or registerto write something here or to contact authors.