#include <Wire.h> // include the Wire library for I2C communication
#include <RTClib.h> // include the RTC library
RTC_DS3231 rtc; // create an RTC_DS3231 object
#define relayPin 2 // define the pin connected to the relay
// Define the times for relay operation
const int onHour1 = 06;
const int onMinute1 = 00;
const int offHour1 = 9;
const int offMinute1 = 00;
const int onHour2 = 11;
const int onMinute2 = 00;
const int offHour2 = 13;
const int offMinute2 = 00;
const int onHour3 = 16;
const int onMinute3 = 00;
const int offHour3 = 18;
const int offMinute3 = 00;
void setup() {
Wire.begin(); // initialize I2C communication
Serial.begin(9600); // initialize serial communication
// Check if the RTC is running
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
// Check if the RTC lost power and if so, set the time
if (rtc.lostPower()) {
Serial.println("RTC lost power, setting the time...");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
pinMode(relayPin, OUTPUT); // set the relay pin as output
}
void loop() {
DateTime now = rtc.now(); // get the current time
// Check if it's time to turn on the relay for the first time
if (now.hour() == onHour1 && now.minute() == onMinute1) {
digitalWrite(relayPin, HIGH); // turn on the relay
Serial.println("Relay turned ON - 1");
}
// Check if it's time to turn off the relay for the first time
if (now.hour() == offHour1 && now.minute() == offMinute1) {
digitalWrite(relayPin, LOW); // turn off the relay
Serial.println("Relay turned OFF - 1");
}
// Check if it's time to turn on the relay for the second time
if (now.hour() == onHour2 && now.minute() == onMinute2) {
digitalWrite(relayPin, HIGH); // turn on the relay
Serial.println("Relay turned ON - 2");
}
// Check if it's time to turn off the relay for the second time
if (now.hour() == offHour2 && now.minute() == offMinute2) {
digitalWrite(relayPin, LOW); // turn off the relay
Serial.println("Relay turned OFF - 2");
}
// Check if it's time to turn on the relay for the third time
if (now.hour() == onHour3 && now.minute() == onMinute3) {
digitalWrite(relayPin, HIGH); // turn on the relay
Serial.println("Relay turned ON - 3");
}
// Check if it's time to turn off the relay for the third time
if (now.hour() == offHour3 && now.minute() == offMinute3) {
digitalWrite(relayPin, LOW); // turn off the relay
Serial.println("Relay turned OFF - 3");
}
delay(1000); // wait for a second before checking again
}