#include <Arduino.h>
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
// Keypad configuration
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
// ESP32 GPIO pins connected to keypad
byte rowPins[ROWS] = {19, 18, 5, 17}; // Connect to the row pinouts of the keypad
byte colPins[COLS] = {16, 4, 0, 2}; // Connect to the column pinouts of the keypad
// Initialize keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// LCD Configuration
#define LCD_ADDR 0x27 // I2C address (common for most I2C LCD adapters)
#define LCD_COLS 16 // Number of columns
#define LCD_ROWS 2 // Number of rows
// I2C pins for LCD
#define SDA_PIN 21
#define SCL_PIN 22
// Initialize LCD
LiquidCrystal_I2C lcd(LCD_ADDR, LCD_COLS, LCD_ROWS);
// Variables for input handling
String inputBuffer = "";
unsigned long lastKeyPressTime = 0;
const unsigned long keyTimeout = 3000; // Clear input after 3 seconds of no activity
void setup() {
// Initialize Serial for debugging
Serial.begin(115200);
Serial.println("ESP32 Keypad and LCD Example");
// Initialize I2C for LCD
Wire.begin(SDA_PIN, SCL_PIN);
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("4x4 Keypad Demo");
lcd.setCursor(0, 1);
lcd.print("Press a key...");
Serial.println("Setup completed");
}
void loop() {
// Check for keypress
char key = keypad.getKey();
if (key) {
// Update the last keypress time
lastKeyPressTime = millis();
Serial.print("Key pressed: ");
Serial.println(key);
// Add key to input buffer
if (inputBuffer.length() < 16) { // Prevent buffer overflow
inputBuffer += key;
}
// Update LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Key pressed: ");
lcd.print(key);
lcd.setCursor(0, 1);
lcd.print("Input: ");
lcd.print(inputBuffer);
// Special handling for certain keys
if (key == '#') {
// Clear input buffer when # is pressed
delay(500); // Brief delay for visual feedback
inputBuffer = "";
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Input cleared");
lcd.setCursor(0, 1);
lcd.print("Press a key...");
delay(1000);
}
else if (key == '*') {
// Delete last character when * is pressed
if (inputBuffer.length() > 0) {
inputBuffer.remove(inputBuffer.length() - 2, 1); // Remove the character before *
inputBuffer.remove(inputBuffer.length() - 1, 1); // Remove the *
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Deleted last");
lcd.setCursor(0, 1);
lcd.print("Input: ");
lcd.print(inputBuffer);
delay(500);
}
}
}
// Check for timeout to clear input
if (inputBuffer.length() > 0 && (millis() - lastKeyPressTime > keyTimeout)) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Timeout - Reset");
lcd.setCursor(0, 1);
lcd.print("Press a key...");
inputBuffer = "";
delay(1000);
}
}