/*
Multi button demo
*/
// user constants
const int NUM_BTNS = 5;
// pin constants
const int BTN_PINS[] = {12, 11, 10, 9, 8};
// globals to hold button states
int btnState[NUM_BTNS];
int oldBtnState[NUM_BTNS];
// function returns which button was pressed, or 0 if none
int checkButtons() {
int btnPressed = 0;
for (int i = 0; i < NUM_BTNS; i++) {
// check each button
btnState[i] = digitalRead(BTN_PINS[i]);
if (btnState[i] != oldBtnState[i]) { // if it changed
oldBtnState[i] = btnState[i]; // remember state for next time
if (btnState[i] == LOW) { // was just pressed
btnPressed = i + 1;
//Serial.print("Button ");
//Serial.print(btnPressed);
//Serial.println(" pressed");
} else { // was just released
//Serial.print("Button ");
//Serial.print(btnPressed);
//Serial.println(" released");
}
delay(20); // debounce
}
}
return btnPressed;
}
void setup() {
Serial.begin(9600);
for (int i = 0; i < NUM_BTNS; i++) {
pinMode(BTN_PINS[i], INPUT_PULLUP);
}
Serial.println("Press a button!\n");
}
void loop() {
int btnNumber = checkButtons();
if (btnNumber) { // btnNumber is not 0
Serial.print("Button ");
Serial.print(btnNumber);
Serial.println(" pressed");
}
}