/*
Arduino Keypad Safe
Author: Rudra Shukla
Description: A keypad-controlled safe using an LCD and servo motor.
*/
// Including Libraries
#include <Keypad.h>
#include <LiquidCrystal.h>
#include <Servo.h>
// Keypad Setup
// Define keypad size
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
// Keypad button layout
char keys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
// Arduino pins connected to keypad rows and columns
uint8_t rowPins[ROWS] = {5, 4, 3, 2};
uint8_t colPins[COLS] = {A3, A2, A1, A0};
// Create keypad object
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// LCD Setup
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
// Servo Setup
Servo myservo;
// Variables
int pos = 0; // Stores servo position
bool move = false, newCode = false; // If servo should move, if new code is being creaed
String password = "1234"; // Stores Password
String input = ""; // Stores keypad input
int count = 0; // Tracks lock state
// Setup
void setup() {
delay(100); // Small delay for system stability
lcd.begin(16, 2); // Initialize LCD size
myservo.attach(6); // Attach servo to pin 6
myservo.write(90); // Set servo to locked position
lcd.setCursor(0, 0);
lcd.print("Enter Code:"); // Display prompt
}
// Main Loop
void loop() {
// Read the key pressed on the keypad
char key = keypad.getKey();
// If a key was pressed
if (key != NO_KEY) {
// '*' clears the current input and resets the screen
if (key == '*') {
input = "";
lcd.clear();
lcd.print("Enter Code:");
}
// '#' submits the entered input
else if (key == '#') {
lcd.clear();
// Special command to enter new password creation mode
if(count == 1 && input == "AAAA"){
lcd.clear();
lcd.print("Create new Code:");
newCode = true;
}
// Correct password entered
else if (input == password) {
lcd.print("Access Granted");
delay(500);
// Display instructions for creating a new code after first unlock
if (count == 0){
lcd.clear();
lcd.print("Enter AAAA to" );
lcd.setCursor(0,1);
lcd.print("Make a New Code");
}
count++; // Increment lock state
move = true; // Enable servo movement
}
// Save new password
else if(newCode){
lcd.print("New Code Created");
password = input;
newCode = false;
}
// Incorrect password entered
else {
lcd.print("Access Denied");
}
// Reset input and LCD after action
delay(2000);
input = "";
lcd.clear();
lcd.print("Enter Code:");
}
// Any other key adds to the input string
else {
input += key;
lcd.setCursor(0, 1);
lcd.print(input);
}
}
// Unlock the safe by rotating servo from 90° to 0°
if(count == 1 && move){
for (pos = 90; pos >= 0; pos--) {
myservo.write(pos);
delay(15);
}
move = false;
}
// Lock the safe by rotating servo from 0° back to 90°
else if(count == 2 && move){
for (pos = 0; pos <= 90; pos++) {
myservo.write(pos);
delay(15);
}
count = 0; // Reset state
move = false;
}
}