Arduino Potentiometer LED Dimmer: Circuit and Code

Turn the knob and the LED gets brighter or dimmer. analogRead gives 0 to 1023, analogWrite takes 0 to 255.

Parts you need

Wiring

  1. Knob: outer legs → 5V and GND, middle leg → A0
  2. Pin ~9 → resistor → LED → GND rail

Arduino code

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

void loop() {
  int knob = analogRead(A0);
  int brightness = map(knob, 0, 1023, 0, 255);
  analogWrite(9, brightness);
  Serial.println(brightness);
  delay(100);
}

Goal and tip

Goal: Move the knob to five different brightness levels.

Tip: Try this: watch the numbers in the serial monitor as you turn the knob.

Run this experiment in the free simulator