ds3231_stc8h3k.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright 2021 IOsetting <iosetting(at)outlook.com>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /***
  15. * Demo: ZS-042, DS3231 I2C RTC/TCXO/Crystal
  16. * Board: STC8H3K32
  17. *
  18. * P32 -> SCL
  19. * P33 -> SDA
  20. * GND -> GND
  21. * 3.3V -> VCC
  22. */
  23. #include "fw_hal.h"
  24. #include "ds3231.h"
  25. __XDATA uint8_t time[9];
  26. void I2C_Init(void)
  27. {
  28. // Master mode
  29. I2C_SetWorkMode(I2C_WorkMode_Master);
  30. /**
  31. * I2C clock = FOSC / 2 / (__prescaler__ * 2 + 4)
  32. */
  33. I2C_SetClockPrescaler(0x3F);
  34. // Switch alternative port
  35. I2C_SetPort(I2C_AlterPort_P32_P33);
  36. // Start I2C
  37. I2C_SetEnabled(HAL_State_ON);
  38. }
  39. void GPIO_Init(void)
  40. {
  41. // SDA
  42. GPIO_P3_SetMode(GPIO_Pin_3, GPIO_Mode_InOut_QBD);
  43. // SCL
  44. GPIO_P3_SetMode(GPIO_Pin_2, GPIO_Mode_Output_PP);
  45. }
  46. int main(void)
  47. {
  48. SYS_SetClock();
  49. // UART1 configuration: baud 115200 with Timer2, 1T mode, no interrupt
  50. UART1_Config8bitUart(UART1_BaudSource_Timer2, HAL_State_ON, 115200);
  51. GPIO_Init();
  52. I2C_Init();
  53. time[0] = DS3231_GetStatus();
  54. UART1_TxString("Status:");
  55. UART1_TxHex(time[0]);
  56. UART1_TxString("\r\n");
  57. // Set time
  58. time[7] = DS3231_FORMAT_24H;
  59. time[0] = 2022 - 1990; // year
  60. time[1] = 7; // month
  61. time[2] = 7; // week day
  62. time[3] = 10; // date
  63. time[4] = 14; // hour
  64. time[5] = 21; // minute
  65. time[6] = 10; // second
  66. DS3231_SetTime(time);
  67. while(1)
  68. {
  69. DS3231_GetTime(time);
  70. UART1_TxHex(time[0]);
  71. UART1_TxChar('-');
  72. UART1_TxHex(time[1]);
  73. UART1_TxChar('-');
  74. UART1_TxHex(time[3]);
  75. UART1_TxChar(' ');
  76. UART1_TxHex(time[4]);
  77. UART1_TxChar(':');
  78. UART1_TxHex(time[5]);
  79. UART1_TxChar(':');
  80. UART1_TxHex(time[6]);
  81. UART1_TxChar(' ');
  82. UART1_TxHex(time[7]);
  83. UART1_TxChar(' ');
  84. UART1_TxHex(time[8]);
  85. UART1_TxString("\r\n");
  86. SYS_Delay(1000);
  87. }
  88. }