#include <Keypad.h> // Include the keypad library
const byte ROWS = 4; // Define the number of rows and columns in the keypad
const byte COLS = 4;
char keys[ROWS][COLS] = { // Define the keypad layout
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; // Connect the keypad pins to the Arduino pins
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS); // Create a new keypad object
int ledPin = 13; // Connect an LED to pin 13
int lockPin = 10; // Connect a servo motor to pin 10
int password[4] = {1, 2, 3, 4}; // Define the password
int enteredPassword[4]; // Create an array to store the entered password
int index = 0; // Define an index variable to keep track of the entered password
void setup() {
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
pinMode(lockPin, OUTPUT); // Set the lock pin as an output
Serial.begin(9600); // Start the serial communication
}
void loop() {
char key = keypad.getKey(); // Read the key that was pressed
if (key != NO_KEY) { // If a key was pressed
Serial.println(key); // Print the key to the serial monitor
if (key >= '0' && key <= '9') { // If the key is a number
enteredPassword[index] = key - '0'; // Convert the key to a number and store it in the entered password array
index++; // Increment the index variable
if (index == 4) { // If the full password has been entered
if (checkPassword()) { // If the password is correct
digitalWrite(ledPin, HIGH); // Turn on the LED
unlock(); // Unlock the door
} else { // If the password is incorrect
digitalWrite(ledPin, LOW); // Turn off the LED
delay(1000); // Wait for 1 second
}
index = 0; // Reset the index variable
}
}
}
}
bool checkPassword() { // Define a function to check the entered password
for (int i = 0; i < 4; i++) { // Loop through the password array
if (enteredPassword[i] != password[i]) { // If any of the digits do not match
return false; // Return false
}
}
return true; // If all the digits match, return true
}
void unlock() { // Define a function to unlock the door
for (int i = 0; i < 180; i++) { // Move the servo motor from 0 to 180 degrees
digitalWrite(lockPin, HIGH); // Turn on the lock pin
delay(15); // Wait for 15 milliseconds
digitalWrite(lockPin, LOW); // Turn off the lock pin
delay(15); // Wait for 15 milliseconds
}
delay(2000); // Wait
for (int i = 180; i > 0; i--) { // Move the servo motor from 180 to 0 degrees
digitalWrite(lockPin, HIGH); // Turn on the lock pin
delay(15); // Wait for 15 milliseconds
digitalWrite(lockPin, LOW); // Turn off the lock pin
delay(15); // Wait for 15 milliseconds
}
}