Labi Shrestha / DS1337
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers ds1337.h Source File

ds1337.h

00001 #ifndef __DS1337_H_
00002 #define __DS1337_H_
00003 
00004 #include "time.h"
00005 #include "mbed.h"
00006 
00007 #define DS1337_ADDR         0x68<<1 /// I2C library needs address shifted left by 1-bit
00008 #define DS1337_BUFFER_SIZE  16      /// Max address for DS1337
00009 #define DS1337_I2C_FCY      300000  /// I2C frequency
00010 #define ERR_BUFFER_LEN      40
00011 
00012 typedef struct tm Time;
00013 
00014 /**
00015  * class to use a DS1337 rtc
00016  */
00017 class DS1337
00018 {
00019 public:
00020 
00021     /// String containing error code when command fails
00022     char err[ERR_BUFFER_LEN];
00023     
00024     /** Create DS1337 instance on the specified pins of I2C bus
00025      */
00026     DS1337(PinName sda, PinName scl);
00027 
00028     /** Read current real time from DS1337
00029      *
00030      * @returns
00031      *   current time on success,
00032      *   0 on error (I2C fail, clock not set)
00033      */
00034     bool now(Time * time);
00035     
00036     /** Write current real time to DS1337
00037      *
00038      * @param time Real time to set up
00039      * @returns
00040      *   true on success,
00041      *   false on error (I2C fail)
00042      */
00043     bool set_time(Time * time);
00044     
00045     /** Convert Time to simple string timestamp
00046      *
00047      * @param time to print
00048      * @param str String to print to
00049      */    
00050     void time2str(Time * time, char * str);
00051 
00052 private:
00053 
00054     I2C _i2c; /// I2C port 
00055     char buffer[DS1337_BUFFER_SIZE]; /// I2C Port Buffer
00056 
00057     /** Convert BCD to decimal 
00058         @param bcd
00059     */
00060     static int bcdToDecimal(int bcd) {
00061         return ((bcd & 0xF0) >> 4) * 10 + (bcd & 0x0F);
00062     }
00063 
00064     /** Convert decimal to BCD
00065         @param decimal
00066     */
00067     static int decimalToBcd(int dec) {
00068         return (dec % 10) + ((dec / 10) << 4);
00069     }
00070 };
00071 
00072 #endif // __DS1337_H_