Pulse-width modulation (PWM)

Back to let’s code

Pulse Width Modulation, or PWM, is a technique for getting analog results with digital means, such as control DC motor. Digital control is used to create a square wave, a signal switched between on and off. This on-off pattern can simulate voltages in between the full Vcc of the board (e.g., 5 V on UNO, 3.3 V on a MKR board) and off (0 Volts) by changing the portion of the time the signal spends on versus the time that the signal spends off. The duration of “on time” is called the pulse width. To get varying analog values, you change, or modulate, that pulse width. If you repeat this on-off pattern fast enough with an LED for example, the result is as if the signal is a steady voltage between 0 and Vcc controlling the brightness of the LED.

In the graphic below, the green lines represent a regular time period. This duration or period is the inverse of the PWM frequency. In other words, with Arduino’s PWM frequency at about 500Hz, the green lines would measure 2 milliseconds each. The percentage of time when the signal was high during the time of period is called Duty Cycle. A call to “analogWrite()” is on a scale of 0 – 255, such that “analogWrite(255)” requests a 100% duty cycle (always on), and “analogWrite(127)” is a 50% duty cycle (on half the time) for example.

Please be aware that not all pin can be used for PWM. On Arduino Uno, only pin 3, 5, 6, 9, 10 & 11 have PWM function.