1 /**
2   ******************************************************************************
3   * @file    stm32wlxx_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
8   *          weak) to use the RTC ALARM for time base generation:
9   *           + Initializes the RTC peripheral to increment the seconds registers
10   *             each 1s
11   *           + The alarm is configured to assert an interrupt when the RTC
12   *             subsecond register reaches 1ms when uwTickFreq is set to default
13   *             value, else 10 ms or 100 ms, depending of above global variable
14   *             value.
15   *           + HAL_IncTick is called at each Alarm event
16   *           + HSE (default), LSE or LSI can be selected as RTC clock source
17   *
18   ******************************************************************************
19   * @attention
20   *
21   * Copyright (c) 2020 STMicroelectronics.
22   * All rights reserved.
23   *
24   * This software is licensed under terms that can be found in the LICENSE file
25   * in the root directory of this software component.
26   * If no LICENSE file comes with this software, it is provided AS-IS.
27   *
28   ******************************************************************************
29  @verbatim
30   ==============================================================================
31                         ##### How to use this driver #####
32   ==============================================================================
33     [..]
34     This file must be copied to the application folder and modified as follows:
35     (#) Rename it to 'stm32wlxx_hal_timebase_rtc_alarm.c'
36     (#) Add this file and the RTC HAL drivers to your project and uncomment
37        HAL_RTC_MODULE_ENABLED define in stm32wlxx_hal_conf.h
38 
39   @endverbatim
40   ******************************************************************************
41   */
42 
43 /* Includes ------------------------------------------------------------------*/
44 #include "stm32wlxx_hal.h"
45 /** @addtogroup STM32WLxx_HAL_Driver
46   * @{
47   */
48 
49 /** @defgroup HAL_TimeBase_RTC_Alarm_Template  HAL TimeBase RTC Alarm Template
50   * @{
51   */
52 
53 /* Private typedef -----------------------------------------------------------*/
54 /* Private define ------------------------------------------------------------*/
55 /* Uncomment the line below to select the appropriate RTC Clock source for your application:
56   + RTC_CLOCK_SOURCE_HSE: can be selected for applications requiring timing precision.
57   + RTC_CLOCK_SOURCE_LSE: can be selected for applications with low constraint on timing
58                           precision.
59   + RTC_CLOCK_SOURCE_LSI: can be selected for applications with low constraint on timing
60                           precision.
61   */
62 /* #define RTC_CLOCK_SOURCE_HSE */
63 /* #define RTC_CLOCK_SOURCE_LSE */
64 #define RTC_CLOCK_SOURCE_LSI
65 
66 #if !defined(RTC_CLOCK_SOURCE_LSI) && !defined(RTC_CLOCK_SOURCE_LSE) && !defined(RTC_CLOCK_SOURCE_HSE)
67 #error Please select the RTC Clock source AT PROJECT LEVEL
68 #endif
69 
70 /* Minimize Asynchronous prescaler for power consumption :
71   ck_apre = RTCCLK / (ASYNC prediv + 1)
72   ck_spre = ck_apre/(SYNC prediv + 1) = 1 Hz */
73 #if defined (RTC_CLOCK_SOURCE_LSE)
74 /* LSE Freq = 32.768 kHz RC */
75 #define RTC_ASYNCH_PREDIV                   0u
76 #define RTC_SYNCH_PREDIV                    0x3FFFu /* (16384 - 1) */
77 #elif defined (RTC_CLOCK_SOURCE_LSI)
78 /* LSI Freq = 32 kHz RC  */
79 #define RTC_ASYNCH_PREDIV                   0u
80 #define RTC_SYNCH_PREDIV                    0x3E7Fu /* (16000 - 1) */
81 #elif defined (RTC_CLOCK_SOURCE_HSE)
82 /* HSE Freq as RTCCLK = 32 MHz / 32 = 1 MHz */
83 #define RTC_ASYNCH_PREDIV                   0x1Fu   /* (32 - 1) */
84 #define RTC_SYNCH_PREDIV                    0x7A11u /* (31250 -1) */
85 #endif
86 
87 
88 /* Private macro -------------------------------------------------------------*/
89 /* Private variables ---------------------------------------------------------*/
90 RTC_HandleTypeDef        hRTC_Handle = {.Init = {0}};
91 
92 /* Private function prototypes -----------------------------------------------*/
93 #if defined(CORE_CM0PLUS)
94 void RTC_LSECSS_IRQHandler(void);
95 #else
96 void RTC_Alarm_IRQHandler(void);
97 #endif
98 
99 /* Private functions ---------------------------------------------------------*/
100 
101 /**
102   * @brief  This function configures the RTC ALARM A as a time base source.
103   *         The time source is configured to have 1ms time base with a dedicated
104   *         Tick interrupt priority.
105   *         Calendar time base is = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1)) / RTC_CLOCK
106   *                               = 1s
107   *         Alarm interrupt timebase is = (RTC_SYNCH_PREDIV / (1000 / uwTickFreq))
108   *                                     = 1 ms when uwTickFreq is set to 1 kHz
109   * @note   This function is called automatically at the beginning of program after
110   *         reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig().
111   * @param  TickPriority: Tick interrupt priority.
112   * @retval HAL status
113   */
HAL_InitTick(uint32_t TickPriority)114 HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
115 {
116   HAL_StatusTypeDef status = HAL_OK;
117   RCC_OscInitTypeDef        RCC_OscInitStruct = {0};
118   RCC_PeriphCLKInitTypeDef  PeriphClkInitStruct = {0};
119   RTC_TimeTypeDef           time;
120   RTC_DateTypeDef           date;
121   RTC_AlarmTypeDef          alarm;
122 
123 
124   /* Check uwTickFreq for MisraC 2012 (even if uwTickFreq is a enum type that don't take the value zero)*/
125   if ((uint32_t)uwTickFreq != 0U)
126   {
127     /* Disable backup domeain protection */
128     HAL_PWR_EnableBkUpAccess();
129 
130     /* Enable RTC APB clock gating */
131     __HAL_RCC_RTCAPB_CLK_ENABLE();
132 
133     /* Disable the Alarm A */
134     __HAL_RTC_ALARMA_DISABLE(&hRTC_Handle);
135     /* In case of interrupt mode is used, the interrupt source must disabled */
136     __HAL_RTC_ALARM_DISABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
137     __HAL_RTC_ALARM_CLEAR_FLAG(&hRTC_Handle, RTC_FLAG_ALRAF);
138 
139     /* Get RTC clock configuration */
140     HAL_RCCEx_GetPeriphCLKConfig(&PeriphClkInitStruct);
141 
142     /*In case of RTC clock already enable, make sure it's the good one */
143 #if defined (RTC_CLOCK_SOURCE_LSE)
144     if ((PeriphClkInitStruct.RTCClockSelection == RCC_RTCCLKSOURCE_LSE) && (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) != 0x00u))
145 #elif defined (RTC_CLOCK_SOURCE_LSI)
146     if ((PeriphClkInitStruct.RTCClockSelection == RCC_RTCCLKSOURCE_LSI) && (__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) != 0x00u))
147 #elif defined (RTC_CLOCK_SOURCE_HSE)
148     if ((PeriphClkInitStruct.RTCClockSelection == RCC_RTCCLKSOURCE_HSE_DIV32) && (__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != 0x00u))
149 #else
150 #error Please select the RTC Clock source
151 #endif
152     {
153       /* Do nothing */
154     }
155     else
156     {
157 #ifdef RTC_CLOCK_SOURCE_LSE
158       /* Configure LSE as RTC clock source */
159       RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE;
160       RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
161       RCC_OscInitStruct.LSEState = RCC_LSE_ON;
162       PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
163 #elif defined (RTC_CLOCK_SOURCE_LSI)
164       /* Configure LSI as RTC clock source */
165       RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI;
166       RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
167       RCC_OscInitStruct.LSIState = RCC_LSI_ON;
168       PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
169 #elif defined (RTC_CLOCK_SOURCE_HSE)
170       /* Configure HSE as RTC clock source */
171       RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
172       RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
173       RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS_PWR;
174       /* Ensure that RTC is clocked by 1MHz */
175       PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV32;
176 #endif
177 
178       /* COnfigure oscillator */
179       status = HAL_RCC_OscConfig(&RCC_OscInitStruct);
180       if(status == HAL_OK)
181       {
182         /* Configure RTC clock source */
183         PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
184         status = HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);
185 
186         /* Enable RTC Clock */
187         if(status == HAL_OK)
188         {
189           __HAL_RCC_RTC_ENABLE();
190         }
191       }
192     }
193 
194     /* If RTC Clock configuration is ok */
195     if (status == HAL_OK)
196     {
197       /* The time base is defined to have highest synchronous prescaler but keeping
198          a 1Hz RTC frequency. */
199       hRTC_Handle.Instance = RTC;
200       hRTC_Handle.Init.HourFormat = RTC_HOURFORMAT_24;
201       hRTC_Handle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV;
202       hRTC_Handle.Init.SynchPrediv = RTC_SYNCH_PREDIV;
203       hRTC_Handle.Init.OutPut = RTC_OUTPUT_DISABLE;
204       hRTC_Handle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
205       hRTC_Handle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
206       status = HAL_RTC_Init(&hRTC_Handle);
207     }
208 
209     /* HAL RTC Init is ok & calendar has never been initialized */
210     if((status == HAL_OK)  && (__HAL_RTC_GET_FLAG(&hRTC_Handle, RTC_FLAG_INITS) == 0x00u))
211     {
212       time.Hours = 0x00u;
213       time.Minutes = 0x00u;
214       time.Seconds = 0x00u;
215       time.TimeFormat = RTC_HOURFORMAT12_PM;
216       time.SubSeconds = 0x00u;
217       time.SecondFraction = 0x00u;
218       time.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
219       time.StoreOperation = RTC_STOREOPERATION_RESET;
220       status = HAL_RTC_SetTime(&hRTC_Handle, &time, RTC_FORMAT_BCD);
221       if(status == HAL_OK)
222       {
223         date.WeekDay = RTC_WEEKDAY_MONDAY;
224         date.Date = 0x01u;
225         date.Month = RTC_MONTH_JANUARY;
226         date.Year = 0x01u;
227         status = HAL_RTC_SetDate(&hRTC_Handle, &date, RTC_FORMAT_BCD);
228       }
229     }
230 
231     /* If RTC calendar is initialized */
232     if (status == HAL_OK)
233     {
234       alarm.AlarmTime.Hours = 0x00u;
235       alarm.AlarmTime.Minutes = 0x00u;
236       alarm.AlarmTime.Seconds = 0x00u;
237       alarm.AlarmTime.TimeFormat = RTC_HOURFORMAT12_PM;
238       alarm.AlarmTime.SubSeconds = (RTC_SYNCH_PREDIV / (1000 / (uint32_t)uwTickFreq));
239       alarm.AlarmTime.SecondFraction = 0x00u;
240       alarm.AlarmTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
241       alarm.AlarmTime.StoreOperation = RTC_STOREOPERATION_RESET;
242       alarm.AlarmMask = RTC_ALARMMASK_ALL;
243 
244       /* Depending on input frequency select Subsecond mask */
245       if (uwTickFreq == HAL_TICK_FREQ_1KHZ)
246       {
247         alarm.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_SS14_5;
248       }
249       else if (uwTickFreq == HAL_TICK_FREQ_100HZ)
250       {
251         alarm.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_SS14_9;
252       }
253       else
254       {
255 #if defined (RTC_CLOCK_SOURCE_HSE)
256         /* When RTCCLK = 1 MHz, need to mask Subsecond register bit 12 to 14
257           to have 10 Hhz interrupt */
258         alarm.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_SS14_12;
259 #else
260         /* When RTCCLK is around 32 kHz, need to mask Subsecond register bit 12 to 11
261           to have 10 Hhz interrupt */
262         alarm.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_SS14_11;
263 #endif
264       }
265       alarm.BinaryAutoClr = RTC_ALARMSUBSECONDBIN_AUTOCLR_NO;
266       alarm.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE;
267       alarm.AlarmDateWeekDay = RTC_WEEKDAY_MONDAY;
268       alarm.Alarm = RTC_ALARM_A;
269       status = HAL_RTC_SetAlarm_IT(&hRTC_Handle, &alarm, RTC_FORMAT_BCD);
270       if(status == HAL_OK)
271       {
272         /* Enable the RTC global Interrupt */
273 #if defined(CORE_CM0PLUS)
274         HAL_NVIC_EnableIRQ(RTC_LSECSS_IRQn);
275 #else
276         HAL_NVIC_EnableIRQ(RTC_Alarm_IRQn);
277 #endif
278 
279         /* Configure the SysTick IRQ priority */
280         if (TickPriority < (1UL << __NVIC_PRIO_BITS))
281         {
282 #if defined(CORE_CM0PLUS)
283           HAL_NVIC_SetPriority(RTC_LSECSS_IRQn, TickPriority, 0U);
284 #else
285           HAL_NVIC_SetPriority(RTC_Alarm_IRQn, TickPriority, 0U);
286 #endif
287           uwTickPrio = TickPriority;
288         }
289         else
290         {
291           status = HAL_ERROR;
292         }
293       }
294     }
295   }
296   else
297   {
298     status = HAL_ERROR;
299   }
300   return status;
301 }
302 
303 /**
304   * @brief  Suspend Tick increment.
305   * @note   Disable the tick increment by disabling RTC_ALRA interrupt.
306   * @retval None
307   */
HAL_SuspendTick(void)308 void HAL_SuspendTick(void)
309 {
310   /* Disable the write protection for RTC registers */
311   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
312   /* Disable ALARM A Interrupt */
313   __HAL_RTC_ALARM_DISABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
314   /* Enable the write protection for RTC registers */
315   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
316 }
317 
318 /**
319   * @brief  Resume Tick increment.
320   * @note   Enable the tick increment by Enabling RTC_ALRA interrupt.
321   * @retval None
322   */
HAL_ResumeTick(void)323 void HAL_ResumeTick(void)
324 {
325   /* Disable the write protection for RTC registers */
326   __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
327   /* Enable ALARM A interrupt */
328   __HAL_RTC_ALARM_ENABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
329   /* Enable the write protection for RTC registers */
330   __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
331 }
332 
333 /**
334   * @brief  Alarm Timer Event Callback in non blocking mode
335   * @note   This function is called  when RTC Alarm takes place, inside
336   *         HAL_RTC_AlarmIRQHandler(). It makes a direct call to HAL_IncTick() to increment
337   *         a global variable "uwTick" used as application time base.
338   * @param  hrtc : RTC handle
339   * @retval None
340   */
HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef * hrtc)341 void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
342 {
343   HAL_IncTick();
344 }
345 
346 /**
347   * @brief  This function handles Alarm interrupt request.
348   * @retval None
349   */
350 #if defined(CORE_CM0PLUS)
RTC_LSECSS_IRQHandler(void)351 void RTC_LSECSS_IRQHandler(void)
352 #else
353 void RTC_Alarm_IRQHandler(void)
354 #endif
355 {
356   HAL_RTC_AlarmIRQHandler(&hRTC_Handle);
357 }
358 
359 /**
360   * @}
361   */
362 
363 /**
364   * @}
365   */
366