AceTimeClock  1.3.0
Clock classes for Arduino that can synchronize from an NTP server or an RTC chip
Stm32F1Rtc.cpp
1 /*
2  * MIT License
3  * Copyright (c) 2021 Brian T. Park
4  *
5  * Extracted from https://github.com/ZulNs/STM32F1_RTC/
6  * Copyright (c) 2019 ZulNs
7  */
8 
9 #include "Stm32F1Rtc.h"
10 
11 #if defined(STM32F1xx)
12 
13 namespace ace_time {
14 namespace hw {
15 
16 bool Stm32F1Rtc::begin() {
17  bool isInit = isInitialized();
18  enableClockInterface();
19  if (isInit) {
20  waitSync();
21  } else {
22  init();
23  }
24  return isInit;
25 }
26 
27 void Stm32F1Rtc::init() {
28  enableBackupWrites();
29  RCC_BDCR |= RCC_BDCR_BDRST; // Resets the entire Backup domain
30  RCC_BDCR &= ~RCC_BDCR_BDRST; // Deactivates reset of entire Backup domain
31  RCC_BDCR |= RCC_BDCR_LSEON; // Enables external low-speed oscillator (LSE)
32  while ((RCC_BDCR & RCC_BDCR_LSERDY) == 0); // Waits for LSE ready
33  RCC_BDCR |= RCC_BDCR_RTCSEL_LSE; // Selects LSE as RTC clock
34  RCC_BDCR |= RCC_BDCR_RTCEN; // Enables the RTC
35  waitSync();
36  waitFinished();
37  enterConfigMode();
38  RTC_PRLL = 0x7FFF;
39  exitConfigMode();
40  waitFinished();
41  RTC_INIT_REG |= RTC_INIT_FLAG; // Signals that RTC initilized
42  disableBackupWrites();
43 }
44 
45 // The 32-bit RTC counter is spread over 2 registers so it cannot be read
46 // atomically. We need to read the high word twice and check if it has rolled
47 // over. If it has, then read the low word a second time to get its new, rolled
48 // over value. See the RTC_ReadTimeCounter() in
49 // system/Drivers/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rtc.c.
50 uint32_t Stm32F1Rtc::getTime() {
51  uint16_t high1 = RTC_CNTH;
52  uint16_t low = RTC_CNTL;
53  uint16_t high2 = RTC_CNTH;
54 
55  if (high1 != high2) {
56  low = RTC_CNTL;
57  high1 = high2;
58  }
59 
60  return (high1 << 16) | low;
61 }
62 
63 void Stm32F1Rtc::setTime(uint32_t time) {
64  enableBackupWrites();
65  waitFinished();
66  enterConfigMode();
67 
68  RTC_CNTH = time >> 16;
69  RTC_CNTL = time & 0xFFFF;
70 
71  exitConfigMode();
72  waitFinished();
73  disableBackupWrites();
74 }
75 
76 } // hw
77 } // ace_time
78 
79 #endif // defined(STM32F1xx)