DS1337 RTC library RTC 55 bytes nvram

Revision:
0:366fa629ac27
Child:
1:8a0e272ed8e6
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ds1337.cpp	Sat Oct 24 20:15:44 2015 +0000
@@ -0,0 +1,71 @@
+#include "ds1337.h"
+
+#define TIME_LENGTH 8 //Length of buffer needed for time/date
+
+DS1337::DS1337(PinName sda, PinName scl) : _i2c(sda, scl)
+{
+    _i2c.frequency(DS1337_I2C_FCY);
+}
+
+void DS1337::time2str(Time * t, char * str)
+{
+    sprintf(str, "%02d/%02d/%04d-%02d:%02d:%02d",t->tm_mon, t->tm_mday,(t->tm_year+1900), t->tm_hour,t->tm_min,t->tm_sec);
+}
+
+bool DS1337::now(Time * now)
+{
+    buffer[0] = 0x00; // memory address
+    
+    if (_i2c.write(DS1337_ADDR, &buffer[0], 1) != 0) 
+    {
+        sprintf(err, "RTC command write Failed");
+        return false;
+    }
+    
+    if (_i2c.read(DS1337_ADDR, buffer, DS1337_BUFFER_SIZE) != 0) 
+    {
+        sprintf(err, "RTC buffer read Failed");
+        return false;
+    }
+   
+    if (buffer[0] & 0x80) 
+    {
+        sprintf(err, "Clock Stopped");
+        return false;
+    }
+    
+    if (buffer[2] & 0x40) 
+    {
+        sprintf(err, "12hour not supported");
+        return false;
+    }
+    
+    now->tm_sec = bcdToDecimal(buffer[0] & 0x7F);
+    now->tm_min = bcdToDecimal(buffer[1] & 0x7F);
+    now->tm_hour = bcdToDecimal(buffer[2] & 0x3F);
+    now->tm_mday = bcdToDecimal(buffer[4] & 0x3F);
+    now->tm_mon = bcdToDecimal(buffer[5] & 0x1F);
+    now->tm_year = bcdToDecimal(buffer[6] & 0xFF);
+    
+    return true;
+}
+
+bool DS1337::set_time(Time * now)
+{
+    buffer[0] = 0x00; // memory address
+    buffer[1] = decimalToBcd(now->tm_sec) & 0x7F;
+    buffer[2] = decimalToBcd(now->tm_min) & 0x7F;
+    buffer[3] = decimalToBcd(now->tm_hour) & 0x3F; // 24-hour format
+    buffer[4] = now->tm_wday & 0x07;
+    buffer[5] = decimalToBcd(now->tm_mday) & 0x3F;
+    buffer[6] = decimalToBcd(now->tm_mon) & 0x1F;
+    buffer[7] = decimalToBcd(now->tm_year) & 0xFF;
+    
+    if (_i2c.write(DS1337_ADDR, buffer, TIME_LENGTH) != 0) 
+    {
+        sprintf(err, "RTC command write Failed");
+        return false;
+    }
+
+    return true;
+}