DS1338 RTC library RTC + 55 bytes nvram

This library let you access a DS1338, which includes a RTC and some nvram.

Most of the mbed chip already have a good rtc, but they can't be powered by a separate backup battery.

With a DS1338, plus a small lithium 3V battery, you will keep trace of time.

You will also have 55 bytes (DS1338 says 56 bytes, but I use one of them for the library) of NVRAM backed up by the battery, to store fast changing data (which would tear down an eeprom), and keep it, even in the case of a watchdog reset.

Demo code

#include "mbed.h"
#include "fr_time.h"
#include "ds1338.h"

int main() {
    struct tm time;
    int count;

    pc=new RawSerial(USBTX, USBRX);
    pc->baud(115200);
    pc->printf("DS1338 Demo\r\n");
    DS1338 ds1338(P0_19,P0_20);
#ifdef INIT_TIME
    count=0;
    time.tm_sec=0;
    time.tm_min=0;
    time.tm_hour=8;
    time.tm_mday=4;
    time.tm_mon=2;
    time.tm_year=115;
    time.tm_wday=1;
    time.tm_yday=0;
    time.tm_isdst=0;
    ds1338.writeTime(&time);
#endif


    while (true) {
        wait(0.5);
        ds1338.readTime(&time);
        ds1338.read(0,4,(char *)(&count));
        count++;
        ds1338.write(0,4,(char *)(&count));
        pc->printf("loop %d at %s\r\n",count,asctime(&time));
    }
}
Revision:
0:0ffb7046206a
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ds1338.h	Wed Mar 04 08:49:37 2015 +0000
@@ -0,0 +1,51 @@
+#ifndef __EEPROM__H_
+#define __EEPROM__H_
+
+#include "mbed.h"
+
+#define DS1338_ADR     0xd0
+#define DS1338_BUFFER_SIZE 10
+
+
+/**
+ * class to use a DS1338 rtc
+ */
+class DS1338 {
+public:
+    /*
+     * Constructor, initialize the ds1338 on i2c interface.
+     * @param sda : sda i2c pin (PinName)
+     * @param scl : scl i2c pin (PinName)
+    */
+    DS1338(PinName sda, PinName scl);
+    /**
+     * read bytes
+     * @param adr the start address
+     * @param count number of byte to read
+     * @param data where to put the bytes
+     * @return the byte
+     */
+    void read(unsigned char adr,unsigned char count,char * data);
+    /**
+     * write bytes
+     * @param adr the start address
+     * @param count number of byte to write
+     * @param data to be written
+     * @return the byte
+     */
+    void write(unsigned char adr,unsigned char count,char * data);
+    /**
+     * read the current time
+     * @param x the time;
+     */
+    void readTime(tm * x);
+    /**
+     * read the current time
+     * @param x the time;
+     */
+    void writeTime(tm * x);
+private:
+    I2C _i2c;
+    char buffer[DS1338_BUFFER_SIZE];
+};
+#endif