//Libraries
#include <Keypad.h>
Servo doorServo;
//Constants
#define SERVO_PIN 9
// Setup the 4x4 keypad
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {7, 6, 5, 4};
byte colPins[COLS] = {3, 2, 1, 0};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Variables
String enteredCode = "";
const String correctCode = "1234"; // door unlock code
void setup()
{
Serial.begin(9600);
// Setup servo
doorServo.attach(SERVO_PIN);
// Start with door locked
Serial.println("Door Lock System Initialized");
lockDoor();
}
void loop()
{
char key = keypad.getKey();
if (key) { // If a key is pressed
Serial.print("Key Pressed: ");
Serial.println(key);
if (key == '#') { // '#' to check entered code
if (enteredCode == correctCode) {
Serial.println("Correct Code! Door Unlocked.");
unlockDoor();
delay(5000); //delay door open for 5s
lockDoor();
} else {
Serial.println("Incorrect Code. Try Again.");
}
enteredCode = ""; // Reset the code after checking
} else {
enteredCode += key; // Append the pressed key to the entered code
Serial.print("Current Code: ");
Serial.println(enteredCode);
}
}
}
//unlock door
void unlockDoor() {
Serial.println("Door Unlocked");
doorServo.write(90);
}
// lock door
void lockDoor() {
Serial.println("Door Locked");
doorServo.write(0);
}