Menu
CoddyTech

Knob Bar Graph

Part of the Outputs section of Coddy's Arduino journey. Lesson 18 of 24.

A row of LEDs can show a number as a bar: the more LEDs lit, the bigger the number. Here the number comes from the knob.

First turn the reading into how many LEDs to light, 0 to 5:

int count = map(analogRead(A0), 0, 1023, 0, 5);

Then visit every LED with a for loop and decide for each one. The LEDs before position count are lit, the rest are off:

for (int i = 0; i < 5; i++) {
  if (i < count) {
    digitalWrite(ledPins[i], HIGH);
  } else {
    digitalWrite(ledPins[i], LOW);
  }
}

The else matters: when you turn the knob down, it is what switches off the LEDs that are no longer part of the bar.

challenge icon

Challenge

Medium

The knob is on A0 and the LEDs are in ledPins. Make a bar graph:

  • turn the reading into a count from 0 to 5 with map()
  • light that many LEDs, starting from the first in the array, and turn the others off
  • wait 10 ms, then do it again

Press Run and turn the knob, then Check.

Try it yourself

const int knobPin = A0;
int ledPins[] = {2, 3, 4, 5, 6};

void setup() {
  for (int i = 0; i < 5; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop() {
  // turn the reading into a count from 0 to 5
  // light the first count LEDs and turn the others off
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Outputs

Practice on your own: Arduino playground