#include <Wire.h>
#include <RTClib.h>
// Initialize the RTC
RTC_DS3231 rtc;
// Define the pin for the switch
const int switchPin = 2;
int lastSwitchState = HIGH; // Assume switch is initially OFF
int currentSwitchState = HIGH;
unsigned long previousMillis = 0;
unsigned long offTimeStart = 0;
const long interval = 60000; // 1 minute in milliseconds
const long warningInterval = 2 * interval; // 2 minutes in milliseconds
void setup() {
Serial.begin(9600);
pinMode(switchPin, INPUT_PULLUP); // Internal pull-up resistor enabled
// Start the RTC
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
// Check if the RTC is running
if (rtc.lostPower()) {
Serial.println("RTC lost power, setting the time!");
// rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // Uncomment to set RTC to compile time
}
}
void loop() {
// Get the current time from the RTC
DateTime now = rtc.now();
// Get the current switch state
currentSwitchState = digitalRead(switchPin);
// Check if a minute has passed
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
// Print the current time and switch status
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(" ");
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.print(" - Switch is ");
Serial.println(currentSwitchState == LOW ? "ON" : "OFF");
// If the switch is OFF, start or continue counting the off time
if (currentSwitchState == HIGH) {
if (offTimeStart == 0) {
offTimeStart = currentMillis; // Start counting when the switch goes OFF
}
// Check if the switch has been OFF for more than 2 minutes
if (currentMillis - offTimeStart >= warningInterval) {
Serial.println("Warning: Switch has been OFF for more than 2 minutes!");
offTimeStart = currentMillis; // Reset to prevent multiple warnings
}
} else {
offTimeStart = 0; // Reset the off time counter if the switch is ON
}
}
}