#include <Keypad.h>
#include <Servo.h>
// Servo setup
Servo myServo;
int servoPin = 10;
// Set a default closed position
int closedPosition = 0; // Angle for closed door
int openPosition = 90; // Angle for open door
// Keypad setup
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Four columns
// Define the keys on the keypad
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; // Connect keypad row pins to Arduino
byte colPins[COLS] = {5, 4, 3, 2}; // Connect keypad column pins to Arduino
// Initialize the Keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Password variables
String password = "1234"; // Set your password here
String inputPassword = ""; // Store user input
void setup() {
Serial.begin(9600);
// Attach the servo
myServo.attach(servoPin);
// Set initial servo position (closed door)
myServo.write(closedPosition);
}
void loop() {
char key = keypad.getKey(); // Get the key pressed
if (key) { // If a key is pressed
Serial.println(key); // Print the key (for debugging)
// Handle keypad input
if (key == '#') { // # key is used to enter the password
if (inputPassword == password) {
openDoor(); // If the password is correct, open the door
} else {
Serial.println("Incorrect Password");
}
inputPassword = ""; // Reset input after checking
} else if (key == '*') { // * key is used to reset the input
inputPassword = "";
Serial.println("Input cleared");
} else {
inputPassword += key; // Add the key to the inputPassword
}
}
}
void openDoor() {
Serial.println("Access Granted! Opening door...");
myServo.write(openPosition); // Move servo to open position
delay(5000); // Keep the door open for 5 seconds
closeDoor(); // Close the door automatically
}
void closeDoor() {
Serial.println("Closing door...");
myServo.write(closedPosition); // Move servo to closed position
}