DEV Community

Hedy
Hedy

Posted on

How to control an LED’s brightness using a potentiometer

Components Needed:

1. Circuit Wiring
Potentiometer:

  • Connect one outer pin to 5V (Arduino's 5V pin).
  • Connect the other outer pin to GND.
  • Connect the wiper (middle pin) to analog input A0.

LED:

2. Arduino Code

cpp
const int potPin = A0;   // Potentiometer connected to A0
const int ledPin = 9;    // LED connected to PWM pin 9

void setup() {
  pinMode(ledPin, OUTPUT);  // Set LED pin as output
  Serial.begin(9600);       // Start serial monitor (optional)
}

void loop() {
  int potValue = analogRead(potPin);         // Read pot (0–1023)
  int brightness = map(potValue, 0, 1023, 0, 255);  // Map to PWM range (0–255)
  analogWrite(ledPin, brightness);           // Set LED brightness

  // Optional: Print values to serial monitor
  Serial.print("Potentiometer: ");
  Serial.print(potValue);
  Serial.print(", Brightness: ");
  Serial.println(brightness);
  delay(50);
}
Enter fullscreen mode Exit fullscreen mode

How It Works
1. Read Potentiometer:

analogRead(A0) reads the wiper voltage (0–1023 for 10-bit ADC).

2. Map to PWM Range:

map() converts 0–1023 → 0–255 (PWM range for analogWrite).

*3. Control LED Brightness:
*

analogWrite(9, brightness) sets the duty cycle (0=off, 255=full brightness).

3. Advanced Tweaks
A. Exponential Brightness (Better for Human Perception)
Human eyes perceive brightness logarithmically. Modify the map() line:

cpp
int brightness = pow(potValue / 1023.0, 2.5) * 255;  // Exponential curve
Enter fullscreen mode Exit fullscreen mode

B. Adding a Capacitor for Smoothing
To reduce flickering, add a 0.1µF capacitor between the pot’s wiper and GND.

C. Using an RGB LED
Control three PWM pins (red, green, blue) with three pots for color mixing!

4. Common Issues & Fixes
LED doesn’t dim:

Check if the LED is connected to a PWM-capable pin (marked with ~ on Arduino).

Values jump erratically:

Add a capacitor (0.1µF) or check for loose connections.

LED too bright/dim at extremes:

Adjust the map() range (e.g., map(potValue, 50, 1000, 10, 200)).

5. Extensions

  • Motor Speed Control: Replace the LED with a motor driver (e.g., L298N).
  • OLED Display: Show the potentiometer value on a screen.
  • MIDI Controller: Use the pot to adjust software parameters (e.g., synth volume).

Top comments (0)