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:
- For each output, keep an integer static variable to reflect the duty cycle. It should be equal to (100-%output)*100.
- Set your sync interrupt to activate every 10,000 cycles.
- Every time your sync interrupt activates, set all outputs low, unless an input's static varialble is equal to zero.
- 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.
- 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 motor
s, you should be prepared for a nasty voltage spike
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.