RTCZero
RTCZero copied to clipboard
Add method to set time from compiler time
trafficstars
It would be handy to be able to set the time from the C TIME and DATE variables. For example:
https://github.com/ITPNYU/clock-club/tree/master/Microcontroller_Time_Setting_Methods/CompileTimeSet
Here is a function you can adapt to your program to get compile date-time to Unix time...
#include <Arduino.h>
#include <TimeLib.h>
#include <RTCZero.h>
#include <stdio.h>
time_t cvt_date(char const *date, char const *time);
void print2digits(int number);
/* Create an rtc object */
RTCZero rtc;
void setup()
{
Serial.begin(115200);
delay(5000);
Serial.println("Set Compile time to RTC");
// Show raw system strings
Serial.println(String("__DATE__ = ") + __DATE__);
Serial.println(String("__TIME__ = ") + __TIME__);
rtc.begin(); // initialize RTC
// set system time = compile time
rtc.setEpoch(cvt_date(__DATE__, __TIME__));
Serial.print("Unix Time: ");
Serial.println(rtc.getEpoch());
}
time_t cvt_date(char const *date, char const *time)
{
char s_month[5];
int year, day;
int hour, minute, second;
tmElements_t t;
static const char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
sscanf(date, "%s %d %d", s_month, &day, &year);
//sscanf(time, "%2hhd %*c %2hhd %*c %2hhd", &t.Hour, &t.Minute, &t.Second);
sscanf(time, "%2d %*c %2d %*c %2d", &hour, &minute, &second);
// Find where is s_month in month_names. Deduce month value.
t.Month = (strstr(month_names, s_month) - month_names) / 3 + 1;
t.Day = day;
// year can be given as '2010' or '10'. It is converted to years since 1970
if (year > 99) t.Year = year - 1970;
else t.Year = year + 50;
t.Hour = hour;
t.Minute = minute;
t.Second = second;
return makeTime(t);
}
void loop() {
}