Yoji KURODA / bcdutil
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers bcdutil.cpp Source File

bcdutil.cpp

00001 //
00002 ///
00003 //
00004 //
00005 //
00006 //
00007 //
00008 //
00009 #include "mbed.h"
00010 #include "bcdutil.h"
00011 
00012 
00013 static struct tm __t;
00014 static char __rtc_data[20];
00015 
00016 unsigned int bin2bcd(unsigned int n)
00017 {
00018     unsigned int bcd=0;
00019     unsigned int base=0;
00020 
00021     while (n>0) {
00022         bcd |= (n%10)<<base;
00023         base += 4;
00024         n /= 10;
00025     }
00026     return bcd;
00027 }
00028 
00029 unsigned char bcd2bin(unsigned char bcd)
00030 {
00031 //    return 10*((bcd>>4)&0xF) + bcd&0xF;   // not good. don't know why.
00032     unsigned char temp = bcd & 0x0F;
00033     while (bcd>=0x10) {
00034         temp += 10;
00035         bcd -= 0x10;
00036     }
00037     return temp;
00038 }
00039 
00040 char*
00041 tm2rtc(struct tm* _t)          // tm -> rtc(BCD)
00042 {
00043     __rtc_data[2] = bin2bcd(_t->tm_sec);
00044     __rtc_data[3] = bin2bcd(_t->tm_min);
00045     __rtc_data[4] = bin2bcd(_t->tm_hour);
00046     __rtc_data[5] = bin2bcd(_t->tm_mday);
00047     __rtc_data[7] = bin2bcd(_t->tm_mon);
00048     __rtc_data[8] = bin2bcd(_t->tm_year-100);
00049     return __rtc_data;
00050 }
00051 
00052 struct tm*
00053 rtc2tm(char* _bcd) {  // rtc(BCD) -> tm
00054     __t.tm_sec = bcd2bin(_bcd[2]&0x7F);      // 0-59
00055     __t.tm_min = bcd2bin(_bcd[3]&0x7F);      // 0-59
00056     __t.tm_hour= bcd2bin(_bcd[4]&0x3F);      // 0-23
00057     __t.tm_mday= bcd2bin(_bcd[5]&0x3F);      // 1-31
00058     __t.tm_mon = bcd2bin(_bcd[7]&0x1F);      // 0-11
00059     __t.tm_year= bcd2bin(_bcd[8])+100;  // year since 1900
00060     return &__t;
00061 }