#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Initialize the LCD with the correct I2C address and dimensions
LiquidCrystal_I2C lcd(0x27, 16, 2); // Change 0x27 to your LCD's I2C address
// Pin definitions
const int buttonPin = 4; // Button to change timer
const int alarmPin1 = 3; // Alarm output 1
const int alarmPin2 = 2; // Alarm output 2
// Timer variables
unsigned long timerDuration = 60 * 60 * 1000; // Default: 60 minutes in milliseconds
unsigned long startTime = 0;
bool timerRunning = false;
bool alarmTriggered = false;
// Timer options
const int timerOptions[] = {15, 30, 45, 60}; // Timer options in minutes
int currentTimerIndex = 3; // Default: 60 minutes (index 3)
void setup() {
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Timer: 60 min");
// Set pin modes
pinMode(buttonPin, INPUT_PULLUP);
pinMode(alarmPin1, OUTPUT);
pinMode(alarmPin2, OUTPUT);
// Initialize outputs
digitalWrite(alarmPin1, LOW);
digitalWrite(alarmPin2, HIGH);
}
void loop() {
// Check if the button is pressed to change the timer
if (digitalRead(buttonPin) == LOW) {
delay(200); // Debounce delay
changeTimer();
while (digitalRead(buttonPin) == LOW); // Wait for button release
}
// Start the timer if not already running
if (!timerRunning && !alarmTriggered) {
startTime = millis();
timerRunning = true;
lcd.setCursor(0, 1);
lcd.print("Running... ");
}
// Check if the timer has expired
if (timerRunning && (millis() - startTime >= timerDuration)) {
timerRunning = false;
triggerAlarm();
}
}
void changeTimer() {
// Cycle through timer options
currentTimerIndex = (currentTimerIndex + 1) % 4;
timerDuration = timerOptions[currentTimerIndex] * 60 * 1000; // Convert minutes to milliseconds
// Update the LCD display
lcd.setCursor(0, 0);
lcd.print("Timer: ");
lcd.print(timerOptions[currentTimerIndex]);
lcd.print(" min ");
// Reset the timer if it was running
if (timerRunning) {
timerRunning = false;
lcd.setCursor(0, 1);
lcd.print("Press to start");
}
}
void triggerAlarm() {
// Trigger the alarm
digitalWrite(alarmPin1, HIGH);
digitalWrite(alarmPin2, LOW);
alarmTriggered = true;
// Display alarm message on LCD
lcd.setCursor(0, 1);
lcd.print("Alarm! ");
// Keep the alarm on until reset
while (alarmTriggered) {
if (digitalRead(buttonPin) == LOW) {
delay(200); // Debounce delay
resetAlarm();
while (digitalRead(buttonPin) == LOW); // Wait for button release
}
}
}
void resetAlarm() {
// Reset the alarm and timer
digitalWrite(alarmPin1, LOW);
digitalWrite(alarmPin2, HIGH);
alarmTriggered = false;
timerRunning = false;
// Update the LCD display
lcd.setCursor(0, 1);
lcd.print("Reset ");
delay(1000);
lcd.setCursor(0, 1);
lcd.print("Press to start");
}