Hi I'm creating a keypad door lock for a game. It will have a 4x4 keypad with an led screen powering a relay for the lock. I'm using an arduino UNO.
#include <Adafruit_Keypad.h>
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
#include <LiquidCrystal.h>
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};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
LiquidCrystal lcd(12, 11, 10, 16, 15, 14, 13);
const int relayPin = A0;
int code[4] = {1, 2, 3, 4}; // Default code
int enteredCode[4] = {0, 0, 0, 0};
bool isLocked = true;
void setup() {
lcd.begin(16, 2);
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, LOW);
lcd.print("Locked");
}
void loop() {
char key = keypad.getKey();
if (key) {
lcd.clear();
lcd.print(key);
for (int i = 0; i < 4; i++) {
if (enteredCode[i] == 0) {
enteredCode[i] = key - '0';
break;
}
}
if (enteredCode[3] != 0) {
if (checkCode()) {
isLocked = !isLocked;
if (isLocked) {
lcd.clear();
lcd.print("Locked");
digitalWrite(relayPin, LOW);
} else {
lcd.clear();
lcd.print("Open");
digitalWrite(relayPin, HIGH);
}
} else {
lcd.clear();
lcd.print("Invalid Code");
delay(1000);
lcd.clear();
}
resetCode();
}
}
}
bool checkCode() {
for (int i = 0; i < 4; i++) {
if (enteredCode[i] != code[i]) {
return false;
}
}
return true;
}
void resetCode() {
for (int i = 0; i < 4; i++) {
enteredCode[i] = 0;
}}