#include <Keypad.h>
#include <LiquidCrystal.h>
#include <Servo.h>
const int servoPin = 10; // Connect the servo to digital pin 10
Servo doorLock;
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Four columns
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {2, 3, 4, 5}; // Connect these to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8, 9}; // Connect these to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const char* correctPasscode = "1234"; // Change this to your initial passcode
void setup() {
doorLock.attach(servoPin);
doorLock.write(90); // Lock the door initially
lcd.begin(16, 2); // Initialize the LCD
lcd.setCursor(0, 0);
lcd.print("Enter passcode:");
}
char newPasscode[5];
byte passcodeIndex = 0;
bool setNewPasscode = false;
void loop() {
char key = keypad.getKey();
if (key) {
if (setNewPasscode) {
if (key == '#') {
if (passcodeIndex == 4) {
newPasscode[4] = '\0'; // Null-terminate the passcode string
setNewPasscode = false;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("New passcode set");
delay(2000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter passcode:");
}
} else if (passcodeIndex < 4) {
newPasscode[passcodeIndex] = key;
passcodeIndex++;
}
} else {
if (key == '*') {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Set new passcode:");
setNewPasscode = true;
passcodeIndex = 0;
} else if (key == '#') {
if (strcmp(newPasscode, correctPasscode) == 0) {
unlockDoor();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Access granted!");
delay(2000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter passcode:");
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Access denied!");
delay(2000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter passcode:");
}
}
}
}
}
void unlockDoor() {
doorLock.write(0); // Open the door
delay(2000); // Keep the door open for 2 seconds
doorLock.write(90); // Close and lock the door
}