The code using Bounce2 library.
#include <Bounce2.h> // include the Bounce2 library
const int buttonPin[] = { 2, 3, 4, 5, 6, 7 }; // array of button pins connected to digital pins 2, 3, 4, 5, 6 and 7
Bounce button[6]; // array of Bounce objects for each button
int buttonCount[6] = { 0 }; // array to store the number of button presses
const int numberOfButtons = 6; // number of buttons
const int password[] = { 1, 2, 3, 4 }; // password array
int passwordSize = sizeof(password) / sizeof(password[0]); // size of the password array
bool isCorrect = false; // variable to store if the password is correct
const int maxCount = 9; // maximum button count value
void setup()
{
for (int i = 0; i < numberOfButtons; i++)
{
button[i].attach(buttonPin[i], INPUT_PULLUP); // attach each button to its pin with pullup
button[i].interval(5); // set debounce interval to 5
}
Serial.begin(9600); // initialize serial communication
}
void loop()
{
for (int i = 0; i < numberOfButtons - 2; i++)
{
button[i].update();
if (button[i].fell()) // if button is pressed
{
buttonCount[i]++; // increment the button press count
if (buttonCount[i] > maxCount)
{
buttonCount[i] = 0; // reset button count to 0 if it exceeds maxCount
}
Serial.print("Button ");
Serial.print(i + 1);
Serial.print(" Press Count: ");
Serial.println(buttonCount[i]); // print the current button press count to the serial monitor
}
}
// Check the penultimate button for password check
button[numberOfButtons - 2].update();
if (button[numberOfButtons - 2].fell())
{
// compare the buttonCount array with the password array
for (int i = 0; i < passwordSize; i++)
{
if (buttonCount[i] == password[i])
{
isCorrect = true;
}
else
{
isCorrect = false;
break;
}
}
if (isCorrect)
{
Serial.println("Correct Password!");
}
else
{
Serial.println("Wrong Password!");
}
// Reset buttonCount and isCorrect
for (int i = 0; i < numberOfButtons - 2; i++)
{
buttonCount[i] = 0;
}
isCorrect = false;
}
// Check the last button for resetting the buttonCount array
button[numberOfButtons - 1].update();
if (button[numberOfButtons - 1].fell())
{
for (int i = 0; i < numberOfButtons - 2; i++)
{
buttonCount[i] = 0;
}
Serial.println("Button Counts Reset!");
}
}