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.
Wire the input and output
LED: PWM pin 9 → 220–330 Ω resistor → LED anode; LED cathode → GND
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
- Reverse the brightness by mapping 0–1023 to 255–0.
- Limit the maximum brightness by mapping to 0–128.
- Add a minimum level so the LED never fully goes out.
- 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.