Class RTC
RTC Class
Members
Public Constructors |
|
---|---|
A public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named RTC. |
Public Methods |
|
---|---|
RTC:: Init |
Initializes the RTC device, including the Clock, the RTC registers, and other functions |
RTC:: DeInit |
Deinitialize the RTC device |
RTC:: Write |
Set the specified timestamp in seconds to RTC |
RTC:: Read |
Get the current timestamp in seconds from RTC |
RTC:: Wait |
Wait for 1 second |
RTC:: SetEpoch |
Convert human-readable time to epoch time |
RTC::Init
/*
* This function describes how to use the RTC API.
* The RTC function is implemented by an independent BCD timer/counter.
* This example will print out the time information every second.
*/
#include <stdio.h>
#include <time.h>
#include “rtc.h”
#define YEAR 2020
#define MONTH 9
#define DAY 10
#define HOUR 20
#define MIN 30
#define SEC 40
/* Create an rtc object */
RTC rtc;
int32_t seconds;
struct tm *timeinfo;
void setup() {
Serial.begin(115200);
rtc.Init(); // initialize RTC
}
void loop() {
// step 1: convert user time to epoch
int epochTime = humanReadableToEpoch(YEAR, MONTH, DAY, HOUR, MIN, SEC);
// step 2: write epoch time to rtc
rtc.Write(epochTime);
while (1) {
seconds = rtc.Read();
printf(“Epoch Time (in s) since January 1, 1970 = %dsn”, seconds);
printf(“Time as a basic string = %s”, ctime(&seconds));
timeinfo = localtime(&seconds);
printf(“Time as a custom formatted string = %d-%d-%d %d:%d:%dn”,
(timeinfo->tm_year + 1900), (timeinfo->tm_mon + 1), timeinfo->tm_mday, timeinfo->tm_hour,
timeinfo->tm_min, timeinfo->tm_sec);
Serial.println();
rtc.wait(1);
}
}
// convert human readable time to epoch time
int humanReadableToEpoch(int year, int month, int day, int hour, int min, int sec) {
struct tm t;
time_t t_of_day;
t.tm_year = year - 1900; // Year - 1970
t.tm_mon = month - 1; // Month, where 0 = jan
t.tm_mday = day; // Day of the month
t.tm_hour = hour;
t.tm_min = min;
t.tm_sec = sec;
t.tm_isdst = -1; // Is DST on? 1 = yes, 0 = no, -1 = unknown
t_of_day = mktime(&t);
// printf(“seconds since the Epoch: %dn”, (long)t_of_day);
return t_of_day;
}
RTC::DeInit
RTC:: Write
RTC::Read
RTC:: Wait
RTC:: SetEpoch