#include "RTClib.h"
RTC_DS1307 rtc;
uint32_t timeOn = 0;
uint32_t timeOff = 0;
uint32_t getSeconds( const uint8_t hours, const uint8_t minutes, const uint8_t seconds )
{
return ( hours * 3600UL ) + ( minutes * 60UL ) + seconds;
}
void setup()
{
Serial.begin( 115200 );
rtc.begin();
rtc.adjust( DateTime( 2023, 9, 21, 10, 9, 55 ) );
timeOn = getSeconds( 10, 10, 0 ); // LED will turn on at 10:10:00
timeOff = getSeconds( 10, 10, 5 ); // LED will turn off at 10:10:05
pinMode( LED_BUILTIN, OUTPUT );
digitalWrite( LED_BUILTIN, LOW );
}
void loop()
{
DateTime now = rtc.now();
uint8_t second = now.second();
static uint8_t second_prev = UINT8_MAX;
if ( second_prev != second )
{
second_prev = second;
uint8_t hour = now.hour();
uint8_t minute = now.minute();
char str[20];
snprintf( str, sizeof(str), "Time is %02hhu:%02hhu:%02hhu", hour, minute, second );
Serial.println( str );
uint32_t seconds = getSeconds( hour, minute, second );
bool invert = timeOff < timeOn;
bool inRange = seconds >= ( invert ? timeOff : timeOn ) && seconds < ( invert ? timeOn : timeOff );
bool ledState = invert ? !inRange : inRange;
static bool ledState_prev = !ledState;
if ( ledState_prev != ledState )
{
ledState_prev = ledState;
Serial.print( "LED " );
Serial.println( ledState ? "ON" : "OFF" );
digitalWrite( LED_BUILTIN, ledState ? HIGH : LOW );
}
}
}