Skip to main content

PWM: dimming an LED

A digital pin can only be fully on (5 V) or off (0 V). To make an LED half bright, the Uno switches the pin on and off very fast: about 490 times a second (980 on pins 5 and 6). Your eye averages it. This is PWM (pulse width modulation).

analogWrite(pin, 64) ▇▁▁▁▇▁▁▁▇▁▁▁ on 25% of the time -> dim
analogWrite(pin, 191) ▇▇▇▁▇▇▇▁▇▇▇▁ on 75% of the time -> bright

The rules​

  • Only pins marked ~ can do PWM on the Uno: 3, 5, 6, 9, 10, 11.
  • analogWrite(pin, value) takes 0 to 255 (0 = off, 255 = fully on, 127 ≈ half).
  • You do not need pinMode(pin, OUTPUT) for analogWrite, but it does no harm.
  • analogWrite has nothing to do with the analog input pins A0–A5. The name is confusing: it is a digital pin switching quickly.

Common surprises​

What you seeWhy
LED only on or off, no dimmingPin is not a ~ pin. Use 3, 5, 6, 9, 10 or 11.
Value 300 is dimmer than 250Values above 255 wrap around (300 behaves like 44). Keep 0–255.
Brightness does not look "linear"Your eye is more sensitive at low brightness: 0→20 looks like a big change, 200→255 hardly any.
PWM stops working on pins 9/10 after adding a librarySome libraries (Servo) use the same timer. Move the LED to another ~ pin.

Turning a reading into a brightness​

analogRead gives 0–1023, analogWrite takes 0–255. Convert with map():

int reading = analogRead(A0); // 0..1023
int brightness = map(reading, 0, 1023, 0, 255);
analogWrite(9, brightness);

map() works for any range, for example a distance of 0–100 cm into 255–0 (closer = brighter): map(distance, 0, 100, 255, 0). Values outside the input range give results outside the output range; wrap with constrain(x, 0, 255) to be safe.

Fading smoothly​

for (int b = 0; b <= 255; b++) {
analogWrite(9, b);
delay(5); // 256 steps x 5 ms = about 1.3 s fade
}

The delay blocks buttons while fading. See LEDs and buttons for the millis() way.

Same idea on the Raspberry Pi​

The Pi does PWM too: PWMLED in gpiozero takes 0.0 to 1.0 instead of 0–255. See Python and GPIO.