#include <Servo.h> // Servo Library
#include <Keypad.h> // Keypad Library
#include <LiquidCrystal_I2C.h> // LCD Library
Servo s1;
LiquidCrystal_I2C lcd(0x27,16,2);
const int Actual_Pin_size = 6; //Change the password size
const int Password_size = (Actual_Pin_size+1);
char password[Password_size] = "12AB34"; //Change the password
char Entered_pin[Password_size];
const char number_of_rows = 4;
const char number_of_columns = 4;
char row_pins[number_of_rows] = {2, 3, 4, 5};
char column_pins[number_of_columns] = {6, 7, 8, 9};
char key_array[number_of_rows][number_of_columns] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
Keypad k = Keypad(makeKeymap(key_array),row_pins , column_pins, number_of_rows, number_of_columns);
char key;
int Red = 12; //Red LED
int Green = 13; //Green LED
int i = 0;
int lock_status = 1; // Status of lock: 1 means 'locked' 0 means 'unlocked'
void setup()
{
Serial.begin(9600);
lcd.begin(16,2);
lcd.backlight();
lcd.setBacklight(HIGH);
s1.attach(10); //Servo signal pin on digital pin 10
pinMode(Red, OUTPUT);
pinMode(Green, OUTPUT);
digitalWrite(Red, HIGH);
digitalWrite(Green, LOW);
s1.write(0); //Servo shaft moves to 0 degree
lcd.setCursor(4,0);
lcd.print("Welcome!");
delay(2000);
lcd.setCursor(1,0);
lcd.print("Door is Locked");
delay(2000);
lcd.clear();
}
void loop()
{
if(lock_status == 1) // Trigger unlock() if door is locked
{
UnLock_activate();
}
if(lock_status == 0) // Trigger Lock() if door is Unlocked
{
lcd.setCursor(0,0);
lcd.print("Enter * to Lock");
key = k.getKey();
Serial.println(key);
if(key == '*')
{
Lock_activate();
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Door Locked");
delay(2000);
lcd.clear();
lock_status = 1;
}
}
}
//Function to handle lock
void Lock_activate()
{
digitalWrite(Red, HIGH);
digitalWrite(Green, LOW);
s1.write(0); //Servo shaft moves to 0 degree
}
//Function to handle unlock logic
void UnLock_activate()
{
lcd.setCursor(0,0);
lcd.print("Enter Pin:");
key = k.getKey();
if(key)
{
Entered_pin[i] = key ;
lcd.setCursor(i,1);
lcd.print("*c");
i++;
if(i == (Password_size-1))
{
//Serial.println(Entered_pin);
delay(1000);
if (strcmp(Entered_pin, password) == 0)
{
digitalWrite(Red, LOW);
digitalWrite(Green, HIGH);
s1.write(90); //Servo shaft moves to 90 degrees
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Door Unlocked");
i=0;
delay(2000);
lock_status = 0; //Setting the lock state as unlocked
}
else
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Wrong Pin");
delay(2200);
lcd.clear();
i=0;
lock_status = 1; //Setting the lock state as locked
}
}
}
}