Dallas DS1307 real-time clock minimalistic driver

Dependents:   testing_RTC_OneWire EMIRv2

DS1307.h

Committer:
alpov
Date:
2014-04-28
Revision:
3:c5018c71887f
Parent:
1:60383faa35a9

File content as of revision 3:c5018c71887f:

#ifndef _DS1307_H
#define _DS1307_H

/* Dallas DS1307 real-time clock minimalistic driver
 *
 * Copyright (c) 2014 Ales Povalac, MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or 
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#define DS1307_ADDR     0xD0    // I2C address
#define DS1307_FREQ     100000  // bus speed

/** Dallas DS1307 real-time clock minimalistic driver
 */
class DS1307
{
public:
    /** Create DS1307 instance on the specified pins of I2C bus
     */
    DS1307(PinName sda, PinName scl);

    /** Read current real time from DS1307
     *
     * @returns
     *   current time on success,
     *   0 on error (I2C fail, clock not set)
     */
    time_t now();
    
    /** Write current real time to DS1307
     *
     * @param time Real time to set up
     * @returns
     *   true on success,
     *   false on error (I2C fail)
     */
    bool set_time(time_t time);

private:
    I2C ds1307_i2c;

    static int bcdToDecimal(int bcd) {
        return ((bcd & 0xF0) >> 4) * 10 + (bcd & 0x0F);
    }

    static int decimalToBcd(int dec) {
        return (dec % 10) + ((dec / 10) << 4);
    }
};

#endif // __DS1307_H