I'm try to write code for my Arduino UNO R3 that will Lock or Unlock a door.
For the purpose of testing, I'm currently just using Pin 13 to turn 'On' and 'Off' the "L" LED (representing Locked or Unlocked).
I'm using a 3x4 keypad to enter a 4 digit password. After the password is pressed, I then press the "#" key to check if the password is correct or not.
Below is the code I have written:
#include "Keypad.h"
#define Password_Lenght 12 // Give enough room for 7 chars + NULL char
int lockLED = 13;
bool lockState = false;
const byte ROWS = 4, COLS = 3;
char Data[Password_Lenght], Master[Password_Lenght] = "1234", keyData;
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {5, 6, 7, 8}, colPins[COLS] = {9, 10, 11}, data_count = 0;
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup(){
pinMode(lockLED, OUTPUT); digitalWrite(lockLED, LOW);
Serial.begin(9600);
}
void loop(){
getKeypadEntry();
if (lockState == false){
digitalWrite(lockLED, LOW);
}
if (lockState == true){
digitalWrite(lockLED, HIGH);
}
}
void getKeypadEntry(){
char keyData = keypad.getKey();
switch (keyData){
case NO_KEY:
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
Data[data_count] = keyData;
data_count++;
Serial.println(keyData);
break;
case '#':
checkPassword();
break;
case '*':
data_count = 0;
Data [0] = (char)0;
break;
}
}
void checkPassword(){
if(!strcmp(Data, Master)){
Serial.println(Data);
lockState = !lockState;
if (lockState == true){
Serial.println("Door is Locked.");
data_count = 0;
Data[0] = (char)0;
}
else{
Serial.println("Door is Unlocked.");
data_count = 0;
Data[0] = (char)0;
}
}else{
Serial.println("Invalid Code");
data_count = 0;
Data[0] = (char)0;
}
}
After uploading, it works as intended when I enter the correct paswword:
Enter "1234" + "#": LED turns On
Enter "1234" + "#" again: LED turns Off
And so on...
The problem I'm having is that if I test for a wrong password, it somtimes gives me an "Invalid Code", eventhough the correct code was entered. Once it does this it will never accept the correct password again until I reset the Arduino board.
I've looked at this code and serached Google for way too many hours trying to understand to problem I'm having. Therfore I'm throwing my hands up and asking for help.
Any thoughts why an incorrect password would cause the code to no longer recognize the correct password?
Thanks