#include <Wire.h>
#include <RTClib.h>
RTC_DS3231 rtc; // Create RTC instance
const int relayPin = 23; // GPIO pin connected to relay
const int switchPin = 5;
// Set the on and off times
// const int onHour = 18; // 6:00 PM
const int onHour = 6; // 6:00 PM
const int onMinute = 0;
const int offHour = 6; // 6:00 AM
const int offMinute = 0;
bool manualOverride = false;
bool lightState = false;
void setup() {
Serial.begin(115200);
pinMode(relayPin, OUTPUT);
pinMode(switchPin, INPUT_PULLUP);
digitalWrite(relayPin, LOW); // Turn relay off initially
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (rtc.lostPower()) {
Serial.println("RTC lost power, setting time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void loop() {
bool switchState = digitalRead(switchPin);
Serial.print("switch state");
Serial.println(switchState);
if (switchState == LOW) {
Serial.println("switch has pressed");
manualOverride = !manualOverride;
// manualOverride = true;
lightState = !lightState; // Toggle the light state
delay(500); // Debounce delay
}
Serial.print("light state");
Serial.println(lightState);
if(lightState) {
digitalWrite(relayPin, HIGH);
} else {
digitalWrite(relayPin, LOW);
}
if (manualOverride) {
// If manual override is active, control the relay manually based on lightState
if (lightState) {
digitalWrite(relayPin, HIGH); // Turn the light on
Serial.println("Manual Override: Light is ON");
} else {
digitalWrite(relayPin, LOW); // Turn the light off
Serial.println("Manual Override: Light is OFF");
}
} else {
// Automatic mode based on time
DateTime now = rtc.now(); // Get current time from RTC
int currentHour = now.hour();
int currentMinute = now.minute();
// Turn the light on if current time is between onHour:onMinute and offHour:offMinute
if ((currentHour > onHour || (currentHour == onHour && currentMinute >= onMinute)) ||
(currentHour < offHour || (currentHour == offHour && currentMinute < offMinute))) {
lightState = true;
digitalWrite(relayPin, HIGH); // Turn relay on
Serial.println("Automatic Mode: Light is ON");
} else {
lightState = false;
digitalWrite(relayPin, LOW); // Turn relay off
Serial.println("Automatic Mode: Light is OFF");
}
}
delay(1000); // Wait for 1 second before checking again
}