I want to type in a specific numeric combination on a 4x4 keypad: '338', and when that happens I want to have a green LED blink 3 times. I have been using Tinkercad and when I start the simulation and press the correct numbers on the keypad, nothing happens. When I press the numbers on the keypad I will see them quickly flash then disappear in the Serial Monitor but the LED doesn't blink.
int h;
int z;
int e;
int m;
int a;
#include <Keypad.h>
// keypad type definition
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
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}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
int count=1;
bool codeEntered = false;
Keypad myKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const int ledPin_1 = 11; // pin for LED
void setup()
{
Serial.begin(9600);
pinMode(ledPin_1, OUTPUT);
}
// function for blinking LED
void blinkLED() {
for (int i = 0; i < 3; i++) {
digitalWrite(ledPin_1, HIGH);
delay(250);
digitalWrite(ledPin_1, LOW);
delay(250);
}
}
void loop()
{
char key = myKeypad.getKey();
if (key != NO_KEY) {
int a = key - '0';
Serial.println(count);
Serial.println("a=" + String(a));
switch (count){
case 1:
if (key != NO_KEY){
h = a * 100;
Serial.println("h=" + String(h));
}
break;
case 2:
if (key != NO_KEY){
z = a * 10;
Serial.println("z=" + String(z));
}
break;
case 3:
if (key != NO_KEY){
e = a;
Serial.println("e=" + String(e));}
m = h + z + e;
Serial.println("m=" + String(m));
if (m == 338) {
codeEntered = true; // check if code entered is '338'
}
break;
}
}
count++; //adds 1 to count
if (count==4) //checks for count=4
{
Serial.println();
count=1;
if (codeEntered) {
blinkLED();
codeEntered = false;
} //reset count
}
}
I tried a different code to check that the keypad was hooked up correctly and when I do this one the serial monitor prints the number I press and it stays in the serial monitor, whereas when i do my original code it flashes for less than 1 second then disappears. So I am assuming there is something wrong with my code and not my circuit setup.
#include <Keypad.h>
// keypad type definition
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
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}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
Keypad myKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup()
{
Serial.begin(9600);
}
void loop()
{
char key = myKeypad.getKey();
if (key != NO_KEY) {
Serial.println(key);
}
}
