Actually, PWM is quite common to all creatures: they roam around for food or money for longer or shorter hours, mostly at daytime, some at nightshift. The longer they work the more they get. Even exposure to sunlight radiation may be regarded as a pulse-width modulation with a frequency of one divided by 24 hours. To transfer this to computers just multiply the frequency by some 10 million: with creatures on this planet the interval will be 24 hours (weekends and holidays excepted). With computers it will only be a few milliseconds.
When students ask you how PWM works exactly you can tell them to read the Good Book (aka doc8161.pdf). But it is no fun to pass through the 16 timer modes listed in paragraph 15.11.1. You better give them this little sketch and tell them to watch the Serial Plotter for a while.
The more the blue pulses get wider the higher the red graph which show the average will go. The maximum of course is 5 volts.
The area below the blue and the red graph will always be the same.
There is only 1 single trick in the sketch:
how to read back the actual level of the PWM output pin.
AddendumSince Revision R3, the I2C signals (SCL and SDA) are presented on two pins, making it easy to connect more than one wire to them. So you can simply add a speaker or headphone to one of them and listen to the generated sound:
Readback PWM at low PWM level:
Readback PWM at high PWM level:
A second sketch is added to this project.
You could even add an FFT analysis to check for harmonics at different PWM levels.





Comments