/*
* TimeAlarmExample.pde
*
* This example calls alarm functions at 8:30 am and at 5:45 pm (17:45)
* and simulates turning lights on at night and off in the morning
* A weekly timer is set for Saturdays at 8:30:30
*
* A timer is called every 15 seconds
* Another timer is called once only after 10 seconds
*
* At startup the time is set to Jan 1 2011 8:29 am
*/
// Questions? Ask them here:
// http://forum.arduino.cc/index.php?topic=66054.0
#include <TimeLib.h>
#include <TimeAlarms.h>
AlarmId OneTimeAlarmId;
AlarmId OneMinuteId;
void setup() {
Serial.begin(115200);
while (!Serial) ; // wait for Arduino Serial Monitor
setTime(23,58,30,5,8,25); // set time to Saturday 8:29:00am Aug 5 2025
// create the alarms, to trigger at specific times
Alarm.alarmRepeat(0, 0, 0, BackupLog); // Backup log file and perform reset at midnight.
OneMinuteId = Alarm.timerRepeat(60, OneMinute); // Update time.
Alarm.timerRepeat(4, UpdateTimers); // Update timers.
Alarm.timerRepeat(300, HourlyTasks); // Hourly tasks
OneTimeAlarmId = Alarm.timerRepeat(20, DelayedAlarmHandler);
Alarm.disable(OneTimeAlarmId);
}
void loop() {
// digitalClockDisplay();
Alarm.delay(0); // wait one second between clock display
delay(10);
}
void OneMinute() {
char text[50] = {};
sprintf_P(text, PSTR("Internal time before correction: %02u:%02u:%02u"), hour(), minute(), second());
Serial.println(text);
setTime(hour(), minute(), second() + random(2, 100), day(), month(), year());
// Alarm.delay(0);
sprintf_P(text, PSTR("Internal time after correction: %02u:%02u:%02u"), hour(), minute(), second());
Serial.println(text);
// Alarm.write(OneMinuteId, 60);
digitalClockDisplay();
}
void digitalClockDisplay() {
// digital clock display of the time
Serial.print(hour());
printDigits(minute());
printDigits(second());
Serial.println();
}
void UpdateTimers() {
Serial.println("Updating timers function - 4 sec.");
digitalClockDisplay();
}
void HourlyTasks() {
Serial.println("Hourly tasks function - 5min.");
digitalClockDisplay();
}
void BackupLog() {
Serial.println("Backup log function - at midnight.");
digitalClockDisplay();
}
void DelayedAlarmHandler() {
Serial.println("Delayed alarm handler - 20sec.");
digitalClockDisplay();
}
void printDigits(int digits) {
Serial.print(":");
if (digits < 10)
Serial.print('0');
Serial.print(digits);
}