DS1337 RTC library RTC 55 bytes nvram

ds1337.h

Committer:
labishrestha
Date:
2015-10-29
Revision:
2:66dbf3ae0f89
Parent:
0:366fa629ac27

File content as of revision 2:66dbf3ae0f89:

#ifndef __DS1337_H_
#define __DS1337_H_

#include "time.h"
#include "mbed.h"

#define DS1337_ADDR         0x68<<1 /// I2C library needs address shifted left by 1-bit
#define DS1337_BUFFER_SIZE  16      /// Max address for DS1337
#define DS1337_I2C_FCY      300000  /// I2C frequency
#define ERR_BUFFER_LEN      40

typedef struct tm Time;

/**
 * class to use a DS1337 rtc
 */
class DS1337
{
public:

    /// String containing error code when command fails
    char err[ERR_BUFFER_LEN];
    
    /** Create DS1337 instance on the specified pins of I2C bus
     */
    DS1337(PinName sda, PinName scl);

    /** Read current real time from DS1337
     *
     * @returns
     *   current time on success,
     *   0 on error (I2C fail, clock not set)
     */
    bool now(Time * time);
    
    /** Write current real time to DS1337
     *
     * @param time Real time to set up
     * @returns
     *   true on success,
     *   false on error (I2C fail)
     */
    bool set_time(Time * time);
    
    /** Convert Time to simple string timestamp
     *
     * @param time to print
     * @param str String to print to
     */    
    void time2str(Time * time, char * str);

private:

    I2C _i2c; /// I2C port 
    char buffer[DS1337_BUFFER_SIZE]; /// I2C Port Buffer

    /** Convert BCD to decimal 
        @param bcd
    */
    static int bcdToDecimal(int bcd) {
        return ((bcd & 0xF0) >> 4) * 10 + (bcd & 0x0F);
    }

    /** Convert decimal to BCD
        @param decimal
    */
    static int decimalToBcd(int dec) {
        return (dec % 10) + ((dec / 10) << 4);
    }
};

#endif // __DS1337_H_