#include <Keypad.h>
#include <Servo.h>
#include <LiquidCrystal.h>
#define codeLength 4 // Password length is 4 digits
Servo myservo; // Declare a Servo object
char Code[codeLength]; // Store the entered password
char PassW[codeLength + 1] = "1234"; // Correct password (size 5 for null-terminator)
byte keycount = 0; // Track how many keys are 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'}
};
// Pin connections for the keypad and LCD
uint8_t rowPins[ROWS] = {26, 22, 21, 20};
uint8_t colPins[COLS] = {19, 18, 17, 16};
// LCD setup (connected to pins 13, 11, 9, 8, 7, 6)
LiquidCrystal lcd(13, 11, 9, 8, 7, 6);
Keypad customKeypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
lcd.begin(16, 2); // Initialize LCD (16 columns, 2 rows)
lcd.print("Enter Code:"); // Display message on LCD
myservo.attach(28); // Attach servo to pin 28
}
void loop() {
char key = customKeypad.getKey(); // Read the pressed key from keypad
if (key) { // If a key is pressed
Code[keycount] = key; // Store the pressed key in Code[]
lcd.setCursor(5, 1); // Move cursor to position 5, 1 (second row)
lcd.print(key); // Display the pressed key on the screen
keycount++; // Increment key count
}
// Once the full password is entered (4 keys)
if (keycount == codeLength) {
delay(500); // Small delay before checking the password
// Check if the entered password matches the correct password
if (strcmp(Code, PassW) == 0) {
lcd.clear(); // Clear the LCD screen
lcd.setCursor(0, 0); // Move cursor to the first row
lcd.print("Correct!"); // Display "Correct!" on the screen
openAndCloseServo(); // Open and close the servo (unlock action)
} else {
lcd.clear(); // Clear the LCD screen
lcd.setCursor(0, 0); // Move cursor to the first row
lcd.print("Wrong! Try Again"); // Display "Wrong! Try Again"
delay(2000); // Wait for 2 seconds before clearing
}
resetPassword(); // Reset the entered password for the next attempt
}
}
// Function to move the servo (simulates unlocking action)
void openAndCloseServo() {
for (int pos = 90; pos <= 180; pos++) { // Move the servo from 90 to 180 degrees
myservo.write(pos); // Move the servo to the new position
delay(15); // Wait for the servo to reach the position
}
delay(1000); // Wait for 1 second
for (int pos = 180; pos >= 90; pos--) { // Move the servo back from 180 to 90 degrees
myservo.write(pos); // Move the servo back to the 90-degree position
delay(15); // Wait for the servo to reach the position
}
}
// Function to reset the entered password (clear Code[] and reset key count)
void resetPassword() {
keycount = 0; // Reset keycount to 0
for (int i = 0; i < codeLength; i++) {
Code[i] = 0; // Clear the Code[] array
}
}