Files
ESP8266lib/ext/time/DS3231.h
kazu 5cb02880b3 many updates..
new sensors.. display.. led.. drawing.. stuff..
2019-01-17 23:12:01 +01:00

125 lines
2.7 KiB
C++

#ifndef TIME_DS3231
#define TIME_DS3231
#include "../../io/SoftI2C.h"
class DS3231 {
static constexpr uint8_t ADDR7 = 0x68;
static constexpr uint8_t REG_SECONDS = 0x00;
static constexpr uint8_t REG_MINUTES = 0x01;
static constexpr uint8_t REG_HOURS = 0x02;
public:
bool isPresent() {
return i2c::query(ADDR7);
}
struct Time {
uint8_t h;
uint8_t m;
uint8_t s;
};
struct Date {
uint8_t d;
uint8_t m;
uint8_t y;
};
struct Res {
Time time;
Date date;
};
Res get() {
uint8_t buf[8];
readRegister(0x00, buf, 8);
Res res;
res.time.h = (((buf[2] & 0b00110000)>>4)*10) + (buf[2] & 0b1111);
res.time.m = (((buf[1] & 0b01110000)>>4)*10) + (buf[1] & 0b1111);
res.time.s = (((buf[0] & 0b01110000)>>4)*10) + (buf[0] & 0b1111);
res.date.d = (((buf[4] & 0b00110000)>>4)*10) + (buf[4] & 0b1111);
res.date.m = (((buf[5] & 0b00010000)>>4)*10) + (buf[5] & 0b1111);
res.date.y = (((buf[6] & 0b11110000)>>4)*10) + (buf[6] & 0b1111);
os_printf("%d %d %d \n", res.time.h, res.time.m, res.time.s);
os_printf("%d %d %d \n", res.date.d, res.date.m, res.date.y);
return res;
}
void setTime(uint8_t h, uint8_t m, uint8_t s) {
uint8_t buf[3];
buf[0] = ((s/10)<<4) + (s % 10);
buf[1] = ((m/10)<<4) + (m % 10);
buf[2] = ((h/10)<<4) + (h % 10);
writeRegister(0x00, buf, 3);
}
void setDate(uint8_t d, uint8_t m, uint8_t y) {
uint8_t buf[3];
buf[0] = ((d/10)<<4) + (d % 10);
buf[1] = ((m/10)<<4) + (m % 10);
buf[2] = ((y/10)<<4) + (y % 10);
writeRegister(0x04, buf, 3);
}
private:
bool readRegister(const uint8_t addr, uint8_t* dst, const uint8_t len) {
bool ok;
// address the slave in write mode and select the first register to read
ok = i2c::startWrite(ADDR7);
if (!ok) {os_printf("failed start write\n"); return false;}
ok = i2c::writeByteAndCheck(addr);
if (!ok) {os_printf("failed to select register %d\n", addr); return false;}
//i2c::stop();
// address the slave in read mode and read [len] registers
ok = i2c::startRead(ADDR7);
if (!ok) {os_printf("failed start read\n"); return 0;}
i2c::readBytes(dst, len);
// done
i2c::stop();
return true;
}
bool writeRegister(const uint8_t addr, const uint8_t* src, const uint8_t len) {
bool ok;
// address the slave in write mode and select the first register to read
ok = i2c::startWrite(ADDR7);
if (!ok) {os_printf("failed start write\n"); return false;}
ok = i2c::writeByteAndCheck(addr);
if (!ok) {os_printf("failed to select register %d\n", addr); return false;}
ok = i2c::writeBytesAndCheck(src, len);
if (!ok) {os_printf("failed to write register contents \n"); return false;}
// done
i2c::stop();
return true;
}
};
#endif