const int NUM_BTNS = 4; // how many buttons
const int BTN_PINS[NUM_BTNS] = {5, 4, 3, 2};
// initialize global variables
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(115200);
for (int i = 0; i < NUM_BTNS; i++) {
pinMode(BTN_PINS[i], INPUT_PULLUP);
}
Serial.println("Button Demo\n");
}
void loop() {
int btnNumber = checkButtons();
if (btnNumber != 0) {
Serial.print("Button number: ");
Serial.println(btnNumber);
}
}