Skip to content
BENIBIX Learn

Pulse-Width Modulation (PWM)

Development🔌 Embedded & IoTInputs and Outputs

Also known as PWM, PWM Pin, analogWrite, Duty Cycle

Turning a pin on and off very fast. It dims a light or slows a motor.

Think of it like

It is like flicking a light on and off so fast it looks half bright.

Example

On an Arduino Uno, analogWrite takes 0 to 255. A value of 64 keeps an LED on about a quarter of the time, so it glows dim.

Why it matters

Digital pins can only be on or off. PWM is how they dim lights, mix colours and set motor speed.

Definition

Pulse-width modulation fakes a level between on and off by switching a pin very fast. The pin turns on and off hundreds of times a second. The share of time it is on is called the duty cycle. On a quarter of the time, a light looks dim. On three quarters of the time, it looks bright, and a motor spins faster.

Example code

cpp
analogWrite(9, 64);  // pin 9 on about a quarter of the time
One line sets a PWM pin to about a quarter on, so the light is dim.
PWM, third row: the longer each pulse, the brighter the light.

Common mistake

Using a pin that cannot do PWM. On an Uno only pins 3, 5, 6, 9, 10 and 11 can, and the others just switch on or off.

Key takeaways

  1. 1
    Fast switching. On and off many times a second.
  2. 2
    Duty cycle. The share of time it is on.
  3. 3
    Looks smooth. Eyes and motors see the average.