Dallas DS1307 real-time clock minimalistic driver
Dependents: testing_RTC_OneWire EMIRv2
DS1307.cpp
- Committer:
- alpov
- Date:
- 2014-04-28
- Revision:
- 2:6d8d35a5b3f2
- Parent:
- 1:60383faa35a9
- Child:
- 3:c5018c71887f
File content as of revision 2:6d8d35a5b3f2:
#include "mbed.h" #include "DS1307.h" DS1307::DS1307(PinName sda, PinName scl) : ds1307_i2c(sda, scl) { ds1307_i2c.frequency(DS1307_FREQ); } time_t DS1307::now() { struct tm now; char addr = 0x00; // memory address char buffer[7]; if (ds1307_i2c.write(DS1307_ADDR, &addr, 1) != 0) return 0; if (ds1307_i2c.read(DS1307_ADDR, buffer, 7) != 0) return 0; if (buffer[0] & 0x80) return 0; // clock stopped if (!(buffer[2] & 0x40)) return 0; // 12-hour format not supported now.tm_sec = bcdToDecimal(buffer[0] & 0x7F); now.tm_min = bcdToDecimal(buffer[1]); now.tm_hour = bcdToDecimal(buffer[2] & 0x3F); now.tm_mday = bcdToDecimal(buffer[4]); now.tm_mon = bcdToDecimal(buffer[5]) - 1; now.tm_year = bcdToDecimal(buffer[6]) + 2000 - 1900; return mktime(&now); } bool DS1307::set_time(time_t t) { struct tm *now; char buffer[9]; now = localtime(&t); buffer[0] = 0x00; // memory address buffer[1] = decimalToBcd(now->tm_sec) & 0x7f; // CH = 0 buffer[2] = decimalToBcd(now->tm_min); buffer[3] = 0x40 | (decimalToBcd(now->tm_hour) & 0x3F); // 24-hour format buffer[4] = now->tm_wday + 1; buffer[5] = decimalToBcd(now->tm_mday); buffer[6] = decimalToBcd(now->tm_mon+1); buffer[7] = decimalToBcd(now->tm_year + 1900 - 2000); buffer[8] = 0x00; // OUT = 0 if (ds1307_i2c.write(DS1307_ADDR, buffer, 9) != 0) return false; return true; }