1 /**
2   ******************************************************************************
3   * @file    stm32u5xx_hal_timebase_rtc_alarm_template.c
4   * @author  MCD Application Team
5   * @brief   HAL time base based on the hardware RTC_ALARM Template.
6   *
7   *          This file overrides the native HAL time base functions (defined as weak)
8   *          to use the RTC ALARM for time base generation:
9   *           + Initializes the RTC peripheral to increment the seconds registers each 1ms
10   *           + The alarm is configured to assert an interrupt when the RTC reaches 1ms
11   *           + HAL_IncTick is called at each Alarm event
12   *           + HSE (default), LSE or LSI can be selected as RTC clock source
13   ******************************************************************************
14   * @attention
15   *
16   * Copyright (c) 2021 STMicroelectronics.
17   * All rights reserved.
18   *
19   * This software is licensed under terms that can be found in the LICENSE file
20   * in the root directory of this software component.
21   * If no LICENSE file comes with this software, it is provided AS-IS.
22   *
23   ******************************************************************************
24  @verbatim
25   ==============================================================================
26                         ##### How to use this driver #####
27   ==============================================================================
28     [..]
29     This file must be copied to the application folder and modified as follows:
30     (#) Rename it to 'stm32u5xx_hal_timebase_rtc_alarm.c'
31     (#) Add this file and the RTC HAL drivers to your project and uncomment
32        HAL_RTC_MODULE_ENABLED define in stm32u5xx_hal_conf.h
33 
34     [..]
35     (@) HAL RTC alarm and HAL RTC wakeup drivers can not be used with low power modes:
36         The wake up capability of the RTC may be intrusive in case of prior low power mode
37         configuration requiring different wake up sources.
38         Application/Example behavior is no more guaranteed
39     (@) The stm32u5xx_hal_timebase_tim use is recommended for the Applications/Examples
40           requiring low power modes
41 
42   @endverbatim
43   ******************************************************************************
44   */
45 
46 /* Includes ------------------------------------------------------------------*/
47 #include "stm32u5xx_hal.h"
48 /** @addtogroup STM32U5xx_HAL_Driver
49   * @{
50   */
51 
52 /** @defgroup HAL_TimeBase_RTC_Alarm_Template  HAL TimeBase RTC Alarm Template
53   * @{
54   */
55 
56 /* Private typedef -----------------------------------------------------------*/
57 /* Private define ------------------------------------------------------------*/
58 
59 /* Uncomment the line below to select the appropriate RTC Clock source for your application:
60   + RTC_CLOCK_SOURCE_HSE: can be selected for applications requiring timing precision.
61   + RTC_CLOCK_SOURCE_LSE: can be selected for applications with low constraint on timing
62                           precision.
63   + RTC_CLOCK_SOURCE_LSI: can be selected for applications with low constraint on timing
64                           precision.
65   */
66 /* #define RTC_CLOCK_SOURCE_HSE */
67 /* #define RTC_CLOCK_SOURCE_LSE */
68 #define RTC_CLOCK_SOURCE_LSI
69 
70 /* The time base should be 1ms
71    Time base = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1)) / RTC_CLOCK
72 */
73 #if defined (RTC_CLOCK_SOURCE_HSE)
74 #define RTC_ASYNCH_PREDIV      99U
75 #define RTC_SYNCH_PREDIV        4U
76 #elif defined (RTC_CLOCK_SOURCE_LSE)
77 #define RTC_ASYNCH_PREDIV       0U
78 #define RTC_SYNCH_PREDIV       32U
79 #elif defined (RTC_CLOCK_SOURCE_LSI)
80 #define RTC_ASYNCH_PREDIV       0U
81 #define RTC_SYNCH_PREDIV       31U
82 #else
83 #error Please select the RTC Clock source
84 #endif /* RTC_CLOCK_SOURCE_LSE */
85 
86 /* Private macro -------------------------------------------------------------*/
87 /* Private variables ---------------------------------------------------------*/
88 static RTC_HandleTypeDef        hRTC_Handle;
89 
90 /* Private function prototypes -----------------------------------------------*/
91 void RTC_IRQHandler(void);
92 #if (USE_HAL_RTC_REGISTER_CALLBACKS == 1U)
93 void TimeBase_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc);
94 #endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
95 /* Private functions ---------------------------------------------------------*/
96 
97 /**
98   * @brief  This function configures the RTC_ALARMA as a time base source.
99   *         The time source is configured to have 1ms time base with a dedicated
100   *         Tick interrupt priority.
101   * @note   This function is called  automatically at the beginning of program after
102   *         reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig().
103   * @param  TickPriority Tick interrupt priority.
104   * @retval HAL status
105   */
HAL_InitTick(uint32_t TickPriority)106 HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
107 {
108   HAL_StatusTypeDef  Status;
109 
110   RCC_OscInitTypeDef        RCC_OscInitStruct;
111   RCC_PeriphCLKInitTypeDef  PeriphClkInitStruct;
112 
113   /* Disable bkup domain protection */
114   __HAL_RCC_PWR_CLK_ENABLE();
115   HAL_PWR_EnableBkUpAccess();
116 
117   /* Force and Release the Backup domain reset */
118   __HAL_RCC_BACKUPRESET_FORCE();
119   __HAL_RCC_BACKUPRESET_RELEASE();
120 
121   /* Enable RTC Clock */
122   __HAL_RCC_RTC_ENABLE();
123   __HAL_RCC_RTCAPB_CLK_ENABLE();
124 
125 #if defined (RTC_CLOCK_SOURCE_LSE)
126   /* Configure LSE as RTC clock source */
127   RCC_OscInitStruct.OscillatorType      = RCC_OSCILLATORTYPE_LSE;
128   RCC_OscInitStruct.PLL.PLLState        = RCC_PLL_NONE;
129   RCC_OscInitStruct.LSEState            = RCC_LSE_ON_RTC_ONLY;
130   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
131 #elif defined (RTC_CLOCK_SOURCE_LSI)
132   /* Configure LSI as RTC clock source */
133   RCC_OscInitStruct.OscillatorType      = RCC_OSCILLATORTYPE_LSI;
134   RCC_OscInitStruct.PLL.PLLState        = RCC_PLL_NONE;
135   RCC_OscInitStruct.LSIDiv              = RCC_LSI_DIV1;
136   RCC_OscInitStruct.LSIState            = RCC_LSI_ON;
137   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
138 #elif defined (RTC_CLOCK_SOURCE_HSE)
139   /* Configure HSE as RTC clock source */
140   RCC_OscInitStruct.OscillatorType      = RCC_OSCILLATORTYPE_HSE;
141   RCC_OscInitStruct.PLL.PLLState        = RCC_PLL_NONE;
142   RCC_OscInitStruct.HSEState            = RCC_HSE_ON;
143   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV32;
144 #else
145 #error Please select the RTC Clock source
146 #endif /* RTC_CLOCK_SOURCE_LSE */
147 
148   Status = HAL_RCC_OscConfig(&RCC_OscInitStruct);
149 
150   if (Status == HAL_OK)
151   {
152     PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
153     Status = HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);
154   }
155 
156   if (Status == HAL_OK)
157   {
158     hRTC_Handle.Instance = RTC;
159     hRTC_Handle.Init.HourFormat     = RTC_HOURFORMAT_24;
160     hRTC_Handle.Init.AsynchPrediv   = RTC_ASYNCH_PREDIV;
161     hRTC_Handle.Init.SynchPrediv    = RTC_SYNCH_PREDIV;
162     hRTC_Handle.Init.OutPut         = RTC_OUTPUT_DISABLE;
163     hRTC_Handle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
164     hRTC_Handle.Init.OutPutType     = RTC_OUTPUT_TYPE_OPENDRAIN;
165     hRTC_Handle.Init.BinMode        = RTC_BINARY_NONE;
166 
167     Status = HAL_RTC_Init(&hRTC_Handle);
168 
169 #if (USE_HAL_RTC_REGISTER_CALLBACKS == 1U)
170     HAL_RTC_RegisterCallback(&hRTC_Handle, HAL_RTC_ALARM_A_EVENT_CB_ID, TimeBase_RTC_AlarmAEventCallback);
171 #endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
172   }
173 
174   if (Status == HAL_OK)
175   {
176     /* RTC variables */
177     RTC_AlarmTypeDef RTC_AlarmStructure;
178 
179     /* RTC Alarm Generation */
180     RTC_AlarmStructure.Alarm                = RTC_ALARM_A;
181     RTC_AlarmStructure.AlarmDateWeekDay     = RTC_WEEKDAY_MONDAY;
182     RTC_AlarmStructure.AlarmDateWeekDaySel  = RTC_ALARMDATEWEEKDAYSEL_DATE;
183     /* Mask all and keep only subsecond, to have one match in each time base 1ms(uwTickFreq) */
184     RTC_AlarmStructure.AlarmMask            = RTC_ALARMMASK_ALL;
185     RTC_AlarmStructure.AlarmSubSecondMask   = RTC_ALARMSUBSECONDMASK_NONE;
186     RTC_AlarmStructure.AlarmTime.TimeFormat = RTC_HOURFORMAT_24;
187     RTC_AlarmStructure.AlarmTime.Hours      = 0;
188     RTC_AlarmStructure.AlarmTime.Minutes    = 0;
189     RTC_AlarmStructure.AlarmTime.Seconds    = 0;
190     RTC_AlarmStructure.AlarmTime.SubSeconds = 0;
191 
192     /* Set the specified RTC Alarm with Interrupt */
193     Status = HAL_RTC_SetAlarm_IT(&hRTC_Handle, &RTC_AlarmStructure, RTC_FORMAT_BCD);
194   }
195 
196   if (TickPriority < (1UL << __NVIC_PRIO_BITS))
197   {
198     /* Enable the RTC global Interrupt */
199     HAL_NVIC_SetPriority(RTC_IRQn, TickPriority, 0);
200     uwTickPrio = TickPriority;
201   }
202   else
203   {
204     Status = HAL_ERROR;
205   }
206 
207   HAL_NVIC_EnableIRQ(RTC_IRQn);
208 
209   return Status;
210 }
211 
212 /**
213   * @brief  Suspend Tick increment.
214   * @note   Disable the tick increment by disabling RTC ALARM interrupt.
215   * @retval None
216   */
HAL_SuspendTick(void)217 void HAL_SuspendTick(void)
218 {
219   /* Disable the write protection for RTC registers */
220   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
221   /* Disable RTC ALARM update Interrupt */
222   __HAL_RTC_ALARM_DISABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
223   /* Enable the write protection for RTC registers */
224   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
225 }
226 
227 /**
228   * @brief  Resume Tick increment.
229   * @note   Enable the tick increment by Enabling RTC ALARM interrupt.
230   * @retval None
231   */
HAL_ResumeTick(void)232 void HAL_ResumeTick(void)
233 {
234   /* Disable the write protection for RTC registers */
235   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
236   /* Enable RTC ALARM Update interrupt */
237   __HAL_RTC_ALARM_ENABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
238   /* Enable the write protection for RTC registers */
239   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
240 }
241 
242 /**
243   * @brief  ALARM A Event Callback in non blocking mode
244   * @note   This function is called  when RTC_ALARM interrupt took place, inside
245   * RTC_ALARM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
246   * a global variable "uwTick" used as application time base.
247   * @param  hrtc RTC handle
248   * @retval None
249   */
250 #if (USE_HAL_RTC_REGISTER_CALLBACKS == 1U)
TimeBase_RTC_AlarmAEventCallback(RTC_HandleTypeDef * hrtc)251 void TimeBase_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
252 #else
253 void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
254 #endif /* USE_HAL_RTC_REGISTER_CALLBACKS */
255 {
256   /* Prevent unused argument(s) compilation warning */
257   UNUSED(hrtc);
258 
259   HAL_IncTick();
260 }
261 
262 /**
263   * @brief  This function handles RTC ALARM interrupt request.
264   * @retval None
265   */
RTC_IRQHandler(void)266 void RTC_IRQHandler(void)
267 {
268   HAL_RTC_AlarmIRQHandler(&hRTC_Handle);
269 }
270 
271 /**
272   * @}
273   */
274 
275 /**
276   * @}
277   */
278