BCD and RTC utility

Files at this revision

API Documentation at this revision

Comitter:
ykuroda
Date:
Sat Oct 06 16:38:23 2012 +0000
Commit message:
BCD and RTC utility

Changed in this revision

bcdutil.cpp Show annotated file Show diff for this revision Revisions of this file
bcdutil.h Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r dc2c526097d2 bcdutil.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/bcdutil.cpp	Sat Oct 06 16:38:23 2012 +0000
@@ -0,0 +1,61 @@
+//
+///
+//
+//
+//
+//
+//
+//
+#include "mbed.h"
+#include "bcdutil.h"
+
+
+static struct tm __t;
+static char __rtc_data[20];
+
+unsigned int bin2bcd(unsigned int n)
+{
+    unsigned int bcd=0;
+    unsigned int base=0;
+
+    while (n>0) {
+        bcd |= (n%10)<<base;
+        base += 4;
+        n /= 10;
+    }
+    return bcd;
+}
+
+unsigned char bcd2bin(unsigned char bcd)
+{
+//    return 10*((bcd>>4)&0xF) + bcd&0xF;   // not good. don't know why.
+    unsigned char temp = bcd & 0x0F;
+    while (bcd>=0x10) {
+        temp += 10;
+        bcd -= 0x10;
+    }
+    return temp;
+}
+
+char*
+tm2rtc(struct tm* _t)          // tm -> rtc(BCD)
+{
+    __rtc_data[2] = bin2bcd(_t->tm_sec);
+    __rtc_data[3] = bin2bcd(_t->tm_min);
+    __rtc_data[4] = bin2bcd(_t->tm_hour);
+    __rtc_data[5] = bin2bcd(_t->tm_mday);
+    __rtc_data[7] = bin2bcd(_t->tm_mon);
+    __rtc_data[8] = bin2bcd(_t->tm_year-100);
+    return __rtc_data;
+}
+
+struct tm*
+rtc2tm(char* _bcd) {  // rtc(BCD) -> tm
+    __t.tm_sec = bcd2bin(_bcd[2]&0x7F);      // 0-59
+    __t.tm_min = bcd2bin(_bcd[3]&0x7F);      // 0-59
+    __t.tm_hour= bcd2bin(_bcd[4]&0x3F);      // 0-23
+    __t.tm_mday= bcd2bin(_bcd[5]&0x3F);      // 1-31
+    __t.tm_mon = bcd2bin(_bcd[7]&0x1F);      // 0-11
+    __t.tm_year= bcd2bin(_bcd[8])+100;  // year since 1900
+    return &__t;
+}
diff -r 000000000000 -r dc2c526097d2 bcdutil.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/bcdutil.h	Sat Oct 06 16:38:23 2012 +0000
@@ -0,0 +1,20 @@
+//
+///
+//
+//
+//
+//
+//
+//
+#ifndef _BCDUTIL_H
+#define _BCDUTIL_H
+
+
+
+unsigned int bin2bcd(unsigned int n);
+unsigned char bcd2bin(unsigned char bcd);
+char* tm2rtc(struct tm* _t);        // tm -> rtc(BCD)
+struct tm* rtc2tm(char* _bcd);      // rtc(BCD) -> tm
+
+
+#endif