//////////PERFECTLY WORKING//////////////////
#include <LiquidCrystal.h>
#include <Keypad.h>
// —— PIN ASSIGNMENTS ——
// Parallel LCD (4‑bit mode):
// RS → D11
// E → D12
// D4 → D13
// D5 → D14
// D6 → D15
// D7 → D0
LiquidCrystal lcd(11, 12, 13, 14, 15, 0);
// Keypad rows and columns:
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'}
};
byte rowPins[ROWS] = {2, 3, 4, 5}; // D2–D5
byte colPins[COLS] = {6, 7, 8, 9}; // D6–D9
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Push‑button:
const int BUTTON_PIN = 10; // D10, wired with INPUT_PULLUP
// —— STATE VARIABLES ——
bool lcdVisible = true;
int lastButtonState = HIGH;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;
int pressCount = 0;
unsigned long firstPressTime = 0;
#define MAX_CHARS 20
String buffer = "";
// —— SETUP ——
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP); // Set button pin to input with pull-up
lcd.begin(20, 4); // Initialize 20x4 LCD
lcd.setCursor(0, 0);
lcd.print("System Ready");
delay(1000);
lcd.clear();
}
// —— MAIN LOOP ——
void loop() {
handleButton();
handleKeypad();
}
// —— BUTTON HANDLER ——
void handleButton() {
static int lastState = HIGH;
static unsigned long lastDebounce = 0;
int reading = digitalRead(BUTTON_PIN);
// Debounce check
if (reading != lastState && (millis() - lastDebounce) > debounceDelay) {
lastDebounce = millis();
// Handle visibility directly: pressed = OFF, released = ON
if (reading == LOW) {
lcd.noDisplay();
lcdVisible = false;
// Count button press for triple-press-clear logic
if (pressCount == 0) {
firstPressTime = millis();
}
pressCount++;
if (pressCount == 3 && (millis() - firstPressTime <= 3000)) {
lcd.clear();
buffer = ""; // 🔥 Clear buffer too!
lcd.setCursor(0, 0);
lcd.print("Display Cleared");
delay(1000);
lcd.clear();
pressCount = 0;
} else if (millis() - firstPressTime > 3000) {
pressCount = 1;
firstPressTime = millis();
}
} else if (reading == HIGH) {
lcd.display(); // Button released: show LCD again
lcdVisible = true;
}
}
lastState = reading;
}
// —— KEYPAD HANDLER ——
void handleKeypad() {
char key = keypad.getKey();
if (key && lcdVisible) {
// Maintain rolling buffer of last 20 characters
if (buffer.length() >= MAX_CHARS) {
buffer = buffer.substring(1); // Remove first character if buffer exceeds MAX_CHARS
}
buffer += key;
// Update LCD display with the buffer
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(buffer);
}
}