1 /**
2   ******************************************************************************
3   * @file    stm32c0xx_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) 2022 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 'stm32c0xx_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 stm32c0xx_hal_conf.h
33 
34     [..]
35     (@) HAL RTC alarm  driver 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 stm32c0xx_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 "stm32c0xx_hal.h"
48 /** @addtogroup STM32C0xx_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 #ifdef RTC_CLOCK_SOURCE_HSE
71 #define RTC_ASYNCH_PREDIV       49U
72 #define RTC_SYNCH_PREDIV        4U
73 #else /* RTC_CLOCK_SOURCE_LSE || RTC_CLOCK_SOURCE_LSI */
74 #define RTC_ASYNCH_PREDIV       0U
75 #define RTC_SYNCH_PREDIV        31U
76 #endif /* RTC_CLOCK_SOURCE_HSE */
77 
78 /* Private macro -------------------------------------------------------------*/
79 /* Private variables ---------------------------------------------------------*/
80 extern RTC_HandleTypeDef hRTC_Handle;
81 RTC_HandleTypeDef hRTC_Handle;
82 
83 /* Private function prototypes -----------------------------------------------*/
84 void RTC_IRQHandler(void);
85 /* Private functions ---------------------------------------------------------*/
86 
87 /**
88   * @brief  This function configures the RTC_ALARMA as a time base source.
89   *         The time source is configured  to have 1ms time base with a dedicated
90   *         Tick interrupt priority.
91   * @note   This function is called  automatically at the beginning of program after
92   *         reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig().
93   * @param  TickPriority: Tick interrupt priority.
94   * @retval HAL status
95   */
HAL_InitTick(uint32_t TickPriority)96 HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
97 {
98   __IO uint32_t counter = 0U;
99 
100   RCC_OscInitTypeDef        RCC_OscInitStruct;
101   RCC_PeriphCLKInitTypeDef  PeriphClkInitStruct;
102 
103 #ifdef RTC_CLOCK_SOURCE_LSE
104   /* ConfigureLSE as RTC clock source */
105   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE;
106   RCC_OscInitStruct.LSEState = RCC_LSE_ON;
107   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
108 #elif defined (RTC_CLOCK_SOURCE_LSI)
109   /* ConfigureLSI as RTC clock source */
110   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI;
111   RCC_OscInitStruct.LSIState = RCC_LSI_ON;
112   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
113 #elif defined (RTC_CLOCK_SOURCE_HSE)
114   /* ConfigureHSE as RTC clock source */
115   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
116   RCC_OscInitStruct.HSEState = RCC_HSE_ON;
117   PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV32;
118 #else
119 #error Please select the RTC Clock source
120 #endif /* RTC_CLOCK_SOURCE_LSE */
121 
122   if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK)
123   {
124     PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
125     if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) == HAL_OK)
126     {
127       /* Enable RTC Clock */
128       __HAL_RCC_RTC_ENABLE();
129       __HAL_RCC_RTCAPB_CLK_ENABLE();
130 
131       /* The time base should be 1ms
132          Time base = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1)) / RTC_CLOCK
133          HSE as RTC clock
134            Time base = ((49 + 1) * (4 + 1)) / 250kHz
135                      = 1ms
136          LSE as RTC clock
137            Time base = ((31 + 1) * (0 + 1)) / 32.768KHz
138                      = ~1ms
139          LSI as RTC clock
140            Time base = ((31 + 1) * (0 + 1)) / 32KHz
141                      = 1ms
142       */
143       hRTC_Handle.Instance = RTC;
144       hRTC_Handle.Init.HourFormat = RTC_HOURFORMAT_24;
145       hRTC_Handle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV;
146       hRTC_Handle.Init.SynchPrediv = RTC_SYNCH_PREDIV;
147       hRTC_Handle.Init.OutPut = RTC_OUTPUT_DISABLE;
148       hRTC_Handle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
149       hRTC_Handle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
150       if (HAL_RTC_Init(&hRTC_Handle) != HAL_OK)
151       {
152         return HAL_ERROR;
153       }
154 
155       /* Disable the write protection for RTC registers */
156       __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
157 
158       /* Disable the Alarm A interrupt */
159       __HAL_RTC_ALARMA_DISABLE(&hRTC_Handle);
160 
161       /* Clear flag alarm A */
162       __HAL_RTC_ALARM_CLEAR_FLAG(&hRTC_Handle, RTC_FLAG_ALRAF);
163 
164       counter = 0U;
165       /* Wait till RTC ALRAWF flag is set and if Time out is reached exit */
166       while (__HAL_RTC_ALARM_GET_FLAG(&hRTC_Handle, RTC_FLAG_ALRAWF) == 0U)
167       {
168         if (counter++ == (SystemCoreClock / 56U)) /* Timeout = ~ 1s */
169         {
170           return HAL_ERROR;
171         }
172       }
173 
174       hRTC_Handle.Instance->ALRMAR = (uint32_t)0x01U;
175 
176       /* Configure the Alarm state: Enable Alarm */
177       __HAL_RTC_ALARMA_ENABLE(&hRTC_Handle);
178       /* Configure the Alarm interrupt */
179       __HAL_RTC_ALARM_ENABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
180 
181       /* RTC Alarm Interrupt Configuration: EXTI configuration */
182       __HAL_RTC_ALARM_EXTI_ENABLE_IT();
183 
184       /* Check if the Initialization mode is set */
185       if ((hRTC_Handle.Instance->ICSR & RTC_ICSR_INITF) == (uint32_t)RESET)
186       {
187         /* Set the Initialization mode */
188         hRTC_Handle.Instance->ICSR = (uint32_t)RTC_INIT_MASK;
189         counter = 0U;
190         while ((hRTC_Handle.Instance->ICSR & RTC_ICSR_INITF) == (uint32_t)RESET)
191         {
192           if (counter++ == (SystemCoreClock / 56U)) /* Timeout = ~ 1s */
193           {
194             return HAL_ERROR;
195           }
196         }
197       }
198       hRTC_Handle.Instance->DR = 0U;
199       hRTC_Handle.Instance->TR = 0U;
200 
201       hRTC_Handle.Instance->ICSR &= (uint32_t)~RTC_ICSR_INIT;
202 
203       /* Enable the write protection for RTC registers */
204       __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
205 
206       HAL_NVIC_SetPriority(RTC_IRQn, TickPriority, 0U);
207       HAL_NVIC_EnableIRQ(RTC_IRQn);
208       return HAL_OK;
209     }
210   }
211   return HAL_ERROR;
212 }
213 
214 /**
215   * @brief  Suspend Tick increment.
216   * @note   Disable the tick increment by disabling RTC ALARM interrupt.
217   * @retval None
218   */
HAL_SuspendTick(void)219 void HAL_SuspendTick(void)
220 {
221   /* Disable the write protection for RTC registers */
222   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
223   /* Disable RTC ALARM update Interrupt */
224   __HAL_RTC_ALARM_DISABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
225   /* Enable the write protection for RTC registers */
226   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
227 }
228 
229 /**
230   * @brief  Resume Tick increment.
231   * @note   Enable the tick increment by Enabling RTC ALARM interrupt.
232   * @retval None
233   */
HAL_ResumeTick(void)234 void HAL_ResumeTick(void)
235 {
236   /* Disable the write protection for RTC registers */
237   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
238   /* Enable RTC ALARM Update interrupt */
239   __HAL_RTC_ALARM_ENABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
240   /* Enable the write protection for RTC registers */
241   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
242 }
243 
244 /**
245   * @brief  ALARM A Event Callback in non blocking mode
246   * @note   This function is called  when RTC_ALARM interrupt took place, inside
247   * RTC_ALARM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
248   * a global variable "uwTick" used as application time base.
249   * @param  hrtc : RTC handle
250   * @retval None
251   */
HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef * hrtc)252 void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
253 {
254   __IO uint32_t counter = 0U;
255 
256   HAL_IncTick();
257 
258   __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
259 
260   /* Set the Initialization mode */
261   hrtc->Instance->ICSR = (uint32_t)RTC_INIT_MASK;
262 
263   while ((hrtc->Instance->ICSR & RTC_ICSR_INITF) == (uint32_t)RESET)
264   {
265     if (counter++ == (SystemCoreClock / 56U)) /* Timeout = ~ 1s */
266     {
267       break;
268     }
269   }
270 
271   hrtc->Instance->DR = 0U;
272   hrtc->Instance->TR = 0U;
273 
274   hrtc->Instance->ICSR &= (uint32_t)~RTC_ICSR_INIT;
275 
276   /* Enable the write protection for RTC registers */
277   __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
278 }
279 
280 /**
281   * @brief  This function handles RTC ALARM interrupt request.
282   * @retval None
283   */
RTC_IRQHandler(void)284 void RTC_IRQHandler(void)
285 {
286   HAL_RTC_AlarmIRQHandler(&hRTC_Handle);
287 }
288 
289 /**
290   * @}
291   */
292 
293 /**
294   * @}
295   */
296