Potentiometer LED dimmer
Turn a knob to set an LED's brightness: analogRead() in, analogWrite() out.
Input · Beginner
In a real product: Dimmable lamp (Smart home): A knob sets the brightness.
The classic analog-in, analog-out project. A potentiometer gives a voltage between 0 V and 5 V, the board reads it with its ADC, and it sets an LED's brightness with PWM.
What you'll learn
- How a potentiometer works as a voltage divider
- The 10-bit ADC:
analogRead()returns 0 to 1023 - PWM output:
analogWrite()takes 0 to 255, so divide by 4
How it works
The potentiometer's outer pins go to 5V and GND, and its wiper (SIG) to A0. Turning the knob slides the wiper along a resistive track, so SIG moves smoothly from 0 V to 5 V.
analogRead(A0) converts that voltage to a number from 0 to 1023 (about 4.9 mV a step). PWM on pin 9 takes 0 to 255, so reading / 4 scales it down. The LED's brightness follows the knob.
The reading is also printed five times a second, so you can watch the numbers in the Serial Monitor.
Try this
- Click the knob and drag it to turn it while the simulation runs.
- Use
map()andconstrain()so the LED is fully off for the first quarter of the turn. - Control a servo's angle instead of an LED (see the slide potentiometer project).
sketch.ino
// A potentiometer on A0 sets the brightness of an LED on pin 9 (PWM).
const int POT = A0;
const int LED = 9;
unsigned long lastPrint = 0;
void setup() {
pinMode(LED, OUTPUT);
Serial.begin(9600);
}
void loop() {
int reading = analogRead(POT); // 0..1023
int brightness = reading / 4; // 0..255
analogWrite(LED, brightness);
if (millis() - lastPrint >= 200) {
lastPrint = millis();
Serial.print("Pot: ");
Serial.print(reading);
Serial.print(" LED: ");
Serial.println(brightness);
}
}