// 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
uno:A5.2
uno:A4.2
uno:AREF
uno:GND.1
uno:13
uno:12
uno:11
uno:10
uno:9
uno:8
uno:7
uno:6
uno:5
uno:4
uno:3
uno:2
uno:1
uno:0
uno:IOREF
uno:RESET
uno:3.3V
uno:5V
uno:GND.2
uno:GND.3
uno:VIN
uno:A0
uno:A1
uno:A2
uno:A3
uno:A4
uno:A5
led1:A
led1:C
btn1:1.l
btn1:2.l
btn1:1.r
btn1:2.r
bz1:1
bz1:2
r1:1
r1:2