Pulses are also known as square waves having only two states, either 0 (LOW) or 1 (HIGH). By modulating the period of highs, we can have different average values and this allows us to control the voltage output to a particular device. Yes, the voltage can also be controlled by a potentiometer but a microcontroller’s digital output can only produce two level of outputs, either +5V or 0V, so in such applications PWM is invaluable.
On the Arduino, not all the digital pins can do PWM. As you can see in the photo below, only pins 3, 5, 6, 9, 10 and 11 have PWM capabilities (at least on the Uno).
Duty cycle of a square wave is calculated by the percentage of the period of highs over the total period. This is a chart taken from the Arduino website.
In the Arduino IDE, the PWM function is given by analogWrite(). For example, analogWrite(9, 127) gives a 50% duty cycle wave output at Digital Pin 9.
To demonstrate the effects of PWM, I’m going to use an LED. For every push of a button, the duty cycle will increase, thus making the LED brighter. In the code, I’ve also implemented switch debouncing but it’s quite sketchy and I think it can be improved (I’m still new at this).