#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <Wire.h>
#define Password_Length 5 //define the length of the password
int buzzer = 11; //define buzzer pin
int rled = 13; //define led pin
int gled = 12;
char InputData[Password_Length]; //array to save user input password
char Master[Password_Length] = "1234"; //array which correct(existing) password is saved
byte data_count = 0; //variable to save the index of the InputData array
byte master_count = 0; //variable to save the index of Master array
//creating a 2D array to save keypad buttons
char key[4][4] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
//initialize rows and colomns
byte pin_row[4] = {8 , 7, 6, 5};
byte pin_column[4] = {4, 3, 2, 1};
//create object kp
Keypad kp = Keypad(makeKeymap(key), pin_row, pin_column, 4, 4);
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
lcd.init();
lcd.backlight();
pinMode(buzzer, OUTPUT);
pinMode(rled, OUTPUT);
pinMode(gled, OUTPUT);
}
void loop() {
lcd.setCursor(0,0);
lcd.print("Enter Password:");
//get user input and save in the array "InputData"
char key = kp.getKey();
if (key){
InputData[data_count] = key;
lcd.setCursor(data_count,1);
lcd.print(InputData[data_count]);
data_count++;
}
//check the user input password is matching to pre-define password
if(data_count == Password_Length-1){ //when number of characters are equal to variable "data_count"
lcd.clear();
if(!strcmp(InputData, Master)){
lcd.print("Correct");
digitalWrite(rled, LOW);
digitalWrite(buzzer, HIGH);
digitalWrite(gled, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
}
else{
lcd.print("Incorrect");
digitalWrite(gled, LOW);
digitalWrite(rled, HIGH);
for(int i=0; i<10; i++){
digitalWrite(buzzer, HIGH);
delay(100);
digitalWrite(buzzer, LOW);
delay(300);
}
}
lcd.clear();
//erase the values in the array
while(data_count !=0){
InputData[data_count--] = 0;
}
}
}