rtc_api.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /* mbed Microcontroller Library
  2. *******************************************************************************
  3. * Copyright (c) 2018, STMicroelectronics
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice,
  10. * this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. * 3. Neither the name of STMicroelectronics nor the names of its contributors
  15. * may be used to endorse or promote products derived from this software
  16. * without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  19. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  20. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  22. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  23. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  24. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  26. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *******************************************************************************
  29. */
  30. #if DEVICE_RTC
  31. #include "rtc_api_hal.h"
  32. #include "mbed_mktime.h"
  33. #include "mbed_error.h"
  34. #include "mbed_critical.h"
  35. #if DEVICE_LPTICKER && !MBED_CONF_TARGET_LPTICKER_LPTIM
  36. volatile uint32_t LP_continuous_time = 0;
  37. volatile uint32_t LP_last_RTC_time = 0;
  38. #endif
  39. static int RTC_inited = 0;
  40. static RTC_HandleTypeDef RtcHandle;
  41. void rtc_init(void)
  42. {
  43. RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  44. RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
  45. if (RTC_inited) {
  46. return;
  47. }
  48. RTC_inited = 1;
  49. // Enable access to Backup domain
  50. __HAL_RCC_PWR_CLK_ENABLE();
  51. HAL_PWR_EnableBkUpAccess();
  52. #if MBED_CONF_TARGET_LSE_AVAILABLE
  53. RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE;
  54. RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // Mandatory, otherwise the PLL is reconfigured!
  55. RCC_OscInitStruct.LSEState = RCC_LSE_ON;
  56. if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
  57. error("Cannot initialize RTC with LSE\n");
  58. }
  59. __HAL_RCC_RTC_CLKPRESCALER(RCC_RTCCLKSOURCE_LSE);
  60. __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSE);
  61. PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
  62. PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
  63. if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) {
  64. error("PeriphClkInitStruct RTC failed with LSE\n");
  65. }
  66. #else /* MBED_CONF_TARGET_LSE_AVAILABLE */
  67. // Reset Backup domain
  68. __HAL_RCC_BACKUPRESET_FORCE();
  69. __HAL_RCC_BACKUPRESET_RELEASE();
  70. // Enable LSI clock
  71. RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI;
  72. RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // Mandatory, otherwise the PLL is reconfigured!
  73. RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  74. if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
  75. error("Cannot initialize RTC with LSI\n");
  76. }
  77. __HAL_RCC_RTC_CLKPRESCALER(RCC_RTCCLKSOURCE_LSI);
  78. __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSI);
  79. PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
  80. PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
  81. if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) {
  82. error("PeriphClkInitStruct RTC failed with LSI\n");
  83. }
  84. #endif /* MBED_CONF_TARGET_LSE_AVAILABLE */
  85. // Enable RTC
  86. __HAL_RCC_RTC_ENABLE();
  87. RtcHandle.Instance = RTC;
  88. RtcHandle.State = HAL_RTC_STATE_RESET;
  89. #if TARGET_STM32F1
  90. RtcHandle.Init.AsynchPrediv = RTC_AUTO_1_SECOND;
  91. #else /* TARGET_STM32F1 */
  92. RtcHandle.Init.HourFormat = RTC_HOURFORMAT_24;
  93. RtcHandle.Init.AsynchPrediv = PREDIV_A_VALUE;
  94. RtcHandle.Init.SynchPrediv = PREDIV_S_VALUE;
  95. RtcHandle.Init.OutPut = RTC_OUTPUT_DISABLE;
  96. RtcHandle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
  97. RtcHandle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
  98. #endif /* TARGET_STM32F1 */
  99. if (HAL_RTC_Init(&RtcHandle) != HAL_OK) {
  100. error("RTC initialization failed");
  101. }
  102. #if !(TARGET_STM32F1) && !(TARGET_STM32F2)
  103. /* STM32F1 : there are no shadow registers */
  104. /* STM32F2 : shadow registers can not be bypassed */
  105. if (HAL_RTCEx_EnableBypassShadow(&RtcHandle) != HAL_OK) {
  106. error("EnableBypassShadow error");
  107. }
  108. #endif /* TARGET_STM32F1 || TARGET_STM32F2 */
  109. }
  110. void rtc_free(void)
  111. {
  112. /* RTC clock can not be reset */
  113. }
  114. /*
  115. Information about STM32F0, STM32F2, STM32F3, STM32F4, STM32F7, STM32L0, STM32L1, STM32L4:
  116. BCD format is used to store the date in the RTC. The year is store on 2 * 4 bits.
  117. Because the first year is reserved to see if the RTC is init, the supposed range is 01-99.
  118. 1st point is to cover the standard range from 1970 to 2038 (limited by the 32 bits of time_t).
  119. 2nd point is to keep the year 1970 and the leap years synchronized.
  120. So by moving it 68 years forward from 1970, it become 1969-2067 which include 1970-2038.
  121. 68 is also a multiple of 4 so it let the leap year synchronized.
  122. Information about STM32F1:
  123. 32bit register is used (no BCD format) for the seconds.
  124. For date, there is no specific register, only a software structure.
  125. It is then not a problem to not use shifts.
  126. */
  127. #if TARGET_STM32F1
  128. time_t rtc_read(void)
  129. {
  130. RTC_DateTypeDef dateStruct = {0};
  131. RTC_TimeTypeDef timeStruct = {0};
  132. struct tm timeinfo;
  133. RtcHandle.Instance = RTC;
  134. // Read actual date and time
  135. // Warning: the time must be read first!
  136. HAL_RTC_GetTime(&RtcHandle, &timeStruct, RTC_FORMAT_BIN);
  137. HAL_RTC_GetDate(&RtcHandle, &dateStruct, RTC_FORMAT_BIN);
  138. /* date information is null before first write procedure */
  139. /* set 01/01/1970 as default values */
  140. if (dateStruct.Year == 0) {
  141. dateStruct.Year = 2 ;
  142. dateStruct.Month = 1 ;
  143. dateStruct.Date = 1 ;
  144. }
  145. // Setup a tm structure based on the RTC
  146. /* tm_wday information is ignored by _rtc_maketime */
  147. /* tm_isdst information is ignored by _rtc_maketime */
  148. timeinfo.tm_mon = dateStruct.Month - 1;
  149. timeinfo.tm_mday = dateStruct.Date;
  150. timeinfo.tm_year = dateStruct.Year + 68;
  151. timeinfo.tm_hour = timeStruct.Hours;
  152. timeinfo.tm_min = timeStruct.Minutes;
  153. timeinfo.tm_sec = timeStruct.Seconds;
  154. // Convert to timestamp
  155. time_t t;
  156. if (_rtc_maketime(&timeinfo, &t, RTC_4_YEAR_LEAP_YEAR_SUPPORT) == false) {
  157. return 0;
  158. }
  159. return t;
  160. }
  161. #else /* TARGET_STM32F1 */
  162. time_t rtc_read(void)
  163. {
  164. struct tm timeinfo;
  165. /* Since the shadow registers are bypassed we have to read the time twice and compare them until both times are the same */
  166. uint32_t Read_time = RTC->TR & RTC_TR_RESERVED_MASK;
  167. uint32_t Read_date = RTC->DR & RTC_DR_RESERVED_MASK;
  168. while ((Read_time != (RTC->TR & RTC_TR_RESERVED_MASK)) || (Read_date != (RTC->DR & RTC_DR_RESERVED_MASK))) {
  169. Read_time = RTC->TR & RTC_TR_RESERVED_MASK;
  170. Read_date = RTC->DR & RTC_DR_RESERVED_MASK;
  171. }
  172. /* Setup a tm structure based on the RTC
  173. struct tm :
  174. tm_sec seconds after the minute 0-61
  175. tm_min minutes after the hour 0-59
  176. tm_hour hours since midnight 0-23
  177. tm_mday day of the month 1-31
  178. tm_mon months since January 0-11
  179. tm_year years since 1900
  180. tm_yday information is ignored by _rtc_maketime
  181. tm_wday information is ignored by _rtc_maketime
  182. tm_isdst information is ignored by _rtc_maketime
  183. */
  184. timeinfo.tm_mday = RTC_Bcd2ToByte((uint8_t)(Read_date & (RTC_DR_DT | RTC_DR_DU)));
  185. timeinfo.tm_mon = RTC_Bcd2ToByte((uint8_t)((Read_date & (RTC_DR_MT | RTC_DR_MU)) >> 8)) - 1;
  186. timeinfo.tm_year = RTC_Bcd2ToByte((uint8_t)((Read_date & (RTC_DR_YT | RTC_DR_YU)) >> 16)) + 68;
  187. timeinfo.tm_hour = RTC_Bcd2ToByte((uint8_t)((Read_time & (RTC_TR_HT | RTC_TR_HU)) >> 16));
  188. timeinfo.tm_min = RTC_Bcd2ToByte((uint8_t)((Read_time & (RTC_TR_MNT | RTC_TR_MNU)) >> 8));
  189. timeinfo.tm_sec = RTC_Bcd2ToByte((uint8_t)((Read_time & (RTC_TR_ST | RTC_TR_SU)) >> 0));
  190. // Convert to timestamp
  191. time_t t;
  192. if (_rtc_maketime(&timeinfo, &t, RTC_4_YEAR_LEAP_YEAR_SUPPORT) == false) {
  193. return 0;
  194. }
  195. return t;
  196. }
  197. #endif /* TARGET_STM32F1 */
  198. void rtc_write(time_t t)
  199. {
  200. RTC_DateTypeDef dateStruct = {0};
  201. RTC_TimeTypeDef timeStruct = {0};
  202. core_util_critical_section_enter();
  203. RtcHandle.Instance = RTC;
  204. // Convert the time into a tm
  205. struct tm timeinfo;
  206. if (_rtc_localtime(t, &timeinfo, RTC_4_YEAR_LEAP_YEAR_SUPPORT) == false) {
  207. return;
  208. }
  209. // Fill RTC structures
  210. if (timeinfo.tm_wday == 0) { /* Sunday specific case */
  211. dateStruct.WeekDay = RTC_WEEKDAY_SUNDAY;
  212. } else {
  213. dateStruct.WeekDay = timeinfo.tm_wday;
  214. }
  215. dateStruct.Month = timeinfo.tm_mon + 1;
  216. dateStruct.Date = timeinfo.tm_mday;
  217. dateStruct.Year = timeinfo.tm_year - 68;
  218. timeStruct.Hours = timeinfo.tm_hour;
  219. timeStruct.Minutes = timeinfo.tm_min;
  220. timeStruct.Seconds = timeinfo.tm_sec;
  221. #if !(TARGET_STM32F1)
  222. timeStruct.TimeFormat = RTC_HOURFORMAT_24;
  223. timeStruct.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
  224. timeStruct.StoreOperation = RTC_STOREOPERATION_RESET;
  225. #endif /* TARGET_STM32F1 */
  226. #if DEVICE_LPTICKER && !MBED_CONF_TARGET_LPTICKER_LPTIM
  227. /* Need to update LP_continuous_time value before new RTC time */
  228. rtc_read_lp();
  229. /* LP_last_RTC_time value is updated with the new RTC time */
  230. LP_last_RTC_time = timeStruct.Seconds + timeStruct.Minutes * 60 + timeStruct.Hours * 60 * 60;
  231. /* Save current SSR */
  232. uint32_t Read_SubSeconds = (uint32_t)(RTC->SSR);
  233. #endif /* DEVICE_LPTICKER && !MBED_CONF_TARGET_LPTICKER_LPTIM */
  234. // Change the RTC current date/time
  235. if (HAL_RTC_SetDate(&RtcHandle, &dateStruct, RTC_FORMAT_BIN) != HAL_OK) {
  236. error("HAL_RTC_SetDate error\n");
  237. }
  238. if (HAL_RTC_SetTime(&RtcHandle, &timeStruct, RTC_FORMAT_BIN) != HAL_OK) {
  239. error("HAL_RTC_SetTime error\n");
  240. }
  241. #if DEVICE_LPTICKER && !MBED_CONF_TARGET_LPTICKER_LPTIM
  242. while (Read_SubSeconds != (RTC->SSR)) {
  243. }
  244. #endif /* DEVICE_LPTICKER && !MBED_CONF_TARGET_LPTICKER_LPTIM */
  245. core_util_critical_section_exit();
  246. }
  247. int rtc_isenabled(void)
  248. {
  249. #if !(TARGET_STM32F1)
  250. return ((RTC->ISR & RTC_ISR_INITS) == RTC_ISR_INITS);
  251. #else /* TARGET_STM32F1 */
  252. return ((RTC->CRL & RTC_CRL_RSF) == RTC_CRL_RSF);
  253. #endif /* TARGET_STM32F1 */
  254. }
  255. #if DEVICE_LPTICKER && !MBED_CONF_TARGET_LPTICKER_LPTIM
  256. static void RTC_IRQHandler(void);
  257. static void (*irq_handler)(void);
  258. volatile uint8_t lp_Fired = 0;
  259. static void RTC_IRQHandler(void)
  260. {
  261. /* Update HAL state */
  262. RtcHandle.Instance = RTC;
  263. if (__HAL_RTC_WAKEUPTIMER_GET_IT(&RtcHandle, RTC_IT_WUT)) {
  264. /* Get the status of the Interrupt */
  265. if ((uint32_t)(RTC->CR & RTC_IT_WUT) != (uint32_t)RESET) {
  266. /* Clear the WAKEUPTIMER interrupt pending bit */
  267. __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&RtcHandle, RTC_FLAG_WUTF);
  268. lp_Fired = 0;
  269. if (irq_handler) {
  270. irq_handler();
  271. }
  272. }
  273. }
  274. if (lp_Fired) {
  275. lp_Fired = 0;
  276. if (irq_handler) {
  277. irq_handler();
  278. }
  279. }
  280. __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG();
  281. }
  282. uint32_t rtc_read_lp(void)
  283. {
  284. struct tm timeinfo;
  285. /* Since the shadow registers are bypassed we have to read the time twice and compare them until both times are the same */
  286. /* We don't have to read date as we bypass shadow registers */
  287. uint32_t Read_SecondFraction = (uint32_t)(RTC->PRER & RTC_PRER_PREDIV_S);
  288. uint32_t Read_time = (uint32_t)(RTC->TR & RTC_TR_RESERVED_MASK);
  289. uint32_t Read_SubSeconds = (uint32_t)(RTC->SSR);
  290. while ((Read_time != (RTC->TR & RTC_TR_RESERVED_MASK)) || (Read_SubSeconds != (RTC->SSR))) {
  291. Read_time = (uint32_t)(RTC->TR & RTC_TR_RESERVED_MASK);
  292. Read_SubSeconds = (uint32_t)(RTC->SSR);
  293. }
  294. timeinfo.tm_hour = RTC_Bcd2ToByte((uint8_t)((Read_time & (RTC_TR_HT | RTC_TR_HU)) >> 16));
  295. timeinfo.tm_min = RTC_Bcd2ToByte((uint8_t)((Read_time & (RTC_TR_MNT | RTC_TR_MNU)) >> 8));
  296. timeinfo.tm_sec = RTC_Bcd2ToByte((uint8_t)((Read_time & (RTC_TR_ST | RTC_TR_SU)) >> 0));
  297. uint32_t RTC_time_s = timeinfo.tm_sec + timeinfo.tm_min * 60 + timeinfo.tm_hour * 60 * 60; // Max 0x0001-517F => * 8191 + 8191 = 0x2A2E-AE80
  298. if (LP_last_RTC_time <= RTC_time_s) {
  299. LP_continuous_time += (RTC_time_s - LP_last_RTC_time);
  300. } else {
  301. /* Add 24h */
  302. LP_continuous_time += (24 * 60 * 60 + RTC_time_s - LP_last_RTC_time);
  303. }
  304. LP_last_RTC_time = RTC_time_s;
  305. return LP_continuous_time * PREDIV_S_VALUE + Read_SecondFraction - Read_SubSeconds;
  306. }
  307. void rtc_set_wake_up_timer(timestamp_t timestamp)
  308. {
  309. uint32_t WakeUpCounter;
  310. uint32_t current_lp_time;
  311. current_lp_time = rtc_read_lp();
  312. if (timestamp < current_lp_time) {
  313. WakeUpCounter = 0xFFFFFFFF - current_lp_time + timestamp;
  314. } else {
  315. WakeUpCounter = timestamp - current_lp_time;
  316. }
  317. if (WakeUpCounter > 0xFFFF) {
  318. WakeUpCounter = 0xFFFF;
  319. }
  320. RtcHandle.Instance = RTC;
  321. if (HAL_RTCEx_SetWakeUpTimer_IT(&RtcHandle, WakeUpCounter, RTC_WAKEUPCLOCK_RTCCLK_DIV4) != HAL_OK) {
  322. error("rtc_set_wake_up_timer init error\n");
  323. }
  324. NVIC_SetVector(RTC_WKUP_IRQn, (uint32_t)RTC_IRQHandler);
  325. irq_handler = (void (*)(void))lp_ticker_irq_handler;
  326. NVIC_EnableIRQ(RTC_WKUP_IRQn);
  327. }
  328. void rtc_fire_interrupt(void)
  329. {
  330. lp_Fired = 1;
  331. NVIC_SetVector(RTC_WKUP_IRQn, (uint32_t)RTC_IRQHandler);
  332. irq_handler = (void (*)(void))lp_ticker_irq_handler;
  333. NVIC_SetPendingIRQ(RTC_WKUP_IRQn);
  334. NVIC_EnableIRQ(RTC_WKUP_IRQn);
  335. }
  336. void rtc_deactivate_wake_up_timer(void)
  337. {
  338. RtcHandle.Instance = RTC;
  339. __HAL_RTC_WRITEPROTECTION_DISABLE(&RtcHandle);
  340. __HAL_RTC_WAKEUPTIMER_DISABLE(&RtcHandle);
  341. __HAL_RTC_WAKEUPTIMER_DISABLE_IT(&RtcHandle, RTC_IT_WUT);
  342. __HAL_RTC_WRITEPROTECTION_ENABLE(&RtcHandle);
  343. NVIC_DisableIRQ(RTC_WKUP_IRQn);
  344. }
  345. #endif /* DEVICE_LPTICKER && !MBED_CONF_TARGET_LPTICKER_LPTIM */
  346. #endif /* DEVICE_RTC */