#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
#include <Keypad.h>
// Initialize LCD
LiquidCrystal_I2C lcd(0x27, 16, 4); // I2C address may vary, adjust as needed
// Initialize Servo
Servo servo;
// Define Keypad
const byte ROWS = 4;
const byte COLS = 4;
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 to the keypad rows
byte colPins[COLS] = {5, 4, 3, 2}; // Connect to the keypad columns
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Safety box state and code
bool boxLocked = true;
String unlockCode = "1234";
bool codeEntered = false;
void setup() {
lcd.init();
lcd.backlight();
servo.attach(10); // Connect servo to pin 10
servo.write(0); // Initial position (locked)
lcd.setCursor(0, 0);
lcd.print("Smart Safety Box");
lcd.setCursor(0, 1);
lcd.print("Enter code:");
}
void loop() {
char key = keypad.getKey();
if (key) {
handleKeypadInput(key);
}
}
void handleKeypadInput(char key) {
static String enteredCode = "";
if (codeEntered) {
if (key == '*') {
toggleLock();
}
} else {
if (key == '#') {
if (enteredCode == unlockCode) {
lcd.setCursor(0, 2);
lcd.print("Unlock success!");
delay(1000);
clearMessage();
codeEntered = true;
enteredCode = "";
} else {
lcd.setCursor(0, 2);
lcd.print("Invalid code!");
delay(1000);
clearMessage();
enteredCode = "";
}
} else {
enteredCode += key;
lcd.setCursor(0, 2);
lcd.print("Code: " + enteredCode);
}
}
}
void toggleLock() {
boxLocked = !boxLocked;
if (boxLocked) {
servo.write(0); // Lock position
lcd.setCursor(0, 3);
lcd.print("Box locked ");
} else {
servo.write(90); // Unlock position
lcd.setCursor(0, 3);
lcd.print("Box unlocked");
}
delay(1000);
clearMessage();
codeEntered = false;
}
void clearMessage() {
lcd.setCursor(0, 2);
lcd.print(" ");
}