I am new to Arduino. I am using a D1307 connected with my Arduino and I am trying to extract the day of the week (e.g. Monday). My code:
//www.elegoo.com
//2018.10.24
#include <Wire.h>
#include <DS3231.h>
#include <TimeLib.h>
DS3231 clock;
RTCDateTime dt;
int dayOfWeek;
void setup()
{
Serial.begin(9600);
Serial.println("Initialize RTC module");
// Initialize DS3231
clock.begin();
// Manual (YYYY, MM, DD, HH, II, SS
// clock.setDateTime(2016, 12, 9, 11, 46, 00);
// Send sketch compiling time to Arduino
clock.setDateTime(__DATE__, __TIME__);
/*
Tips:This command will be executed every time when Arduino restarts.
Comment this line out to store the memory of DS3231 module
*/
}
void loop()
{
dt = clock.getDateTime(); // dt is object of class RTCDateTime
// For leading zero look to DS3231_dateformat example
Serial.print("Raw data: ");
Serial.print(dt.year); Serial.print("-");
Serial.print(dt.month); Serial.print("-");
Serial.print(dt.day); Serial.print(" ");
Serial.print(dt.hour); Serial.print(":");
Serial.print(dt.minute); Serial.print(":");
Serial.print(dt.second); Serial.println("");
dayOfWeek = weekday();
Serial.print(dayStr(dayOfWeek)); Serial.println("");
delay(1000);
}
Which returns:
Raw data: 2021-9-18 12:30:34
Thursday
where I would expect Saturday.
Apparently I am not using the weekday() correctly, but apparently it does not need any arguments so I am not sure how it could extract the day in the week from e.g. my RTCDateTime object.
You can use functions in the TimeLib to act as a perpetual calendar, but the way you are setting the time does not automagically calculate the day of week.
This lets you set all the registers. use a day value from 1 to 7 inclusive.
If you set it manually to just before midnight, you can then disable the setting (comment out the setDateTime call). Run your program a few minutes later and the day will have incremented.
and leave TimeLib's weekday() out of it. Didn't you notice the first day printed was "Err", not any Sunday through Saturday? That was my clue to go looking…
Just pass the RTC's dt.dayOfWeek to dayStr.
And now I can say that the DS3231 library has a Zeller's congruence algorithm, so it does, in fact, set the day of week correctly for use with dayStr.
dayStr is the only thing you are using from TimeLib it seems.