Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.2 KiB

  1. /*
  2. ds3231 support module
  3. Copyright (C) 2018 by Pavel Chauzov <poulch at mail dot ru>
  4. */
  5. #pragma once
  6. #undef I2C_SUPPORT
  7. #define I2C_SUPPORT 1 // Explicitly request I2C support.
  8. #include <TimeLib.h>
  9. #define DS3231ADDR 0x68
  10. #define _bcdToDec(val) ((uint8_t) ((val / 16 * 10) + (val % 16)))
  11. #define _decToBcd(val) ((uint8_t) ((val / 10 * 16) + (val % 10)))
  12. time_t getTime_rtc() {
  13. uint8_t data[7];
  14. tmElements_t tm;
  15. i2c_write_uint8(DS3231ADDR,0);
  16. i2c_read_buffer(DS3231ADDR, data, 7);
  17. tm.Second = _bcdToDec(data[0]);
  18. tm.Minute = _bcdToDec(data[1]);
  19. tm.Hour = _bcdToDec(data[2]);
  20. tm.Wday = _bcdToDec(data[3]);
  21. tm.Day = _bcdToDec(data[4]);
  22. tm.Month = _bcdToDec(data[5]);
  23. tm.Year = y2kYearToTm(_bcdToDec(data[6]));
  24. return makeTime(tm);
  25. }
  26. uint8_t setTime_rtc(time_t nt) {
  27. uint8_t data[8];
  28. tmElements_t ct;
  29. breakTime(nt, ct);
  30. data[0] = 0;
  31. data[1] = _decToBcd(ct.Second);
  32. data[2] = _decToBcd(ct.Minute);
  33. data[3] = _decToBcd(ct.Hour);
  34. data[4] = _decToBcd(ct.Wday);
  35. data[5] = _decToBcd(ct.Day);
  36. data[6] = _decToBcd(ct.Month);
  37. data[7] = _decToBcd(tmYearToY2k(ct.Year));
  38. uint8_t s = i2c_write_buffer(DS3231ADDR, data, 8);
  39. return s;
  40. }