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