Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependents: espresso-machine-control SAT_OLED Mbedesclava Mbedmaestra ... more
You are viewing an older revision! See the latest version
Homepage
RTCLib¶
This was ported from Adafruit's RTCLib
Example¶
#include "DS1307.h"
class I2C2 : public I2C
{
public:
I2C2 ( PinName sda, PinName scl, int hz, const char *name = NULL) : I2C ( sda, scl, name) { frequency(hz * 100); };
};
I2C2 gI2c ( p28, p27, 100 );
RtsDs1307 gRtc ( gI2c );
Serial gSerial(USBTX, USBRX);
void printDT(char *pre, DateTime &dt)
{
gSerial.printf("%s - %u/%u/%02u %2u:%02u:%02u\r\n"
,pre
,dt.month(),dt.day(),dt.year()
,dt.hour(),dt.minute(),dt.second()
);
}
bool rtcUpdate(RtcDs1307 &rtc, int32_t bias) // this must be signed
{ bool bUpdated = false;
// Use the compiled date/time as a basis for setting the clock.
// We assign it to a signed integer so that negative biases work correctly
int64_t compiledTime = DateTime(__DATE__,__TIME__).unixtime();
// This assumes that the program is run VERY soon after the initial compile.
time_t localt = DateTime(compiledTime + bias).unixtime(); // offset by bias
// If the stored static time stamp does not equal the compiled time stamp,
// then we need to update the RTC clock and the stored time stamp
if(*((time_t *)&rtc[0]) != localt)
{
// Update the RTC time as local time, not GMT/UTC
rtc.adjust(localt);
// Store the new compiled time statically in the object ram image
*((time_t *)&rtc[0]) = localt;
// Push the object ram image to the RTC ram image
bUpdated = rtc.commit();
}
return bUpdated;
}
int main()
{ time_t tick = 0;
if(rtcUpdate(gRtc, -(5*60*60) )) // CDT
gSerial.printf("Updated RTC to compiled time\r\n");
gSerial.printf("compiled %s %s\r\n",__DATE__,__TIME__);
DateTime timeFlashed(*((time_t *)&gRtc[0]));
printDT("last flashed on",timeFlashed);
DateTime dt = gRtc.now();
printDT("reset",dt);
gSerial.printf("rtc clock is %s\r\n", (gRtc.isRunning() ? "running" : "halted");
while(1)
{
if(time(NULL) >= tick)
{
DateTime dt = gRrtc.now();
gSerial.printf("%u/%u/%02u %2u:%02u:%02u \r"
,dt.month(),dt.day(),dt.year()
,dt.hour(),dt.minute(),dt.second()
);
tick = time(NULL)+1;
}
}
}