Pseudo real-time clock using Ticker interruption, also implements time() and set_time() for platforms that don't (such as mBuino)

Fork of PseudoRTC by Shigenori Inoue

Revision:
2:7d153bc7403f
Parent:
0:9ab044e24d20
Child:
3:c8bfeb8a2989
--- a/PseudoRTC.cpp	Sat Sep 20 14:25:38 2014 +0000
+++ b/PseudoRTC.cpp	Mon Aug 03 09:04:48 2015 +0000
@@ -26,6 +26,7 @@
     hour = 1;
     minute = 0;
     second = 0;
+    unixtime = 0;
     t.attach(this, &PseudoRTC::tictoc, 1);
 }
 
@@ -35,16 +36,46 @@
 void PseudoRTC::setTime(int y, int mo, int d, int h, int mi, int s)
 {
     /* Check the validity */
-    if (month < 13 && day < 32 && hour < 24 && minute < 60 && second < 60) {
+    if (month < 13 && day < 32 && hour < 24 && minute < 60 && second < 60)
+    {
         year = y;
         month = mo;
         day = d;
         hour = h;
         minute = mi;
         second = s;
+        unixtime=toUnixTime();
     }
 }
 
+void PseudoRTC::set_time(time_t thetime)
+{
+    unixtime=thetime;
+
+    struct tm *ptm;
+    ptm = localtime (&unixtime);
+
+    second=ptm->tm_sec;
+    minute=ptm->tm_min;
+    hour=ptm->tm_hour;
+    day=ptm->tm_mday;
+    month=ptm->tm_mon;
+    year=ptm->tm_year+1900;
+}
+
+time_t PseudoRTC::time(time_t* timer=NULL)
+{
+    if(timer!=NULL)
+        *timer=unixtime;
+    return(unixtime);
+}
+
+time_t PseudoRTC::addSeconds(int nSec)
+{   // add (or substract) some seconds to the rtc to adjust time as needed
+    this->set_time(unixtime+nSec);
+    return(unixtime);
+} 
+
 int PseudoRTC::getYear(void)
 {
     return year;
@@ -75,8 +106,37 @@
     return second;
 }
 
+/****** private methods *******/
+time_t PseudoRTC::toUnixTime(void)
+{
+    struct tm tms;
+    /*
+        tm_sec  int seconds after the minute    0-61*
+        tm_min  int minutes after the hour  0-59
+        tm_hour int hours since midnight    0-23
+        tm_mday int day of the month    1-31
+        tm_mon  int months since January    0-11
+        tm_year int years since 1900    
+        tm_wday int days since Sunday   0-6
+        tm_yday int days since January 1    0-365
+        tm_isdst    int Daylight Saving Time flag   
+    */
+    tms.tm_sec=second;
+    tms.tm_min=minute;
+    tms.tm_hour=hour;
+    tms.tm_mday=day;
+    tms.tm_mon=month;
+    tms.tm_year=year-1900;
+    return(mktime(&tms));
+}
+
 void PseudoRTC::tictoc(void)
 {
+    unixtime++;
+    this->set_time(unixtime);   // update second, minute, hour, etc. member variables
+
+/* old code    
+    
     if(second < 59) {
         second++;
     } else {
@@ -106,4 +166,5 @@
     if(month > 12) {
         year++;
     }
+*/
 }
\ No newline at end of file