#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
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] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
LiquidCrystal_I2C lcd(0x27, 16, 2);
String input = "0000"; // Initialize input string with "00:00"
bool timerRunning = false;
unsigned long startTime = 0;
unsigned long remainingTime = 0;
void setup() {
lcd.init(); // initialize the LCD
lcd.backlight(); // turn on backlight
Serial.begin(9600); // initialize serial communication
}
void loop() {
char key = keypad.getKey();
if (key == 'A' && !timerRunning) {
startTimer();
} else if (key == 'B') {
restartTimer();
} else if (key >= '0' && key <= '9' && !timerRunning) {
updateInput(key);
}
// Display the input on LCD
displayInput();
// Start countdown if timer is running
if (timerRunning) {
updateTimer();
displayRemainingTime();
}
}
void startTimer() {
timerRunning = true;
startTime = millis(); // Store the current time as start time
int minutes = input.substring(0, 2).toInt(); // Get the first two digits as minutes
int seconds = input.substring(2).toInt(); // Get the last two digits as seconds
remainingTime = minutes * 60 + seconds; // Convert minutes to seconds and add to seconds
Serial.print("startTime: ");
Serial.println(startTime);
Serial.print("remainingTime: ");
Serial.println(remainingTime);
}
void restartTimer() {
timerRunning = false;
remainingTime = 0; // Set remaining time to 0
startTime = millis(); // Reset the start time
}
void updateInput(char key) {
if (input.length() < 4) {
// Append the key to the input string
input += key;
} else {
// Shift the input string to the left and replace the last character with the new key
input = input.substring(1) + key;
}
}
void displayInput() {
// lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Time: ");
if (input == "" || input == "0000") {
lcd.print("00:00");
} else {
lcd.print(input.substring(0, 2));
lcd.print(":");
lcd.print(input.substring(2));
}
}
void updateTimer() {
unsigned long elapsedTime = millis() - startTime;
if (elapsedTime >= 1000) {
remainingTime--; // Decrease remaining time by 1 second every second
startTime = millis(); // Reset start time
}
}
void displayRemainingTime() {
unsigned long minutes = remainingTime / 60;
unsigned long seconds = remainingTime % 60;
lcd.setCursor(0, 1);
lcd.print("Remaining: ");
if (minutes < 10) {
lcd.print("0");
}
lcd.print(minutes);
lcd.print(":");
if (seconds < 10) {
lcd.print("0");
}
lcd.print(seconds);
}