#include <Keypad.h> // Library for Keypad
#include <Servo.h> // Library for Servo Motor
// Define the Keypad size (4x4)
const byte ROWS = 4;
const byte COLS = 4;
// Define Keypad keys layout
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
// Define Arduino digital pins connected to Keypad
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
// Create a Keypad object
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Create a Servo object
Servo myServo;
// Define the password
String password = "1234"; // Change this to set a different password
String inputPassword = ""; // Variable to store user input
void setup() {
Serial.begin(9600); // Start serial communication
myServo.attach(10); // Connect the servo to pin 10
myServo.write(0); // Set the servo to 0° position (locked)
}
void loop() {
char key = keypad.getKey(); // Read pressed key
if (key) { // If a key is pressed
Serial.print("Key Pressed: ");
Serial.println(key);
if (key == '#') { // "#" key is used to confirm the password
if (inputPassword == password) { // Check if password is correct
Serial.println(" Correct Password! Unlocking...");
myServo.write(90); // Rotate servo to 90° (Unlocked)
delay(3000); // Wait for 3 seconds
myServo.write(0); // Reset servo to 0° (Locked)
}
else {
Serial.println(" Incorrect Password! Try again.");
}
inputPassword = ""; // Reset input password
}
else if (key == '*') { // "*" key clears the input
inputPassword = "";
Serial.println(" Input Cleared.");
}
else {
inputPassword += key; // Append pressed key to password input
}
}
}