#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <Servo.h>
#define I2C_ADDR 0x27
#define LCD_COLUMNS 16
#define LCD_LINES 2
byte lockedChar[8] = {
0b01110,
0b10001,
0b10001,
0b11111,
0b11011,
0b11011,
0b11011,
0b11111
};
byte unlockedChar[8] = {
0b01110,
0b10000,
0b10000,
0b11111,
0b11011,
0b11011,
0b11011,
0b11111
};
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
/* Keypad setup */
const byte KEYPAD_ROWS = 4;
const byte KEYPAD_COLS = 4;
byte rowPins[KEYPAD_ROWS] = {2, 3, 4, 5};
byte colPins[KEYPAD_COLS] = {6, 7,8, 9};
char keys[KEYPAD_ROWS][KEYPAD_COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, KEYPAD_ROWS, KEYPAD_COLS);
#define SERVO_PIN 10
#define SERVO_LOCK_POS 20
#define SERVO_UNLOCK_POS 90
Servo lockServo;
String SafeCode="";
bool locked=false;
void SafeUnlockFuction()
{
lcd.clear();
lcd.setCursor(0, 0);
lcd.write((byte)0);
lcd.setCursor(2, 0);
lcd.print(" Safe Locked! ");
String userCode = inputSecretCode();
bool unlockedSuccessfully;
if(userCode.equals(SafeCode))
{
unlockedSuccessfully=true;
}
else
{
unlockedSuccessfully=false;
}
Serial.println(unlockedSuccessfully);
if (unlockedSuccessfully) {
lcd.clear();
lcd.setCursor(4, 0);
lcd.print("Unlocked!");
delay(1000);
unlock();
}
else {
lcd.clear();
lcd.setCursor(4, 0);
lcd.print("Denied!");
delay(1000);
}
}
void SafeLockFunction() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.write((byte)1);
lcd.setCursor(2, 0);
lcd.print(" # to lock");
char key = keypad.getKey();
while (key != '#') {
key = keypad.getKey();
}
bool readyToLock = setNewCode();
if (readyToLock) {
lcd.clear();
lock();
}
}
void lock() {
lockServo.write(SERVO_LOCK_POS);
locked=true;
}
void unlock() {
lockServo.write(SERVO_UNLOCK_POS);
locked=false;
}
bool setNewCode() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter new code:");
delay(200);
String newCode = inputSecretCode();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Confirm new code");
String confirmCode = inputSecretCode();
if (newCode.equals(confirmCode)) {
SafeCode="";
for(int i=0;i<newCode.length();i++)
{
SafeCode+=newCode[i];
}
return true;
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Code mismatch");
delay(500);
lcd.setCursor(1, 1);
lcd.print("Safe not locked!");
delay(2000);
return false;
}
}
String inputSecretCode() {
lcd.setCursor(5, 1);
lcd.print("[____]");
lcd.setCursor(6, 1);
String result = "";
while (result.length() < 4) {
char key = keypad.getKey();
if (key >= '0' && key <= '9') {
lcd.print('*');
result += key;
}
}
return result;
}
void setup() {
// put your setup code here, to run once:
lockServo.attach(SERVO_PIN);
lcd.init();
lcd.backlight();
lcd.createChar(0,lockedChar);
lcd.createChar(1,unlockedChar);
lcd.setCursor(4, 0);
lcd.print("Welcome!");
delay(1000);
}
void loop() {
// put your main code here, to run repeatedly:
if(locked)
{
SafeUnlockFuction();
}
else
{
SafeLockFunction();
}
}