| 1 |
/* |
| 2 |
LED bar graph |
| 3 |
|
| 4 |
Turns on a series of LEDs based on the value of an analog sensor. |
| 5 |
This is a simple way to make a bar graph display. Though this graph uses 10 |
| 6 |
LEDs, you can use any number by changing the LED count and the pins in the |
| 7 |
array. |
| 8 |
|
| 9 |
This method can be used to control any series of digital outputs that depends |
| 10 |
on an analog input. |
| 11 |
|
| 12 |
The circuit: |
| 13 |
- LEDs from pins 2 through 11 to ground |
| 14 |
|
| 15 |
created 4 Sep 2010 |
| 16 |
by Tom Igoe |
| 17 |
|
| 18 |
This example code is in the public domain. |
| 19 |
|
| 20 |
https://www.arduino.cc/en/Tutorial/BuiltInExamples/BarGraph |
| 21 |
*/ |
| 22 |
|
| 23 |
// these constants won't change: |
| 24 |
const int analogPin = A0; // the pin that the potentiometer is attached to |
| 25 |
const int ledCount = 10; // the number of LEDs in the bar graph |
| 26 |
|
| 27 |
int ledPins[] = { |
| 28 |
2, 3, 4, 5, 6, 7, 8, 9, 10, 11 |
| 29 |
}; // an array of pin numbers to which LEDs are attached |
| 30 |
|
| 31 |
|
| 32 |
void setup() { |
| 33 |
// loop over the pin array and set them all to output: |
| 34 |
for (int thisLed = 0; thisLed < ledCount; thisLed++) { |
| 35 |
pinMode(ledPins[thisLed], OUTPUT); |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
void loop() { |
| 40 |
// read the potentiometer: |
| 41 |
int sensorReading = analogRead(analogPin); |
| 42 |
// map the result to a range from 0 to the number of LEDs: |
| 43 |
int ledLevel = map(sensorReading, 0, 1023, 0, ledCount); |
| 44 |
|
| 45 |
// loop over the LED array: |
| 46 |
for (int thisLed = 0; thisLed < ledCount; thisLed++) { |
| 47 |
// if the array element's index is less than ledLevel, |
| 48 |
// turn the pin for this element on: |
| 49 |
if (thisLed < ledLevel) { |
| 50 |
digitalWrite(ledPins[thisLed], HIGH); |
| 51 |
} |
| 52 |
// turn off all pins higher than the ledLevel: |
| 53 |
else { |
| 54 |
digitalWrite(ledPins[thisLed], LOW); |
| 55 |
} |
| 56 |
} |
| 57 |
} |