Introduction: Adding Daylight Savings Time to Your RTC

Having made a little toddler clock for my daughter (just a RGB LED that turns green at 7:30am and red at 7:30pm to let her know the time) I realized in March that it does not have support for Daylight Savings Time.

Since I live in Canada which shares this with most of the United States, our Daylight Savings Time (DST for short) begins on the second Sunday in March and ends on the first Sunday of November.

Below is the code snippet you can add to your RTC project to add support for DST (tested on DS3231 with the RTClib.h library from Adafruit: https://github.com/adafruit/RTClib). It uses Arduino's EEPROM.h library to store the DST flag. It works best if the RTC project is always plugged in (as it updates at 2am) but there is a piece of code in the setup() function that lets you very quickly adjust DST if you miss the time window (if the project is not plugged in all the time) Note that RTClib uses 0 to 6 for days, 0 being Sunday.

#include <EEPROM.h>
#include <RTClib.h>

RTC_DS3231 rtc; int DST;

void setup() {

DST = EEPROM.get(0, DST);

if(DST != 0 && DST != 1)

{

DST = 1;

EEPROM.put(0, DST);

}

// Uncomment the following 2 lines if you need to set the DST (if you miss the actual day etc). Change the +1 to -1 in the fall. // DateTime t2 = rtc.now(); // rtc.adjust(DateTime(t2.year(), t2.month(), t2.day(), t2.hour()+1, t2.minute(), t2.second()));

}

void loop() {

DateTime now = rtc.now();

if (now.dayOfTheWeek() == 0 && now.month() == 3 && now.day() >= 8 && now.day() <= 16 && now.hour() == 2 && now.minute() == 0 && now.second() == 0 && DST == 0) {

rtc.adjust(DateTime(now.year(), now.month(), now.day(), now.hour()+1, now.minute(), now.second())); DST = 1; EEPROM.put(0, DST);

} else if(now.dayOfTheWeek() == 0 && now.month() == 11 && now.day() >= 1 && now.day() <= 8 && now.hour() == 2 && now.minute() == 0 && now.second() == 0 && DST == 1) {

rtc.adjust(DateTime(now.year(), now.month(), now.day(), now.hour()-1, now.minute(), now.second())); DST = 0; EEPROM.put(0, DST);

}

}

Comments