const int numRows = 4; // number of rows in the keypad
const int numCols = 4; // number of columns
const int debounceTime = 20; // number of milliseconds for switch to be stable
const int ledPin = 13;
const char password[] = "8714";
int passwordIndex = 0;
const char keymap[numRows][numCols] = {
{ '1', '2', '3' ,'A' } ,
{ '4', '5', '6' ,'B'} ,
{ '7', '8', '9' ,'C'} ,
{ '*', '0', '#' ,'D'}
};
const int rowPins[numRows] = {11,10,9,8};
const int colPins[numCols] = {5,4,3,2}; // Columns 0 through 2
void setup()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // Set LED pin as output
for (int row = 0; row < numRows; row++)
{
pinMode(rowPins[row],INPUT); // Set row pins as input
digitalWrite(rowPins[row],HIGH); // turn on Pull-ups
}
for (int column = 0; column < numCols; column++)
{
pinMode(colPins[column],OUTPUT); // Set column pins as outputs
// for writing
digitalWrite(colPins[column],HIGH); // Make all columns inactive
}
}
void loop()
{
char key = getKey();
if( key != 0) { // if the character is not 0 then
// it's a valid key press
Serial.print("Got key ");
Serial.println(key);
// Check if the key is part of the password
if (key == password[passwordIndex])
{
passwordIndex++;
if (passwordIndex == strlen(password))
{
Serial.println("Password correct! Turning on LED.");
digitalWrite(ledPin, HIGH);
passwordIndex = 0;
}
}
else
{
passwordIndex = 0;
}
if (key == 'C')
{
Serial.println("Turning off LED.");
digitalWrite(ledPin, LOW);
}
}
}
char getKey()
{
char key = 0;
for(int column = 0; column < numCols; column++)
{
digitalWrite(colPins[column],LOW); // Activate the current column.
for(int row = 0; row < numRows; row++) // Scan all rows for
// a key press.
{
if(digitalRead(rowPins[row]) == LOW) // Is a key pressed?
{
delay(debounceTime); // debounce
while(digitalRead(rowPins[row]) == LOW); // wait for key to be released
key = keymap[row][column]; // Remember which key
// was pressed.
}
}
digitalWrite(colPins[column],HIGH); // De-activate the current column.
}
return key; // returns the key pressed or 0 if none
}