1 /**
2   ******************************************************************************
3   * @file    stm32f2xx_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   *           + Intializes the RTC peripheral with required prescalers value for each
10   *             RTC clock source (HSE, LSE or LSI)
11   *           + The wakeup feature is configured to assert an interrupt each 1ms
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 'stm32f2xx_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 stm32f2xx_hal_conf.h
23 
24     [..]
25     (@) HAL RTC alarm and HAL RTC wakeup drivers can�t be used with low power modes:
26         The wake up capability of the RTC may be intrusive in case of prior low power mode
27         configuration requiring different wake up sources.
28         Application/Example behavior is no more guaranteed
29     (@) The stm32f2xx_hal_timebase_tim use is recommended for the Applications/Examples
30         requiring low power modes
31 
32   @endverbatim
33   ******************************************************************************
34   * @attention
35   *
36   * <h2><center>&copy; Copyright (c) 2016 STMicroelectronics.
37   * All rights reserved.</center></h2>
38   *
39   * This software component is licensed by ST under BSD 3-Clause license,
40   * the "License"; You may not use this file except in compliance with the
41   * License. You may obtain a copy of the License at:
42   *                        opensource.org/licenses/BSD-3-Clause
43   *
44   ******************************************************************************
45   */
46 
47 /* Includes ------------------------------------------------------------------*/
48 #include "stm32f2xx_hal.h"
49 
50 /** @addtogroup STM32F2xx_HAL_Driver
51   * @{
52   */
53 
54 /** @defgroup HAL_TimeBase_RTC_WakeUp_Template  HAL TimeBase RTC WakeUp Template
55   * @{
56   */
57 
58 /* Private typedef -----------------------------------------------------------*/
59 /* Private define ------------------------------------------------------------*/
60 
61 /* Uncomment the line below to select the appropriate RTC Clock source for your application:
62   + RTC_CLOCK_SOURCE_HSE: can be selected for applications requiring timing precision.
63   + RTC_CLOCK_SOURCE_LSE: can be selected for applications with low constraint on timing
64                           precision.
65   + RTC_CLOCK_SOURCE_LSI: can be selected for applications with low constraint on timing
66                           precision.
67   */
68 #define RTC_CLOCK_SOURCE_HSE
69 /* #define RTC_CLOCK_SOURCE_LSE */
70 /* #define RTC_CLOCK_SOURCE_LSI */
71 
72 #ifdef RTC_CLOCK_SOURCE_HSE
73   #define RTC_ASYNCH_PREDIV       99U
74   #define RTC_SYNCH_PREDIV        9U
75   #define RCC_RTCCLKSOURCE_1MHZ   ((uint32_t)((uint32_t)RCC_BDCR_RTCSEL | (uint32_t)((HSE_VALUE/1000000U) << 16U)))
76 #elif defined (RTC_CLOCK_SOURCE_LSE)
77   #define RTC_ASYNCH_PREDIV       2U
78   #define RTC_SYNCH_PREDIV        0U
79 #else /* RTC_CLOCK_SOURCE_LSI */
80   #define RTC_ASYNCH_PREDIV       1U
81   #define RTC_SYNCH_PREDIV        0U
82 #endif /* RTC_CLOCK_SOURCE_HSE */
83 
84 /* Private macro -------------------------------------------------------------*/
85 /* Private variables ---------------------------------------------------------*/
86 RTC_HandleTypeDef        hRTC_Handle;
87 
88 /* Private function prototypes -----------------------------------------------*/
89 void RTC_WKUP_IRQHandler(void);
90 
91 /* Private functions ---------------------------------------------------------*/
92 
93 /**
94   * @brief  This function configures the RTC_WKUP as a time base source.
95   *         The time source is configured  to have 1ms time base with a dedicated
96   *         Tick interrupt priority.
97   * @note   This function is called  automatically at the beginning of program after
98   *         reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig().
99   * @param  TickPriority Tick interrupt priority.
100   * @retval HAL status
101   */
HAL_InitTick(uint32_t TickPriority)102 HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
103 {
104   __IO uint32_t counter = 0U;
105 
106   RCC_OscInitTypeDef        RCC_OscInitStruct;
107   RCC_PeriphCLKInitTypeDef  PeriphClkInitStruct;
108   HAL_StatusTypeDef     status;
109 
110 #ifdef RTC_CLOCK_SOURCE_LSE
111   /* Configue LSE as RTC clock soucre */
112   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE;
113   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
114   RCC_OscInitStruct.LSEState = RCC_LSE_ON;
115   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
116 #elif defined (RTC_CLOCK_SOURCE_LSI)
117   /* Configue LSI as RTC clock soucre */
118   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI;
119   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
120   RCC_OscInitStruct.LSIState = RCC_LSI_ON;
121   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
122 #elif defined (RTC_CLOCK_SOURCE_HSE)
123   /* Configue HSE as RTC clock soucre */
124   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
125   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
126   RCC_OscInitStruct.HSEState = RCC_HSE_ON;
127   /* Ensure that RTC is clocked by 1MHz */
128   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_1MHZ;
129 #else
130 #error Please select the RTC Clock source
131 #endif /* RTC_CLOCK_SOURCE_LSE */
132 
133   status = HAL_RCC_OscConfig(&RCC_OscInitStruct);
134   if (status == HAL_OK)
135   {
136     PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
137     status = HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);
138   }
139   if (status == HAL_OK)
140   {
141     /* Enable RTC Clock */
142     __HAL_RCC_RTC_ENABLE();
143 
144     /* The time base should be 1ms
145        Time base = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1) * (WakeUpCounter + 1)) / RTC_CLOCK
146        HSE as RTC clock
147          Time base = ((99 + 1) * (9 + 1) * (0 + 1)) / 1Mhz
148                    = 1ms
149        LSE as RTC clock
150          Time base = ((2 + 1) * (0 + 1) * (10 + 1)) / 32.768Khz
151                    = ~1ms
152        LSI as RTC clock
153          Time base = ((1 + 1) * (0 + 1) * (15 + 1)) / 32Khz
154                    = 1ms
155     */
156     hRTC_Handle.Instance = RTC;
157     hRTC_Handle.Init.HourFormat = RTC_HOURFORMAT_24;
158     hRTC_Handle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV;
159     hRTC_Handle.Init.SynchPrediv = RTC_SYNCH_PREDIV;
160     hRTC_Handle.Init.OutPut = RTC_OUTPUT_DISABLE;
161     hRTC_Handle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
162     hRTC_Handle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
163     status = HAL_RTC_Init(&hRTC_Handle);
164   }
165   if (status == HAL_OK)
166   {
167     /* Disable the write protection for RTC registers */
168     __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
169 
170     /* Disable the Wake-up Timer */
171     __HAL_RTC_WAKEUPTIMER_DISABLE(&hRTC_Handle);
172 
173     /* In case of interrupt mode is used, the interrupt source must disabled */
174     __HAL_RTC_WAKEUPTIMER_DISABLE_IT(&hRTC_Handle, RTC_IT_WUT);
175 
176     /* Wait till RTC WUTWF flag is set  */
177     while (__HAL_RTC_WAKEUPTIMER_GET_FLAG(&hRTC_Handle, RTC_FLAG_WUTWF) == RESET)
178     {
179       if (counter++ == SystemCoreClock / 48U)
180       {
181         status = HAL_ERROR;
182       }
183     }
184   }
185   if (status == HAL_OK)
186   {
187 
188     /* Clear PWR wake up Flag */
189     __HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU);
190 
191     /* Clear RTC Wake Up timer Flag */
192     __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&hRTC_Handle, RTC_FLAG_WUTF);
193 
194     /* Configure the Wake-up Timer counter */
195 #ifdef RTC_CLOCK_SOURCE_HSE
196     hRTC_Handle.Instance->WUTR = 0U;
197 #elif defined (RTC_CLOCK_SOURCE_LSE)
198     hRTC_Handle.Instance->WUTR = 10U;
199 #else
200     hRTC_Handle.Instance->WUTR = 15U;
201 #endif
202 
203     /* Clear the Wake-up Timer clock source bits in CR register */
204     hRTC_Handle.Instance->CR &= (uint32_t)~RTC_CR_WUCKSEL;
205 
206     /* Configure the clock source */
207     hRTC_Handle.Instance->CR |= (uint32_t)RTC_WAKEUPCLOCK_CK_SPRE_16BITS;
208 
209     /* RTC WakeUpTimer Interrupt Configuration: EXTI configuration */
210     __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_IT();
211 
212     __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE();
213 
214     /* Configure the Interrupt in the RTC_CR register */
215     __HAL_RTC_WAKEUPTIMER_ENABLE_IT(&hRTC_Handle, RTC_IT_WUT);
216 
217     /* Enable the Wake-up Timer */
218     __HAL_RTC_WAKEUPTIMER_ENABLE(&hRTC_Handle);
219 
220     /* Enable the write protection for RTC registers */
221     __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
222 
223     /* Enable the RTC global Interrupt */
224     HAL_NVIC_EnableIRQ(RTC_WKUP_IRQn);
225 
226     /* Configure the SysTick IRQ priority */
227     if (TickPriority < (1UL << __NVIC_PRIO_BITS))
228     {
229       HAL_NVIC_SetPriority(RTC_WKUP_IRQn, TickPriority, 0U);
230       uwTickPrio = TickPriority;
231     }
232     else
233     {
234       status = HAL_ERROR;
235     }
236   }
237 
238   return status;
239 }
240 
241 /**
242   * @brief  Suspend Tick increment.
243   * @note   Disable the tick increment by disabling RTC_WKUP interrupt.
244   * @param  None
245   * @retval None
246   */
HAL_SuspendTick(void)247 void HAL_SuspendTick(void)
248 {
249   /* Disable the write protection for RTC registers */
250   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
251   /* Disable WAKE UP TIMER Interrupt */
252   __HAL_RTC_WAKEUPTIMER_DISABLE_IT(&hRTC_Handle, RTC_IT_WUT);
253   /* Enable the write protection for RTC registers */
254   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
255 }
256 
257 /**
258   * @brief  Resume Tick increment.
259   * @note   Enable the tick increment by Enabling RTC_WKUP interrupt.
260   * @param  None
261   * @retval None
262   */
HAL_ResumeTick(void)263 void HAL_ResumeTick(void)
264 {
265   /* Disable the write protection for RTC registers */
266   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
267   /* Enable  WAKE UP TIMER  interrupt */
268   __HAL_RTC_WAKEUPTIMER_ENABLE_IT(&hRTC_Handle, RTC_IT_WUT);
269   /* Enable the write protection for RTC registers */
270   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
271 }
272 
273 /**
274   * @brief  Wake Up Timer Event Callback in non blocking mode
275   * @note   This function is called  when RTC_WKUP interrupt took place, inside
276   * RTC_WKUP_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
277   * a global variable "uwTick" used as application time base.
278   * @param  hrtc RTC handle
279   * @retval None
280   */
HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef * hrtc)281 void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc)
282 {
283   HAL_IncTick();
284 }
285 
286 /**
287   * @brief  This function handles  WAKE UP TIMER  interrupt request.
288   * @param  None
289   * @retval None
290   */
RTC_WKUP_IRQHandler(void)291 void RTC_WKUP_IRQHandler(void)
292 {
293   HAL_RTCEx_WakeUpTimerIRQHandler(&hRTC_Handle);
294 }
295 
296 /**
297   * @}
298   */
299 
300 /**
301   * @}
302   */
303 
304 /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
305