#include <Keypad.h>
#include <Servo.h>
const int servoPin = 9; // Connect the servo to digital pin 9
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] = {5, 4, 3, 2}; // Connect these to the row pinouts of the keypad
byte colPins[COLS] = {13, 12, 11, 10}; // Connect these to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char* correctPasscode = "1234"; // Change this to your desired passcode
void setup() {
doorLock.attach(servoPin);
doorLock.write(90); // Lock the door initially
Serial.begin(9600);
pinMode(8, OUTPUT);
}
void loop() {
char key = keypad.getKey();
if (key) {
Serial.print("Entered: ");
Serial.println(key);
if (key == '1234') {
unlockDoor();
digitalWrite(8, HIGH);
delay(1000);
} else {
// Collect the entered passcode
static char enteredPasscode[5];
static byte passcodeIndex = 0;
enteredPasscode[passcodeIndex] = key;
passcodeIndex++;
if (passcodeIndex == 4) {
enteredPasscode[4] = '\0'; // Null-terminate the passcode string
if (strcmp(enteredPasscode, correctPasscode) == 0) {
unlockDoor();
} else {
Serial.println("Incorrect passcode!");
}
// Reset the passcode entry
passcodeIndex = 0;
}
}
}
}
void unlockDoor() {
Serial.println("Unlocking the door");
doorLock.write(0); // Open the door
delay(2000); // Keep the door open for 2 seconds
doorLock.write(90); // Close and lock the door
}