#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 16, 2);
const char on[4] = "7123";
const char off[4] = "4569";
const int numRows = 4; // number of rows in the keypad
const int numCols = 4; // number of columns
const int ledpin = 12;
const int debounceTime = 20; // number of milliseconds for switch to be stable
char pressedKeys[4]; // Array to store pressed keys
int keyIndex = 0; // Index for storing pressed keys
const char keymap[numRows][numCols] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
const int rowPins[numRows] = { 2,3 ,4 ,5 }; // Rows 0 through 3
const int colPins[numCols] = { 6, 7, 8, 9 }; // Columns 0 through 3
void setup() {
pinMode(ledpin, 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
digitalWrite(colPins[column], HIGH); // Make all columns inactive
}
lcd.init();
lcd.backlight();
lcd.cursor();
lcd.println("Got key:");
}
void loop() {
char key = getKey();
if (key != 0) {
pressedKeys[keyIndex] = key; // Store the pressed key
keyIndex++; // Increment the index
lcd.print(key);
if (keyIndex >= 3) {
pressedKeys[keyIndex] = '\0'; // Add null terminator to make it a valid string
int result = strcmp(on, pressedKeys);
int result2 = strcmp(off, pressedKeys);
if (result == 0) {
digitalWrite(ledpin, HIGH);
lcd.clear();
} else if (result2 == 0) {
digitalWrite(ledpin, LOW);
}
// Reset the array and index for the next set of pressed keys
memset(pressedKeys, 0, sizeof(pressedKeys));
keyIndex = 0;
}
}
}
// returns the key pressed, or 0 if no key is pressed
char getKey() {
char key = 0; // 0 indicates no key pressed
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) {
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
}