#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define BUTTON_PIN 2
#define START_BUTTON_PIN 3
#define ALARM_PIN 4
LiquidCrystal_I2C lcd(0x27, 16, 2);
int timerDurations[] = {1, 15, 30, 45, 60};
int currentTimerIndex = 4; // Default to 60 minutes
int remainingTime;
bool timerRunning = false;
unsigned long previousMillis = 0;
const long interval = 1000; // 1 second in milliseconds
int resetButtonPressCount = 0; // Counter for reset button presses
unsigned long lastResetPressTime = 0; // Track the last time the reset button was pressed
const unsigned long resetTimeout = 3000; // Time window for counting resets (3 seconds)
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(START_BUTTON_PIN, INPUT_PULLUP);
pinMode(ALARM_PIN, OUTPUT);
lcd.init();
lcd.backlight();
resetTimer();
}
void loop() {
if (buttonPressed(BUTTON_PIN)) {
changeTimer();
}
if (buttonPressed(START_BUTTON_PIN)) {
if (!timerRunning && remainingTime == 0) {
resetTimer(); // Reset timer if it's finished
} else {
timerRunning = true;
}
}
if (timerRunning) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (remainingTime > 0) {
remainingTime--;
updateDisplay();
} else {
triggerAlarm();
}
}
}
// Check if the reset button is pressed more than 3 times within 3 seconds
if (resetButtonPressCount > 3 && (millis() - lastResetPressTime) <= resetTimeout) {
resetRunningTime(); // Reset the running time
resetButtonPressCount = 0; // Reset the counter
}
}
bool buttonPressed(int pin) {
if (digitalRead(pin) == LOW) {
delay(50); // Debounce delay
if (digitalRead(pin) == LOW) {
while (digitalRead(pin) == LOW); // Wait for release
// If the button is the reset button (BUTTON_PIN), increment the counter
if (pin == BUTTON_PIN) {
resetButtonPressCount++;
lastResetPressTime = millis(); // Update the last press time
}
return true;
}
}
return false;
}
void changeTimer() {
if (!timerRunning) {
currentTimerIndex = (currentTimerIndex + 1) % 5; // Cycle through all options
resetTimer();
}
}
void resetTimer() {
remainingTime = timerDurations[currentTimerIndex] * 60; // Convert minutes to seconds
updateDisplay();
digitalWrite(ALARM_PIN, LOW); // Ensure alarm is off on reset
timerRunning = false;
}
void resetRunningTime() {
remainingTime = timerDurations[currentTimerIndex] * 60; // Reset to the selected duration
updateDisplay();
digitalWrite(ALARM_PIN, LOW); // Ensure alarm is off
timerRunning = false; // Stop the timer
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Time Reset!");
delay(1000); // Display the message for 1 second
updateDisplay(); // Update the display with the new time
}
void updateDisplay() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Time left: ");
lcd.setCursor(0, 1);
lcd.print(remainingTime / 60);
lcd.print(" min ");
lcd.print(remainingTime % 60);
lcd.print(" sec");
}
void triggerAlarm() {
digitalWrite(ALARM_PIN, HIGH);
timerRunning = false;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Time's up!");
}