/*
Program LED Bar Graph Di Ambil Dari
https://www.arduino.cc/en/Tutorial/BuiltInExamples/BarGraph
*/
// variabel constant yang tidak berubah:
int potPin = A0; // pin potentiometer
int ledCount = 10; // jumlah led
int buttonPin = 13; // button pin
int ledPins[] = {
2, 3, 4, 5, 6, 7, 8, 9, 10, 11
}; // array pin lampu
// debounce delay untuk menunggu program di jalankan ketika buttonstate berubah
int debounceDelay = 50;
int lastTimeButtonStateChanged = 0;
int lastButtonState = LOW;
bool LEDOn = false;
void setup() {
// looping pin array untuk dimasukan ke output
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
pinMode(ledPins[thisLed], OUTPUT);
}
pinMode(buttonPin, INPUT);
}
void loop() {
int timeNow = millis();
if (timeNow - lastTimeButtonStateChanged > debounceDelay) {
int buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) {
lastTimeButtonStateChanged = timeNow;
lastButtonState = buttonState;
if (buttonState == LOW) { // button di tekan
LEDOn = !LEDOn;
}
}
}
if (LEDOn) {
int potValue = analogRead(potPin);
// map hasil input dari potentiometer ke jumlah led
int ledLevel = map(potValue, 0, 1023, 0, ledCount);
// looping array pin led lagi
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
if (thisLed < ledLevel) {
digitalWrite(ledPins[thisLed], HIGH);
}
else {
digitalWrite(ledPins[thisLed], LOW);
}
}
}
else {
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
digitalWrite(ledPins[thisLed], LOW);
}
}
}