This is a complete sketch
Code:
#include <TimeLib.h> // https://github.com/PaulStoffregen/Time
time_t clock;
int i = 0;
void setup()
{
Serial.begin(115200);
while (!Serial) ;
// set the Time library to use Teensy 4.0's RTC to keep time
setSyncProvider(getTeensy3Time);
setSyncInterval(60);
if (timeStatus()!= timeSet) Serial.println("Init: RTC -> Unable to sync with the RTC");
else Serial.println("Init: RTC has set the system time");
}
void loop()
{
i = check_btn(); // read which button has been pressed
if (i==1) RTC_Time_set(60); // + 1 minute
if (i==2) RTC_Time_set(-60); // - 1 minute
if (i==10) RTC_Time_set(+3600); // + 1 hour
if (i==20) RTC_Time_set(-3600); // - 1 hour
display_time(); // show time on screen
}
time_t getTeensy3Time()
{
return Teensy3Clock.get();
}
void RTC_Time_set(int x) // add x seconds
{
clock = now();
setTime(clock + x);
delay(100);
Teensy3Clock.set(now());
}
int check_btn()
{
if (Serial.available() > 0)
{
String data = "";
char x;
while (Serial.available())
{
x = Serial.read();
if (isDigit(x))
data += x - '0';
}
return data.toInt();
}
}
void display_time()
{
char s[10];
sprintf(s, "%02d:%02d:%02d", hour(), minute(), second());
Serial.println(s);
delay(1000);
}
Serial Monitor:
Code:
Init: RTC has set the system time
19:35:07
19:35:08
19:35:09
19:35:10
19:35:11
19:35:12
19:35:13
19:35:14
19:35:15
19:35:16
19:35:17
18:35:18 // -1 hour
18:35:19
18:35:20
19:35:21 // +1 hour
20:35:22 // +1 hour
20:35:23
20:35:24
20:35:25
20:35:26
20:35:27
20:35:28
21:35:29 // +1 hour
21:35:30
21:35:31
21:35:32
21:35:33
21:35:34
21:35:35
Power off -> wait a few minutes -> power on
Code:
Init: RTC has set the system time
19:39:32
19:39:33
19:39:34
19:39:35
19:39:36