Bar graph level meter
Turn a potentiometer and watch a 10-LED bar graph fill up, like a volume meter.
Output · Beginner
In a real product: Audio level meter (Consumer electronics): Bars show the sound level at a glance.
Ten LEDs in a row make a bar graph. Reading a potentiometer and lighting that many of them gives a level meter, the kind you see on audio mixers and battery indicators.
What you'll learn
- Reading an analog voltage with
analogRead()(0 to 1023) - Scaling one range to another with
map() - Driving many LEDs from a loop
- Why each LED needs its own current-limiting resistor
How it works
The potentiometer is a voltage divider between 5V and GND, and its middle pin (SIG) goes to A0. Turning it moves the voltage from 0 V to 5 V, which analogRead(A0) reads as 0 to 1023.
map(reading, 0, 1023, 0, 10) turns that into how many LEDs to light. The loop then sets LED i HIGH if i is below the level and LOW otherwise.
The bar's anodes (A1 to A10) go to pins 2 to 11, and each cathode goes to GND through its own 220 Ω resistor, so a pin driven HIGH lights its LED. The resistors matter: an LED straight between a pin and GND would pull about 110 mA, nearly three times what an Uno pin can give. With 220 Ω each bar takes about 13 mA (turn on Real circuit and open Currents to see it). One resistor per LED, rather than one shared, keeps every bar equally bright however many are lit; on the cathode side it limits the current just as well as on the anode side.
Try this
- Click the potentiometer while it runs and turn it: the bar follows.
- Light only the top LED of the level (a "dot" display) instead of the whole bar.
- Make the last two LEDs blink when the level is at maximum, as a warning.
sketch.ino
// A potentiometer on A0 sets how many of the bar graph's 10 LEDs (pins 2-11) are lit.
const int POT = A0;
const int FIRST_LED = 2;
const int LED_COUNT = 10;
void setup() {
for (int i = 0; i < LED_COUNT; i++) pinMode(FIRST_LED + i, OUTPUT);
}
void loop() {
int level = map(analogRead(POT), 0, 1023, 0, LED_COUNT);
for (int i = 0; i < LED_COUNT; i++) {
digitalWrite(FIRST_LED + i, i < level ? HIGH : LOW);
}
delay(20);
}