#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
LiquidCrystal_I2C myLCD(0x27,16,2);
// user input array
char userInput[4] = {'1','1','1','1'};
// our keypad bytes
const byte ROWS = 4;
const byte COLS = 4;
// our char array
char keys[ROWS][COLS] =
{
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
// assigning row pins and col pins
byte rowPin[ROWS] = {9,8,7,6};
byte colPin[COLS] = {5,4,3,2};
// our keypad object
Keypad pad = Keypad(makeKeymap(keys), rowPin, colPin, ROWS, COLS);
// helper method to light up led
void rgbL(bool ans)
{
if(ans)
{
// light up green for two seconds
pinMode(12, OUTPUT);
analogWrite(12, 255);
}else
{
// light up red for two seconds
pinMode(13, OUTPUT);
analogWrite(13, 255);
}
delay(2000);
analogWrite(12,0);
analogWrite(13,0);
}
// helper method to clear second row of LCD
void clr()
{
myLCD.setCursor(0,1);
myLCD.print(" "); // clear our row
}
// helper method to check if a password is correct
// Our Password
char pass[4] = {'4','8','7','3'};
void passCheck(char passUser[])
{
bool same = true;
for(int i = 0; i < 4; i++)
{
if(passUser[i] != pass[i])
{
same = false;
}
}
// print information to LCD
clr();
myLCD.setCursor(0,1);
if(same)
{
// is correct
myLCD.print("Correct!");
}else
{
myLCD.print("Incorrect!");
}
// send our boolean to our rgb LED
rgbL(same);
clr();
}
void setup() {
Serial.begin(9600);
// starting our LCD variable
myLCD.init();
myLCD.backlight();
// setup our LCD
myLCD.setCursor(0,0);
myLCD.print("Enter your code:");
// Initialize userInput array to be empty
for(int i = 0; i < 4; i++) {
userInput[i] = '\0';
}
}
bool loopEnder = true;
void loop() {
// our user input tracking
int trackIn = -1;
while (loopEnder) {
char userKey = pad.getKey(); // Get key pressed
// Check if a key is pressed
if (userKey) {
trackIn++;
if (userKey == '#' && trackIn >= 4) {
// send our array to check our password
passCheck(userInput);
loopEnder = false; // Exit loop after checking password
} else {
if(userKey != '#' && trackIn < 4)
{
// insert user input into array and print *
userInput[trackIn] = userKey;
myLCD.setCursor(trackIn, 1);
myLCD.print("*");
}
}
}
}
// reset loop ender
loopEnder = true;
}