Learn Arduino UNO · Lesson 10

Use the knob to dim an LED smoothly.

Now connect an analogue input to a controllable output. The potentiometer sets a value from 0 to 1023, map() scales it to 0–255, and analogWrite() produces PWM on pin 9 to control LED brightness.

What you need

  • Arduino UNO
  • 10 kΩ potentiometer
  • 1 LED
  • 1 × 220–330 Ω resistor
  • Breadboard and jumper wires

Goal: turn the potentiometer and see the LED brightness track the knob position.

▶ YOUTUBE DEMO PLACEHOLDERSuggested: “Arduino PWM LED Dimmer — Potentiometer Controls Brightness”

Wire the input and output

Potentiometer: outer pins → 5 V and GND; centre wiper → A0

LED: PWM pin 9 → 220–330 Ω resistor → LED anode; LED cathode → GND
Use a PWM-capable pin. On an UNO R3, pins marked with ~ support analogWrite(). Pin 9 is used here.

Map analogue input to PWM output

const int potPin = A0;
const int ledPin = 9;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(potPin);
  int brightness = map(sensorValue, 0, 1023, 0, 255);

  analogWrite(ledPin, brightness);

  Serial.print("Input: " );
  Serial.print(sensorValue);
  Serial.print("   PWM: " );
  Serial.println(brightness);

  delay(20);
}

What analogWrite() really does

On the classic UNO, analogWrite() does not generate a continuously variable analogue voltage. It rapidly switches the output on and off using pulse-width modulation. A value of 0 is always off, 255 is effectively always on, and values in between change the duty cycle so the LED appears dimmer or brighter.

The 0–1023 sensor range and 0–255 PWM range are different, which is why map() is useful here.

Experiments

  1. Reverse the brightness by mapping 0–1023 to 255–0.
  2. Limit the maximum brightness by mapping to 0–128.
  3. Add a minimum level so the LED never fully goes out.
  4. Replace the potentiometer reading with your LDR reading and create an automatic light.

Challenge

Build an automatic night light: use the LDR divider from Lesson 8 as the input and make the LED get progressively brighter as the room becomes darker.