1 /**
2   ******************************************************************************
3   * @file    stm32u0xx_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
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   ******************************************************************************
15   * @attention
16   *
17   * Copyright (c) 2023 STMicroelectronics.
18   * All rights reserved.
19   *
20   * This software is licensed under terms that can be found in the LICENSE file
21   * in the root directory of this software component.
22   * If no LICENSE file comes with this software, it is provided AS-IS.
23   *
24   ******************************************************************************
25  @verbatim
26   ==============================================================================
27                         ##### How to use this driver #####
28   ==============================================================================
29     [..]
30     This file must be copied to the application folder and modified as follows:
31     (#) Rename it to 'stm32u0xx_hal_timebase_rtc_wakeup.c'
32     (#) Add this file and the RTC HAL drivers to your project and uncomment
33        HAL_RTC_MODULE_ENABLED define in stm32u0xx_hal_conf.h
34 
35     [..]
36     (@) HAL RTC alarm and HAL RTC wakeup drivers cannot be used with low power modes:
37         The wake up capability of the RTC may be intrusive in case of prior low power mode
38         configuration requiring different wake up sources.
39         Application/Example behavior is no more guaranteed
40     (@) The stm32u0xx_hal_timebase_tim use is recommended for the Applications/Examples
41           requiring low power modes
42 
43   @endverbatim
44   ******************************************************************************
45   */
46 
47 /* Includes ------------------------------------------------------------------*/
48 #include "stm32u0xx_hal.h"
49 /** @addtogroup STM32U0xx_HAL_Driver
50   * @{
51   */
52 
53 /** @defgroup HAL_TimeBase_RTC_WakeUp_Template  HAL TimeBase RTC WakeUp Template
54   * @{
55   */
56 
57 /* Private typedef -----------------------------------------------------------*/
58 /* Private define ------------------------------------------------------------*/
59 
60 /* Uncomment the line below to select the appropriate RTC Clock source for your application:
61   + RTC_CLOCK_SOURCE_HSE: can be selected for applications requiring timing precision.
62   + RTC_CLOCK_SOURCE_LSE: can be selected for applications with low constraint on timing
63                           precision.
64   + RTC_CLOCK_SOURCE_LSI: can be selected for applications with low constraint on timing
65                           precision.
66   */
67 #define RTC_CLOCK_SOURCE_HSE
68 /* #define RTC_CLOCK_SOURCE_LSE */
69 /* #define RTC_CLOCK_SOURCE_LSI */
70 
71 #ifdef RTC_CLOCK_SOURCE_HSE
72 #define RTC_ASYNCH_PREDIV       49U
73 #define RTC_SYNCH_PREDIV        4U
74 #else /* RTC_CLOCK_SOURCE_LSE || RTC_CLOCK_SOURCE_LSI */
75 #define RTC_ASYNCH_PREDIV       0U
76 #define RTC_SYNCH_PREDIV        31U
77 #endif /* RTC_CLOCK_SOURCE_HSE */
78 
79 /* Private macro -------------------------------------------------------------*/
80 /* Private variables ---------------------------------------------------------*/
81 extern RTC_HandleTypeDef hRTC_Handle;
82 RTC_HandleTypeDef        hRTC_Handle;
83 
84 /* Private function prototypes -----------------------------------------------*/
85 void RTC_TAMP_IRQHandler(void);
86 
87 /* Private functions ---------------------------------------------------------*/
88 
89 /**
90   * @brief  This function configures the RTC_TAMP as a time base source.
91   *         The time source is configured  to have 1ms time base with a dedicated
92   *         Tick interrupt priority.
93   *         Wakeup Time base = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1)) / RTC_CLOCK
94                              = 1ms
95   *         Wakeup Time = WakeupTimebase * WakeUpCounter (0 + 1)
96                         = 1 ms
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 
109 #ifdef RTC_CLOCK_SOURCE_LSE
110   /* Configure LSE as RTC clock source */
111   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE;
112   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
113   RCC_OscInitStruct.LSEState = RCC_LSE_ON;
114   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
115 #elif defined (RTC_CLOCK_SOURCE_LSI)
116   /* Configure LSI as RTC clock source */
117   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI;
118   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
119   RCC_OscInitStruct.LSIState = RCC_LSI_ON;
120   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
121 #elif defined (RTC_CLOCK_SOURCE_HSE)
122   /* Configure HSE as RTC clock source */
123   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
124   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
125   RCC_OscInitStruct.HSEState = RCC_HSE_ON;
126   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV32;
127 #else
128 #error Please select the RTC Clock source
129 #endif /* RTC_CLOCK_SOURCE_LSE */
130 
131   if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK)
132   {
133     PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
134     if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) == HAL_OK)
135     {
136       /* Enable RTC Clock */
137       __HAL_RCC_RTC_ENABLE();
138       __HAL_RCC_RTCAPB_CLK_ENABLE();
139 
140       /* The time base should be 1ms
141          Time base = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1)) / RTC_CLOCK
142          HSE as RTC clock
143            Time base = ((49 + 1) * (4 + 1)) / 250khz
144                      = 1ms
145          LSE as RTC clock
146            Time base = ((31 + 1) * (0 + 1)) / 32.768Khz
147                      = ~1ms
148          LSI as RTC clock
149            Time base = ((31 + 1) * (0 + 1)) / 32Khz
150                      = 1ms
151       */
152       hRTC_Handle.Instance = RTC;
153       hRTC_Handle.Init.HourFormat = RTC_HOURFORMAT_24;
154       hRTC_Handle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV;
155       hRTC_Handle.Init.SynchPrediv = RTC_SYNCH_PREDIV;
156       hRTC_Handle.Init.OutPut = RTC_OUTPUT_DISABLE;
157       hRTC_Handle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
158       hRTC_Handle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
159       if (HAL_RTC_Init(&hRTC_Handle) != HAL_OK)
160       {
161         return HAL_ERROR;
162       }
163 
164       /* Disable the write protection for RTC registers */
165       __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
166 
167       /* Disable the Wake-up Timer */
168       __HAL_RTC_WAKEUPTIMER_DISABLE(&hRTC_Handle);
169 
170       /* In case of interrupt mode is used, the interrupt source must disabled */
171       __HAL_RTC_WAKEUPTIMER_DISABLE_IT(&hRTC_Handle, RTC_IT_WUT);
172 
173       /* Wait till RTC WUTWF flag is set  */
174       while (__HAL_RTC_WAKEUPTIMER_GET_FLAG(&hRTC_Handle, RTC_FLAG_WUTWF) == 0U)
175       {
176         if (counter++ == (SystemCoreClock / 56U))
177         {
178           return HAL_ERROR;
179         }
180       }
181 
182       /* Clear PWR wake up Flag */
183       __HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU);
184 
185       /* Clear RTC Wake Up timer Flag */
186       __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&hRTC_Handle, RTC_FLAG_WUTF);
187 
188       /* Configure the Wake-up Timer counter */
189       hRTC_Handle.Instance->WUTR = 0U;
190 
191       /* Clear the Wake-up Timer clock source bits in CR register */
192       hRTC_Handle.Instance->CR &= (uint32_t)~RTC_CR_WUCKSEL;
193 
194       /* Configure the clock source */
195       hRTC_Handle.Instance->CR |= (uint32_t)RTC_WAKEUPCLOCK_CK_SPRE_16BITS;
196 
197       /* RTC WakeUpTimer Interrupt Configuration: EXTI configuration */
198       __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_IT();
199 
200       /* Configure the Interrupt in the RTC_CR register */
201       __HAL_RTC_WAKEUPTIMER_ENABLE_IT(&hRTC_Handle, RTC_IT_WUT);
202 
203       /* Enable the Wake-up Timer */
204       __HAL_RTC_WAKEUPTIMER_ENABLE(&hRTC_Handle);
205 
206       /* Enable the write protection for RTC registers */
207       __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
208 
209       HAL_NVIC_SetPriority(RTC_TAMP_IRQn, TickPriority, 0U);
210       HAL_NVIC_EnableIRQ(RTC_TAMP_IRQn);
211       return HAL_OK;
212     }
213   }
214   return HAL_ERROR;
215 }
216 
217 /**
218   * @brief  Suspend Tick increment.
219   * @note   Disable the tick increment by disabling RTC_TAMP interrupt.
220   * @retval None
221   */
HAL_SuspendTick(void)222 void HAL_SuspendTick(void)
223 {
224   /* Disable the write protection for RTC registers */
225   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
226   /* Disable WAKE UP TIMER Interrupt */
227   __HAL_RTC_WAKEUPTIMER_DISABLE_IT(&hRTC_Handle, RTC_IT_WUT);
228   /* Enable the write protection for RTC registers */
229   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
230 }
231 
232 /**
233   * @brief  Resume Tick increment.
234   * @note   Enable the tick increment by Enabling RTC_TAMP interrupt.
235   * @retval None
236   */
HAL_ResumeTick(void)237 void HAL_ResumeTick(void)
238 {
239   /* Disable the write protection for RTC registers */
240   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
241   /* Enable  WAKE UP TIMER  interrupt */
242   __HAL_RTC_WAKEUPTIMER_ENABLE_IT(&hRTC_Handle, RTC_IT_WUT);
243   /* Enable the write protection for RTC registers */
244   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
245 }
246 
247 /**
248   * @brief  Wake Up Timer Event Callback in non blocking mode
249   * @note   This function is called  when RTC_TAMP interrupt took place, inside
250   * RTC_TAMP_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
251   * a global variable "uwTick" used as application time base.
252   * @param  hrtc : RTC handle
253   * @retval None
254   */
HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef * hrtc)255 void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc)
256 {
257   HAL_IncTick();
258 }
259 
260 /**
261   * @brief  This function handles RTC WAKE UP TIMER interrupt request.
262   * @retval None
263   */
RTC_TAMP_IRQHandler(void)264 void RTC_TAMP_IRQHandler(void)
265 {
266   HAL_RTCEx_WakeUpTimerIRQHandler(&hRTC_Handle);
267 }
268 
269 /**
270   * @}
271   */
272 
273 /**
274   * @}
275   */
276