#include <Keypad.h>
#include <Servo.h>
#include <LiquidCrystal.h>
#define codeLength 5 // Password length (including null terminator)
Servo myservo; // Servo object
char Code[codeLength]; // Array to store entered password
char PassW[codeLength] = "1234"; // Correct password
byte keycount = 0; // Track the number of keys pressed
// Keypad setup (4x4 matrix)
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
// LCD setup (connected to pins 13, 11, 9, 8, 7, 6)
LiquidCrystal lcd(13, 11, 9, 8, 7, 6);
uint8_t rowPins[ROWS] = {26, 22, 21, 20};
uint8_t colPins[COLS] = {19, 18, 17, 16};
Keypad customKeypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
lcd.begin(16, 2); // Initialize the LCD with 16 columns and 2 rows
lcd.print("Enter a Key:-"); // Display initial message on the LCD
myservo.attach(28); // Attach the servo to pin 28
}
void loop() {
int pos;
char customKey = customKeypad.getKey(); // Read the pressed key from the keypad
if(customKey) { // If a key is pressed
Code[keycount] = customKey; // Store the pressed key
Serial.print(Code[keycount]); // Print the key to the Serial Monitor
lcd.setCursor(5, 1); // Move the cursor to the second row
lcd.print(Code[keycount]); // Display the entered key
keycount++; // Increment the key count
}
// When the full password is entered (4 keys)
if(keycount == codeLength - 1) {
Serial.println(""); // Add a newline in the Serial Monitor for clarity
// Check if the entered password matches the correct password
if(strcmp(Code, PassW) == 0) { // If passwords match
Serial.println("Correct Password");
lcd.clear(); // Clear the LCD screen
lcd.setCursor(0, 0); // Move the cursor to the first row
lcd.print("Correct Password"); // Display "Correct Password"
// Open the servo (rotate from 90 to 180 degrees)
for(pos = 90; pos <= 180; pos++) {
myservo.write(pos); // Move the servo to the new position
delay(40); // Wait for the servo to reach the position
}
delay(1000); // Wait for 1 second
// Close the servo (rotate back from 180 to 90 degrees)
for(pos = 180; pos >= 90; pos--) {
myservo.write(pos); // Move the servo back to 90 degrees
delay(40); // Wait for the servo to reach the position
}
} else { // If the passwords do not match
Serial.println("Incorrect Password");
lcd.clear(); // Clear the LCD screen
lcd.setCursor(0, 0); // Move the cursor to the first row
lcd.print("Wrong Password"); // Display "Wrong Password" on the LCD
delay(2000); // Wait for 2 seconds to display the message
}
deletecount(); // Reset the password input after checking
}
}
// Function to reset the password input
void deletecount() {
while(keycount != 0) {
Code[keycount--] = 0; // Clear the entered password
}
return;
}