#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD address to 0x27 for a 16 chars and 2 line display
const int numRows = 4;
const int numCols = 4;
char keys[numRows][numCols] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[numRows] = {0,1,2,3}; //connect to the row pinouts of the keypad
byte colPins[numCols] = {A0,A1,A2,A3}; //connect to the column pinouts of the keypad
void setup() {
Serial.begin(9600);
lcd.init(); // initialize the lcd
lcd.backlight();
lcd.print("Hello World");
delay(3000);
lcd.clear();
}
void loop() {
char key = getKey();
if (key != NO_KEY) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Pressed Key:");
lcd.setCursor(0, 1);
lcd.print(key);
delay(1000);
}
}
char getKey() {
char key = NO_KEY;
for (int i = 0; i < numCols; i++) {
pinMode(colPins[i], OUTPUT);
digitalWrite(colPins[i], LOW);
for (int j = 0; j < numRows; j++) {
pinMode(rowPins[j], INPUT_PULLUP);
if (digitalRead(rowPins[j]) == LOW) {
key = keys[j][i];
while (digitalRead(rowPins[j]) == LOW)
delay(10);
}
pinMode(rowPins[j], INPUT);
}
pinMode(colPins[i], INPUT);
digitalWrite(colPins[i], HIGH);
}
return key;
}