1 /**
2   ******************************************************************************
3   * @file    stm32h7xx_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 override 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 and the time is reset to 00:00:00
12   *           + HSE (default), LSE or LSI can be selected as RTC clock source
13   *
14   ******************************************************************************
15   * @attention
16   *
17   * Copyright (c) 2017 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   */
26  @verbatim
27   ==============================================================================
28                         ##### How to use this driver #####
29   ==============================================================================
30     [..]
31     This file must be copied to the application folder and modified as follows:
32     (#) Rename it to 'stm32h7xx_hal_timebase_rtc_alarm.c'
33     (#) Add this file and the RTC HAL drivers to your project and uncomment
34        HAL_RTC_MODULE_ENABLED define in stm32h7xx_hal_conf.h
35 
36     [..]
37     (@) HAL RTC alarm and HAL RTC wakeup drivers can not be used with low power modes:
38         The wake up capability of the RTC may be intrusive in case of prior low power mode
39         configuration requiring different wake up sources.
40         Application/Example behavior is no more guaranteed
41     (@) The stm32h7xx_hal_timebase_tim use is recommended for the Applications/Examples
42           requiring low power modes
43 
44   @endverbatim
45   ******************************************************************************
46   */
47 
48 /* Includes ------------------------------------------------------------------*/
49 #include "stm32h7xx_hal.h"
50 /** @addtogroup STM32H7xx_HAL_Driver
51   * @{
52   */
53 
54 /** @defgroup HAL_TimeBase_RTC_Alarm_Template  HAL TimeBase RTC Alarm 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) << 12U)))
76 #else /* RTC_CLOCK_SOURCE_LSE || RTC_CLOCK_SOURCE_LSI */
77   #define RTC_ASYNCH_PREDIV       0U
78   #define RTC_SYNCH_PREDIV        31U
79 #endif /* RTC_CLOCK_SOURCE_HSE */
80 
81 /* Private macro -------------------------------------------------------------*/
82 /* Private variables ---------------------------------------------------------*/
83 static RTC_HandleTypeDef        hRTC_Handle;
84 /* Private function prototypes -----------------------------------------------*/
85 void RTC_Alarm_IRQHandler(void);
86 /* Private functions ---------------------------------------------------------*/
87 
88 /**
89   * @brief  This function configures the RTC_ALARMA as a time base source.
90   *         The time source is configured to have 1ms time base with a dedicated
91   *         Tick interrupt priority.
92   * @note   This function is called  automatically at the beginning of program after
93   *         reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig().
94   * @param  TickPriority Tick interrupt priority.
95   * @retval HAL status
96   */
HAL_InitTick(uint32_t TickPriority)97 HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
98 {
99   __IO uint32_t counter = 0U;
100 
101   RCC_OscInitTypeDef        RCC_OscInitStruct;
102   RCC_PeriphCLKInitTypeDef  PeriphClkInitStruct;
103   HAL_StatusTypeDef     status;
104 
105 #ifdef RTC_CLOCK_SOURCE_LSE
106   /* Configure LSE as RTC clock source */
107   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE;
108   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
109   RCC_OscInitStruct.LSEState = RCC_LSE_ON;
110   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
111 #elif defined (RTC_CLOCK_SOURCE_LSI)
112   /* Configure LSI as RTC clock source */
113   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI;
114   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
115   RCC_OscInitStruct.LSIState = RCC_LSI_ON;
116   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
117 #elif defined (RTC_CLOCK_SOURCE_HSE)
118   /* Configure HSE as RTC clock source */
119   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
120   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
121   RCC_OscInitStruct.HSEState = RCC_HSE_ON;
122   /* Ensure that RTC is clocked by 1MHz */
123   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_1MHZ;
124 #else
125 #error Please select the RTC Clock source
126 #endif /* RTC_CLOCK_SOURCE_LSE */
127 
128   status = HAL_RCC_OscConfig(&RCC_OscInitStruct);
129   if (status == HAL_OK)
130   {
131     PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
132     status = HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);
133   }
134   if (status == HAL_OK)
135   {
136       /* Enable RTC Clock */
137       __HAL_RCC_RTC_ENABLE();
138       /* The time base should be 1ms
139          Time base = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1)) / RTC_CLOCK
140          HSE as RTC clock
141            Time base = ((99 + 1) * (9 + 1)) / 1MHz
142                      = 1ms
143          LSE as RTC clock
144            Time base = ((31 + 1) * (0 + 1)) / 32.768KHz
145                      = ~1ms
146          LSI as RTC clock
147            Time base = ((31 + 1) * (0 + 1)) / 32KHz
148                      = 1ms
149       */
150       hRTC_Handle.Instance = RTC;
151       hRTC_Handle.Init.HourFormat = RTC_HOURFORMAT_24;
152       hRTC_Handle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV;
153       hRTC_Handle.Init.SynchPrediv = RTC_SYNCH_PREDIV;
154       hRTC_Handle.Init.OutPut = RTC_OUTPUT_DISABLE;
155       hRTC_Handle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
156       hRTC_Handle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
157       status = HAL_RTC_Init(&hRTC_Handle);
158   }
159   if (status == HAL_OK)
160   {
161      /* Disable the write protection for RTC registers */
162      __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
163 
164      /* Disable the Alarm A interrupt */
165      __HAL_RTC_ALARMA_DISABLE(&hRTC_Handle);
166 
167      /* Clear flag alarm A */
168      __HAL_RTC_ALARM_CLEAR_FLAG(&hRTC_Handle, RTC_FLAG_ALRAF);
169 
170      counter = 0U;
171      /* Wait till RTC ALRAWF flag is set and if Time out is reached exit */
172 #if defined(RTC_ICSR_ALRAWF)
173      while ( READ_BIT(hRTC_Handle.Instance->ICSR, RTC_FLAG_ALRAWF) == (uint32_t)RESET)
174 #else
175      while (__HAL_RTC_ALARM_GET_FLAG(&hRTC_Handle, RTC_FLAG_ALRAWF) == (uint32_t)RESET)
176 #endif /* RTC_ICSR_ALRAWF */
177      {
178        if (counter++ == (SystemCoreClock / 48U)) /* Timeout = ~ 1s */
179        {
180           status = HAL_ERROR;
181        }
182      }
183   }
184   if (status == HAL_OK)
185   {
186     hRTC_Handle.Instance->ALRMAR = (uint32_t)0x01U;
187 
188     /* Configure the Alarm state: Enable Alarm */
189     __HAL_RTC_ALARMA_ENABLE(&hRTC_Handle);
190     /* Configure the Alarm interrupt */
191     __HAL_RTC_ALARM_ENABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
192 
193     /* RTC Alarm Interrupt Configuration: EXTI configuration */
194     __HAL_RTC_ALARM_EXTI_ENABLE_IT();
195     __HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE();
196 
197     /* Check if the Initialization mode is set */
198 #if defined(RTC_ISR_INITF)
199     if ((hRTC_Handle.Instance->ISR & RTC_ISR_INITF) == (uint32_t)RESET)
200 #else
201     if ((hRTC_Handle.Instance->ICSR & RTC_ICSR_INITF) == (uint32_t)RESET)
202 #endif /* RTC_ISR_INITF */
203     {
204        /* Set the Initialization mode */
205 #if defined(RTC_ISR_INITF)
206        hRTC_Handle.Instance->ISR = (uint32_t)RTC_INIT_MASK;
207 #else
208        hRTC_Handle.Instance->ICSR = (uint32_t)RTC_INIT_MASK;
209 #endif /* RTC_ISR_INITF */
210        counter = 0U;
211 #if defined(RTC_ISR_INITF)
212        while ((hRTC_Handle.Instance->ISR & RTC_ISR_INITF) == (uint32_t)RESET)
213 #else
214        while ((hRTC_Handle.Instance->ICSR & RTC_ICSR_INITF) == (uint32_t)RESET)
215 #endif /* RTC_ISR_INITF */
216        {
217          if (counter++ == (SystemCoreClock / 48U)) /* Timeout = ~ 1s */
218          {
219            status = HAL_ERROR;
220          }
221        }
222      }
223   }
224   if (status == HAL_OK)
225   {
226     hRTC_Handle.Instance->DR = 0U;
227     hRTC_Handle.Instance->TR = 0U;
228 
229 #if defined(RTC_ISR_INIT)
230     hRTC_Handle.Instance->ISR &= (uint32_t)~RTC_ISR_INIT;
231 #else
232     hRTC_Handle.Instance->ICSR &= (uint32_t)~RTC_ICSR_INIT;
233 #endif /* RTC_ISR_INIT */
234 
235     /* Enable the write protection for RTC registers */
236     __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
237 
238     /* Enable the RTC Alarm Interrupt */
239     HAL_NVIC_EnableIRQ(RTC_Alarm_IRQn);
240 
241     /* Configure the SysTick IRQ priority */
242     if (TickPriority < (1UL << __NVIC_PRIO_BITS))
243     {
244       HAL_NVIC_SetPriority(RTC_Alarm_IRQn, TickPriority, 0U);
245       uwTickPrio = TickPriority;
246     }
247     else
248     {
249       status = HAL_ERROR;
250     }
251 
252   }
253   return status;
254 }
255 
256 /**
257   * @brief  Suspend Tick increment.
258   * @note   Disable the tick increment by disabling RTC ALARM interrupt.
259   * @retval None
260   */
HAL_SuspendTick(void)261 void HAL_SuspendTick(void)
262 {
263   /* Disable the write protection for RTC registers */
264   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
265   /* Disable RTC ALARM update Interrupt */
266   __HAL_RTC_ALARM_DISABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
267   /* Enable the write protection for RTC registers */
268   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
269 }
270 
271 /**
272   * @brief  Resume Tick increment.
273   * @note   Enable the tick increment by Enabling RTC ALARM interrupt.
274   * @retval None
275   */
HAL_ResumeTick(void)276 void HAL_ResumeTick(void)
277 {
278   /* Disable the write protection for RTC registers */
279   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
280   /* Enable RTC ALARM Update interrupt */
281   __HAL_RTC_ALARM_ENABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
282   /* Enable the write protection for RTC registers */
283   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
284 }
285 
286 /**
287   * @brief  ALARM A Event Callback in non blocking mode
288   * @note   This function is called  when RTC_ALARM interrupt took place, inside
289   * RTC_ALARM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
290   * a global variable "uwTick" used as application time base.
291   * @param  hrtc RTC handle
292   * @retval None
293   */
HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef * hrtc)294 void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
295 {
296   __IO uint32_t counter = 0U;
297 
298   HAL_IncTick();
299 
300   __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
301 
302   /* Set the Initialization mode */
303 #if defined(RTC_ISR_INIT)
304   hrtc->Instance->ISR = (uint32_t)RTC_INIT_MASK;
305 
306   while((hrtc->Instance->ISR & RTC_ISR_INITF) == (uint32_t)RESET)
307 #else
308   hrtc->Instance->ICSR = (uint32_t)RTC_INIT_MASK;
309 
310   while((hrtc->Instance->ICSR & RTC_ICSR_INITF) == (uint32_t)RESET)
311 #endif /* RTC_ISR_INIT */
312   {
313     if(counter++ == (SystemCoreClock /48U)) /* Timeout = ~ 1s */
314     {
315       break;
316     }
317   }
318 
319   hrtc->Instance->DR = 0U;
320   hrtc->Instance->TR = 0U;
321 #if defined(RTC_ISR_INIT)
322   hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT;
323 #else
324   hrtc->Instance->ICSR &= (uint32_t)~RTC_ICSR_INIT;
325 #endif /* RTC_ISR_INIT  */
326   /* Enable the write protection for RTC registers */
327   __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
328 }
329 
330 /**
331   * @brief  This function handles RTC ALARM interrupt request.
332   * @retval None
333   */
RTC_Alarm_IRQHandler(void)334 void RTC_Alarm_IRQHandler(void)
335 {
336   HAL_RTC_AlarmIRQHandler(&hRTC_Handle);
337 }
338 
339 /**
340   * @}
341   */
342 
343 /**
344   * @}
345   */
346 
347