#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
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'}
};
// Corrected keypad wiring: pin 1→32 through pin 8→13
byte rowPins[ROWS] = {32, 33, 25, 26};
byte colPins[COLS] = {27, 14, 12, 13};
Keypad keypad = Keypad(
makeKeymap(keys),
rowPins,
colPins,
ROWS,
COLS
);
enum UiMode {
HOME_SCREEN,
EDIT_ON_TIME,
EDIT_OFF_TIME
};
UiMode uiMode = HOME_SCREEN;
uint16_t onMinutes = 15;
uint16_t offMinutes = 4;
String enteredValue = "";
void printLine(byte row, String text) {
text = text.substring(0, 16);
while (text.length() < 16) {
text += " ";
}
lcd.setCursor(0, row);
lcd.print(text);
}
void showHomeScreen() {
char schedule[17];
snprintf(
schedule,
sizeof(schedule),
"ON:%03u OFF:%03u",
onMinutes,
offMinutes
);
printLine(0, schedule);
printLine(1, "A=ON B=OFF");
}
void showEditScreen() {
if (uiMode == EDIT_ON_TIME) {
printLine(0, "SET ON TIME");
} else {
printLine(0, "SET OFF TIME");
}
String secondLine = ">";
if (enteredValue.length() == 0) {
secondLine += "___";
} else {
secondLine += enteredValue;
}
secondLine += " D=SAVE";
printLine(1, secondLine);
}
void setup() {
Serial.begin(115200);
Wire.begin(21, 22);
lcd.init();
lcd.backlight();
printLine(0, "INDUSTRIAL");
printLine(1, "TIMER STARTING");
delay(1500);
showHomeScreen();
}
void loop() {
char key = keypad.getKey();
if (!key) {
return;
}
Serial.print("Pressed key: ");
Serial.println(key);
if (uiMode == HOME_SCREEN) {
if (key == 'A') {
uiMode = EDIT_ON_TIME;
enteredValue = "";
showEditScreen();
} else if (key == 'B') {
uiMode = EDIT_OFF_TIME;
enteredValue = "";
showEditScreen();
}
return;
}
if (key >= '0' && key <= '9') {
if (enteredValue.length() < 3) {
enteredValue += key;
showEditScreen();
}
} else if (key == '#') {
if (enteredValue.length() > 0) {
enteredValue.remove(enteredValue.length() - 1);
showEditScreen();
}
} else if (key == 'C') {
uiMode = HOME_SCREEN;
enteredValue = "";
showHomeScreen();
} else if (key == 'D') {
int value = enteredValue.toInt();
if (value >= 1 && value <= 999) {
if (uiMode == EDIT_ON_TIME) {
onMinutes = value;
printLine(0, "ON TIME SAVED");
} else {
offMinutes = value;
printLine(0, "OFF TIME SAVED");
}
printLine(1, "VALUE ACCEPTED");
delay(1200);
} else {
printLine(0, "INVALID VALUE");
printLine(1, "USE 1 TO 999");
delay(1200);
}
uiMode = HOME_SCREEN;
enteredValue = "";
showHomeScreen();
}
}