ds3231.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "mbed.h"
  2. #include "main.h"
  3. #include "ds3231.h"
  4. InterruptIn IO_Rtc(PB_5);
  5. #define BCDToDecimal(x) (((x >> 4) * 10) + (x & 0xF))
  6. #define DecimalToBCD(x) (((x / 10) << 4) | (x % 10))
  7. void DS3231_Init(void (*Callback)()) {
  8. DS3231_REGS regs = {0};
  9. regs.Control_1.nEOSC = 0; // Enable internal oscillator on VBAT
  10. regs.Control_1.BBSQW = 0; // Disable outputs on VBAT
  11. regs.Control_1.RS1 = 0; // Set square wave output to 1Hz
  12. regs.Control_1.RS2 = 0; // Set square wave output tp 1Hz
  13. regs.Control_1.INTCN = 0; // Enable square wave output
  14. regs.Control_1.A1IE = 0; // Disable alarm 1
  15. regs.Control_1.A2IE = 0; // Disable alarm 2
  16. regs.Control_2.EN32KHZ = 0; // Disable 32kHz output
  17. I2C_Write(DS3231_ADDR, FIELD_OFFSET(DS3231_REGS, Control_1),
  18. regs.AS_BYTE + FIELD_OFFSET(DS3231_REGS, Control_1),
  19. FIELD_SIZE_THROUGH(DS3231_REGS, Control_1, Control_2));
  20. IO_Rtc.rise(Callback);
  21. }
  22. void DS3231_SetTime(int Second, int Minute, int Hour, bool PM) {
  23. DS3231_REGS regs = {0};
  24. regs.Second.Value = DecimalToBCD(Second);
  25. regs.Minute.Value = DecimalToBCD(Minute);
  26. regs.Hour.Value = DecimalToBCD(Hour);
  27. regs.Hour.nAM = PM;
  28. regs.Hour.n24 = 1;
  29. I2C_Write(DS3231_ADDR, FIELD_OFFSET(DS3231_REGS, Second),
  30. regs.AS_BYTE + FIELD_OFFSET(DS3231_REGS, Second),
  31. FIELD_SIZE_THROUGH(DS3231_REGS, Second, Hour));
  32. }
  33. void DS3231_SetDate(int Day, int Date, int Month, int Year, int Century) {
  34. DS3231_REGS regs = {0};
  35. regs.Day.Value = DecimalToBCD(Day);
  36. regs.Date.Value = DecimalToBCD(Date);
  37. regs.Month.Value = DecimalToBCD(Month);
  38. regs.Month.Century = DecimalToBCD(Century);
  39. regs.Year.Value = DecimalToBCD(Year);
  40. I2C_Write(DS3231_ADDR, FIELD_OFFSET(DS3231_REGS, Day),
  41. regs.AS_BYTE + FIELD_OFFSET(DS3231_REGS, Day),
  42. FIELD_SIZE_THROUGH(DS3231_REGS, Day, Year));
  43. }
  44. void DS3231_GetTime(int *Second, int *Minute, int *Hour) {
  45. DS3231_REGS regs = {0};
  46. I2C_Read(DS3231_ADDR, FIELD_OFFSET(DS3231_REGS, Second),
  47. regs.AS_BYTE + FIELD_OFFSET(DS3231_REGS, Second),
  48. FIELD_SIZE_THROUGH(DS3231_REGS, Second, Hour));
  49. *Second = BCDToDecimal(regs.Second.Value);
  50. *Minute = BCDToDecimal(regs.Minute.Value);
  51. *Hour = BCDToDecimal(regs.Hour.Value);
  52. }