Bench NotesUno handbook

PWM: Dimming an LED

Use analogWrite() and a potentiometer to set LED brightness, and see what PWM really does.

BeginnerLEDResistorPotentiometer

Overview

The Uno cannot output an in-between voltage. Pulse-width modulation (PWM) switches a pin fully on and off hundreds of times per second; the fraction of time spent on, the duty cycle, sets the average. An LED flickers too fast to see, so it simply looks dimmer.

You will need

  • Arduino Uno R3
  • LED and 330 Ω resistor
  • 10 kΩ potentiometer
  • Breadboard and jumper wires

Wiring

Uno pinConnects toNotes
9330 Ω resistor → LED anodePWM pin (~)
GNDLED cathode
5VPot outer leg
A0Pot wiper
GNDPot other outer leg
Wiring for PWM: Dimming an LEDArduino Uno D9 (~PWM) to LED anode through 330 Ω; Arduino Uno GND to LED cathode; Arduino Uno 5V to Potentiometer outer leg; Arduino Uno A0 to Potentiometer wiper; Arduino Uno GND to Potentiometer outer leg .Connections (each line is one wire)Arduino UnoLEDPotentiometerD9 (~PWM)anode330 ΩGNDcathode5Vouter legA0wiperGND outer leg
Original wiring diagram. Each line is one jumper wire; boxes on a line are series resistors.

Diagram

PWM duty cycleThree square waves at about 490 hertz. At 25 percent duty the pin is high a quarter of each period, at 50 percent half, at 75 percent three quarters. Average voltage, and so LED brightness, rises with duty.0 ms≈6.1 ms (3 periods at ≈490 Hz)25% dutyanalogWrite(64)50% dutyanalogWrite(128)75% dutyanalogWrite(191)
Same frequency, different duty cycles.

The sketch

pwm_dimmer.ino
const int LED_PIN = 9;     // must be a PWM pin: 3, 5, 6, 9, 10 or 11
const int POT_PIN = A0;

void setup() {
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
  int reading = analogRead(POT_PIN);              // 0..1023
  int brightness = map(reading, 0, 1023, 0, 255); // 0..255
  analogWrite(LED_PIN, brightness);
  delay(10);
}

How the code works

analogWrite() takes 0–255, where 0 is always off and 255 always on. Pins 5 and 6 run at about 980 Hz, the others at about 490 Hz. The Servo library disables PWM on pins 9 and 10, and tone() interferes with pins 3 and 11, so plan pins when combining features.

Perceived brightness is not linear: the change from 0 to 30 looks bigger than from 200 to 255. For an even-looking fade, square the value before writing it.

What you should observe

  • Turning the knob dims the LED smoothly from off to full.
  • Waving the LED quickly in a dark room at mid brightness shows a dotted trail: the pulses.