This is a pretty simple piece of Code, but I must be missing something very basic.
The Code is intended to accept a 6-digit numeric code from a numeric keypad. If the entered code is correct, an LCD panel says so; likewise if the code is not correct. The basic mechanism, in the checkCode() function, is to compare each entered digit to the corresponding digit of the magic number. If there is a mismatch, the OKSoFar boolean variable is set to false. If not, that variable, which was originally set to true, should remain true. When the value of that variable is returned to the main loop, it basically becomes the value of the rightCode variable; depending on whether that variable is true or false, the LCD panel is supposed to give the appropriate message.
The problem is that, regardless of whether the entered number is correct, I get the "wrong Code" message. I've confirmed that it is reading the keypad correctly, so the problem must be in the logic which tests whether each entered digit is correct, and, if not, sets OKSoFar to false. Somehow, that is being set to false even when the numbers match.
I'm sure this is something obvious, but I'm missing it. Any thoughts?
Thanks.
Rob Rothman
//Numeric Keypad Test 2
// Robert Rothman 9/25/14
#include <LiquidCrystal.h>
#include <Keypad.h>
LiquidCrystal lcd(2,3,4,5,6,7); //Connect RS to Arduino 2; EN to Arduino 3; Data 4-7 to Arduino 4-7, respectively
const byte ROWS = 4;
const byte COLS = 3;
char keys [ROWS][COLS] =
{{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}};
byte rowPins[ROWS] = {8,9,10,11};
byte colPins[COLS] = {12,13,A0};
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
int magicCode[] = {0,9,2,0,5,6};
void setup()
{
lcd.begin(16,2);
lcd.clear();
lcd.setCursor(0,0);
}
void loop()
{
boolean rightCode = checkCode();
if (rightCode == false)
{
lcd.print ("Wrong Code!");
}
else
{
lcd.print ("Code Correct");
}
}
boolean checkCode()
{
boolean OKSoFar = true;
int cursorPlace = 0;
for (int digit =0; digit < 6;)
{
char key = keypad.getKey();
if (key != NO_KEY)
{
lcd.print("*");
cursorPlace ++;
int lastKey = key;
if (lastKey != magicCode[digit])
{
OKSoFar = false;
}
digit ++;
}
}
lcd.setCursor(0,0);
return OKSoFar;
}