// Define the pin numbers
const int LED_PIN = 8;
const int BUTTON_PIN = 2;
const int BUZZER_PIN = 9;
// Define the code for the correct password
const int PASSWORD[] = {1, 2, 3, 4};
const int PASSWORD_LENGTH = 4;
// Define the current password
int currentPassword[PASSWORD_LENGTH];
int currentLength = 0;
// Define the state of the lock
bool locked = true;
void setup() {
// Set the LED, button, and buzzer pins as outputs/inputs
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(BUZZER_PIN, OUTPUT);
// Turn off the LED and buzzer
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
// Set the initial password to all zeros
for (int i = 0; i < PASSWORD_LENGTH; i++) {
currentPassword[i] = 0;
}
}
void loop() {
// Check if the button is pressed
if (digitalRead(BUTTON_PIN) == LOW) {
// Turn on the LED
digitalWrite(LED_PIN, HIGH);
// Add the current digit to the password
int digit = getDigit();
if (digit != -1) {
currentPassword[currentLength] = digit;
currentLength++;
// Check if the password is complete
if (currentLength == PASSWORD_LENGTH) {
// Check if the password is correct
if (checkPassword()) {
// Unlock the door
locked = false;
} else {
// Incorrect password, sound the buzzer
buzzer(500, 1000);
}
// Reset the current password
currentLength = 0;
for (int i = 0; i < PASSWORD_LENGTH; i++) {
currentPassword[i] = 0;
}
}
}
// Wait for the button to be released
while (digitalRead(BUTTON_PIN) == LOW) {}
// Turn off the LED
digitalWrite(LED_PIN, LOW);
}
// Check the state of the lock
if (locked) {
// Sound the buzzer
buzzer(100, 500);
// Turn on the LED
digitalWrite(LED_PIN, HIGH);
delay(1000);
digitalWrite(LED_PIN, LOW);
delay(1000);
} else {
// Turn off the buzzer
digitalWrite(BUZZER_PIN, LOW);
// Blink the LED
digitalWrite(LED_PIN, HIGH);
delay(1000);
digitalWrite(LED_PIN, LOW);
delay(1000);
}
}
// Get the current digit from the button press
int getDigit() {
int digit = -1;
// Check which button is pressed