// This debouncer validates a button press only after the debounce timeout.
byte buttonpin[] = { 5, 6, 7, 4, 3, 2 }; // declare button pins in an array
byte element; // indicates pressed button/pin
byte buttonArray = sizeof(buttonpin) / sizeof(buttonpin[0]); // get number of elements in button array
unsigned long timer; // timer keeps track of length of button press (or noise/ringing).
unsigned long timeout = 100; // timeout (in milliseconds) is the minimum for "a button is pressed".
byte redPin = 11, grnPin = 9, bluPin = 8; // pins for the common cathode RGBLED
void setup() {
Serial.begin(115200); // start serial monitor
for (int i = 0; i < buttonArray; i++) // count to number of elements in button array
pinMode(buttonpin[i], INPUT_PULLUP); // configure button pins for reading (LOW when pressed)
}
void loop() {
if (element > buttonArray) // count through array... do not use for() loops. they blocking program flow.
element = 0; // if beyond the array size, start again from the first element
if (!digitalRead(buttonpin[element])) { // button may have been pressed, or just noise/ringing
if (millis() - timer > timeout) { // measure time from last "press" to this "press. replaces delay();
if (digitalRead(buttonpin[element])) { // valid button was released after debounce timeout
timer = millis(); // reset timer after valid button press
switch (element) {
case 0: blk(); break;
case 1: wht(); break;
case 2: yel(); break;
case 3: blu(); break;
case 4: grn(); break;
case 5: red(); break;
default: break;
}
}
}
}
element++; // check next array element
}
void blk() { digitalWrite(redPin, LOW); digitalWrite(grnPin, LOW); digitalWrite(bluPin, LOW); }
void wht() { digitalWrite(redPin, HIGH); digitalWrite(grnPin, HIGH); digitalWrite(bluPin, HIGH); }
void yel() { digitalWrite(redPin, HIGH); digitalWrite(grnPin, HIGH); digitalWrite(bluPin, LOW); }
void blu() { digitalWrite(redPin, LOW); digitalWrite(grnPin, LOW); digitalWrite(bluPin, HIGH); }
void grn() { digitalWrite(redPin, LOW); digitalWrite(grnPin, HIGH); digitalWrite(bluPin, LOW); }
void red() { digitalWrite(redPin, HIGH); digitalWrite(grnPin, LOW); digitalWrite(bluPin, LOW); }