Also known as: PWM
Pulse-width modulation (PWM) encodes an analog level as the fraction of time a fast digital square wave spends switched on — its duty cycle.1
Overview
A pin toggled at, say, 20 kHz that is high 25% of the time delivers, on average, a quarter of the supply voltage. Because the switching is far faster than the load can respond, an LED, motor, or heater simply sees the average. A microcontroller generates PWM in hardware timers, so it costs no CPU once configured, and the duty cycle can be changed on the fly. Servos and many sensors also use PWM as their signaling format.
What it’s for
PWM is how an MCU produces an effectively analog output from purely digital GPIO: dimming LEDs, controlling motor and fan speed, positioning servos, and — with a simple low-pass filter — approximating a digital-to-analog converter. On an Arduino, analogWrite() is PWM under the hood. Duty cycle is typically updated in the main loop or from a timer interrupt.
Sources
-
Pulse-width modulation — Wikipedia, on duty cycle and PWM applications. ↩