1 /**
2   ******************************************************************************
3   * @file    stm32wlxx_hal_timebase_rtc_wakeup_template.c
4   * @author  MCD Application Team
5   * @brief   HAL time base based on the hardware RTC_WAKEUP Template.
6   *
7   *          This file overrides the native HAL time base functions (defined as weak)
8   *          to use the RTC WAKEUP for the time base generation:
9   *           + Initializes the RTC peripheral and configures the wakeup timer to be
10   *             incremented each 1ms when uwTickFreq is set to default value, else
11   *              10 ms or 100 ms, depending of above global variable value.
12   *           + HAL_IncTick is called inside the HAL_RTCEx_WakeUpTimerEventCallback
13   *           + HSE (default), LSE or LSI can be selected as RTC clock source
14   @verbatim
15   ==============================================================================
16                         ##### How to use this driver #####
17   ==============================================================================
18     [..]
19     This file must be copied to the application folder and modified as follows:
20     (#) Rename it to 'stm32wlxx_hal_timebase_rtc_wakeup.c'
21     (#) Add this file and the RTC HAL drivers to your project and uncomment
22        HAL_RTC_MODULE_ENABLED define in stm32wlxx_hal_conf.h
23 
24   @endverbatim
25   ******************************************************************************
26   * @attention
27   *
28   * Copyright (c) 2020 STMicroelectronics.
29   * All rights reserved.
30   *
31   * This software is licensed under terms that can be found in the LICENSE file
32   * in the root directory of this software component.
33   * If no LICENSE file comes with this software, it is provided AS-IS.
34   *
35   ******************************************************************************
36   */
37 
38 /* Includes ------------------------------------------------------------------*/
39 #include "stm32wlxx_hal.h"
40 /** @addtogroup STM32WLxx_HAL_Driver
41   * @{
42   */
43 
44 /** @defgroup HAL_TimeBase_RTC_WakeUp_Template  HAL TimeBase RTC WakeUp Template
45   * @{
46   */
47 
48 /* Private typedef -----------------------------------------------------------*/
49 /* Private define ------------------------------------------------------------*/
50 
51 /* Uncomment the line below to select the appropriate RTC Clock source for your application:
52   + RTC_CLOCK_SOURCE_HSE: can be selected for applications requiring timing precision.
53   + RTC_CLOCK_SOURCE_LSE: can be selected for applications with low constraint on timing
54                           precision.
55   + RTC_CLOCK_SOURCE_LSI: can be selected for applications with low constraint on timing
56                           precision.
57   */
58 /* #define RTC_CLOCK_SOURCE_HSE */
59 /* #define RTC_CLOCK_SOURCE_LSE */
60 #define RTC_CLOCK_SOURCE_LSI
61 
62 #if !defined(RTC_CLOCK_SOURCE_LSI) && !defined(RTC_CLOCK_SOURCE_LSE) && !defined(RTC_CLOCK_SOURCE_HSE)
63 #error Please select the RTC Clock source AT PROJECT LEVEL
64 #endif
65 
66 #if defined (RTC_CLOCK_SOURCE_LSE)
67 /* LSE Freq = 32.768 kHz RC */
68 #define RTC_ASYNCH_PREDIV                   0x7Fu
69 #define RTC_SYNCH_PREDIV                    0x00FFu
70 #elif defined (RTC_CLOCK_SOURCE_LSI)
71 /* LSI Freq = 32 kHz RC  */
72 #define RTC_ASYNCH_PREDIV                   0x7Fu
73 #define RTC_SYNCH_PREDIV                    0x00FEu
74 #elif defined (RTC_CLOCK_SOURCE_HSE)
75 /* HSE Freq as RTCCLK = 32 MHz / 32 = 1 MHz */
76 #define RTC_ASYNCH_PREDIV                   0x7Fu
77 #define RTC_SYNCH_PREDIV                    0x1E83u
78 #endif
79 
80 
81 /* Private macro -------------------------------------------------------------*/
82 /* Private variables ---------------------------------------------------------*/
83 RTC_HandleTypeDef        hRTC_Handle = {.Init = {0}};
84 
85 /* Private function prototypes -----------------------------------------------*/
86 #if defined(CORE_CM0PLUS)
87 void RTC_LSECSS_IRQHandler(void);
88 #else
89 void RTC_WKUP_IRQHandler(void);
90 #endif
91 
92 /* Private functions ---------------------------------------------------------*/
93 
94 /**
95   * @brief  This function configures the RTC_WKUP as a time base source.
96   *         The time source is configured  to have 1ms time base with a dedicated
97   *         Tick interrupt priority.
98   *         Wakeup Time base = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1)) / RTC_CLOCK
99                              = 1ms
100   *         Wakeup Time = WakeupTimebase * WakeUpCounter (0 + 1)
101                         = 1 ms
102   * @note   This function is called  automatically at the beginning of program after
103   *         reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig().
104   * @param  TickPriority: Tick interrupt priority.
105   * @retval HAL status
106   */
HAL_InitTick(uint32_t TickPriority)107 HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
108 {
109   HAL_StatusTypeDef status = HAL_OK;
110   uint32_t wucounter;
111   RCC_OscInitTypeDef        RCC_OscInitStruct = {0};
112   RCC_PeriphCLKInitTypeDef  PeriphClkInitStruct = {0};
113 
114   /* Check uwTickFreq for MisraC 2012 (even if uwTickFreq is a enum type that don't take the value zero)*/
115   if ((uint32_t)uwTickFreq != 0U)
116   {
117     /* Disable backup domeain protection */
118     HAL_PWR_EnableBkUpAccess();
119 
120     /* Enable RTC APB clock gating */
121     __HAL_RCC_RTCAPB_CLK_ENABLE();
122 
123     /* Disable the Wake-up Timer */
124     __HAL_RTC_WAKEUPTIMER_DISABLE(&hRTC_Handle);
125     /* In case of interrupt mode is used, the interrupt source must disabled */
126     __HAL_RTC_WAKEUPTIMER_DISABLE_IT(&hRTC_Handle,RTC_IT_WUT);
127     __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&hRTC_Handle,RTC_FLAG_WUTF);
128 
129     /* Get RTC clock configuration */
130     HAL_RCCEx_GetPeriphCLKConfig(&PeriphClkInitStruct);
131 
132     /*In case of RTC clock already enable, make sure it's the good one */
133 #ifdef RTC_CLOCK_SOURCE_LSE
134     if ((PeriphClkInitStruct.RTCClockSelection == RCC_RTCCLKSOURCE_LSE) && (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) != 0x00u))
135 #elif defined (RTC_CLOCK_SOURCE_LSI)
136     if ((PeriphClkInitStruct.RTCClockSelection == RCC_RTCCLKSOURCE_LSI) && (__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) != 0x00u))
137 #elif defined (RTC_CLOCK_SOURCE_HSE)
138     if ((PeriphClkInitStruct.RTCClockSelection == RCC_RTCCLKSOURCE_HSE_DIV32) && (__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != 0x00u))
139 #else
140 #error Please select the RTC Clock source
141 #endif
142     {
143       /* Do nothing */
144     }
145     else
146     {
147 #ifdef RTC_CLOCK_SOURCE_LSE
148       /* Configure LSE as RTC clock source */
149       RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE;
150       RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
151       RCC_OscInitStruct.LSEState = RCC_LSE_ON;
152       PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
153 #elif defined (RTC_CLOCK_SOURCE_LSI)
154       /* Configure LSI as RTC clock source */
155       RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI;
156       RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
157       RCC_OscInitStruct.LSIState = RCC_LSI_ON;
158       PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
159 #elif defined (RTC_CLOCK_SOURCE_HSE)
160       /* Configure HSE as RTC clock source */
161       RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
162       RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
163       RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS_PWR;
164       /* Ensure that RTC is clocked by 1MHz */
165       PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV32;
166 #endif
167 
168       /* COnfigure oscillator */
169       status = HAL_RCC_OscConfig(&RCC_OscInitStruct);
170       if(status == HAL_OK)
171       {
172         /* Configure RTC clock source */
173         PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
174         status = HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);
175 
176         /* Enable RTC Clock */
177         if(status == HAL_OK)
178         {
179           __HAL_RCC_RTC_ENABLE();
180         }
181       }
182     }
183 
184     /* If RTC Clock configuration is ok */
185     if(status == HAL_OK)
186     {
187       /* No care of RTC init parameter here. Only needed if RTC is being used
188         for other features in same time: calendar, alarm, timestamp, etc... */
189       hRTC_Handle.Instance = RTC;
190       hRTC_Handle.Init.HourFormat = RTC_HOURFORMAT_24;
191       hRTC_Handle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV;
192       hRTC_Handle.Init.SynchPrediv = RTC_SYNCH_PREDIV;
193       hRTC_Handle.Init.OutPut = RTC_OUTPUT_DISABLE;
194       hRTC_Handle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
195       hRTC_Handle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
196       status = HAL_RTC_Init(&hRTC_Handle);
197 
198       if(status == HAL_OK)
199       {
200         /* The time base should be of (uint32_t)uwTickFreq) ms. Tick counter
201           is incremented eachtime wakeup time reaches zero. Wakeup timer is
202           clocked on RTCCLK divided by 2. So downcounting counter has to be
203           set to (RTCCLK / 2) / (1000 / (uint32_t)uwTickFreq)) minus 1 */
204 #ifdef RTC_CLOCK_SOURCE_LSE
205         wucounter = LSE_VALUE;
206 #elif defined (RTC_CLOCK_SOURCE_LSI)
207         wucounter = LSI_VALUE;
208 #elif defined (RTC_CLOCK_SOURCE_HSE)
209         /* HSE input clock to RTC is divided by 32 */
210         wucounter = (HSE_VALUE >> 5);
211 #endif
212         wucounter = ((wucounter >> 1) / (1000U / (uint32_t)uwTickFreq)) -1u;
213         status = HAL_RTCEx_SetWakeUpTimer_IT(&hRTC_Handle, wucounter, RTC_WAKEUPCLOCK_RTCCLK_DIV2, 0);
214 
215         if(status == HAL_OK)
216         {
217           /* Enable the RTC global Interrupt */
218 #if defined(CORE_CM0PLUS)
219           HAL_NVIC_EnableIRQ(RTC_LSECSS_IRQn);
220 #else
221           HAL_NVIC_EnableIRQ(RTC_WKUP_IRQn);
222 #endif
223           /* Configure the SysTick IRQ priority */
224           if (TickPriority < (1UL << __NVIC_PRIO_BITS))
225           {
226 #if defined(CORE_CM0PLUS)
227             HAL_NVIC_SetPriority(RTC_LSECSS_IRQn, TickPriority, 0U);
228 #else
229             HAL_NVIC_SetPriority(RTC_WKUP_IRQn, TickPriority, 0U);
230 #endif
231             uwTickPrio = TickPriority;
232           }
233           else
234           {
235             status = HAL_ERROR;
236           }
237         }
238       }
239     }
240   }
241   else
242   {
243     status = HAL_ERROR;
244   }
245   return status;
246 }
247 
248 /**
249   * @brief  Suspend Tick increment.
250   * @note   Disable the tick increment by disabling RTC_WKUP interrupt.
251   * @retval None
252   */
HAL_SuspendTick(void)253 void HAL_SuspendTick(void)
254 {
255   /* Disable the write protection for RTC registers */
256   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
257   /* Disable WAKE UP TIMER Interrupt */
258   __HAL_RTC_WAKEUPTIMER_DISABLE_IT(&hRTC_Handle, RTC_IT_WUT);
259   /* Enable the write protection for RTC registers */
260   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
261 }
262 
263 /**
264   * @brief  Resume Tick increment.
265   * @note   Enable the tick increment by Enabling RTC_WKUP interrupt.
266   * @retval None
267   */
HAL_ResumeTick(void)268 void HAL_ResumeTick(void)
269 {
270   /* Disable the write protection for RTC registers */
271   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
272   /* Enable  WAKE UP TIMER  interrupt */
273   __HAL_RTC_WAKEUPTIMER_ENABLE_IT(&hRTC_Handle, RTC_IT_WUT);
274   /* Enable the write protection for RTC registers */
275   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
276 }
277 
278 /**
279   * @brief  Wake Up Timer Event Callback in non blocking mode
280   * @note   This function is called  when RTC_WKUP interrupt takes place, inside
281   *         RTC_WKUP_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
282   *         a global variable "uwTick" used as application time base.
283   * @param  hrtc : RTC handle
284   * @retval None
285   */
HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef * hrtc)286 void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc)
287 {
288   HAL_IncTick();
289 }
290 
291 /**
292   * @brief  This function handles  WAKE UP TIMER  interrupt request.
293   * @retval None
294   */
295 
296 #if defined(CORE_CM0PLUS)
RTC_LSECSS_IRQHandler(void)297 void RTC_LSECSS_IRQHandler(void)
298 #else
299 void RTC_WKUP_IRQHandler(void)
300 #endif
301 {
302   HAL_RTCEx_WakeUpTimerIRQHandler(&hRTC_Handle);
303 }
304 
305 /**
306   * @}
307   */
308 
309 /**
310   * @}
311   */
312