const byte ButtonCount = 4;
const byte ButtonPins[ButtonCount] = {2, 3, 4, 5};
const unsigned long DebounceTime = 1000; // just to see the issue better
boolean ButtonWasPressed[ButtonCount]; // Defaults to 'false'
unsigned long ButtonStateChangeTime = 0; // Debounce timer common to all buttons
void setup()
{
Serial.begin(115200);
Serial.println("\nWake up!\n"); // wokwi
for (byte i = 0; i < ButtonCount; i++)
{
pinMode (ButtonPins[i], INPUT_PULLUP); // Button between Pin and Ground
}
}
void loop()
{
checkButtons();
}
void checkButtons()
{
unsigned long currentTime = millis();
// Update the buttons
for (byte i = 0; i < ButtonCount; i++)
{
boolean buttonIsPressed = digitalRead(ButtonPins[i]) == LOW; // Active LOW
// Check for button state change and do debounce
if (buttonIsPressed != ButtonWasPressed[i] &&
currentTime - ButtonStateChangeTime > DebounceTime)
{
// Button state has changed
ButtonStateChangeTime = currentTime;
ButtonWasPressed[i] = buttonIsPressed;
if (ButtonWasPressed[i])
{
// Button i was just pressed
Serial.print("I see button ");
Serial.print(i); Serial.print(" go down. ");
Serial.print(millis());
Serial.println("");
}
else
{
// Button i was just released
}
}
}
}