1 /**
2   ******************************************************************************
3   * @file    stm32wbaxx_hal_iwdg.c
4   * @author  MCD Application Team
5   * @brief   IWDG HAL module driver.
6   *          This file provides firmware functions to manage the following
7   *          functionalities of the Independent Watchdog (IWDG) peripheral:
8   *           + Initialization and Start functions
9   *           + IO operation functions
10   *
11   ******************************************************************************
12   * @attention
13   *
14   * Copyright (c) 2022 STMicroelectronics.
15   * All rights reserved.
16   *
17   * This software is licensed under terms that can be found in the LICENSE file
18   * in the root directory of this software component.
19   * If no LICENSE file comes with this software, it is provided AS-IS.
20   *
21   ******************************************************************************
22   @verbatim
23   ==============================================================================
24                     ##### IWDG Generic features #####
25   ==============================================================================
26   [..]
27     (+) The IWDG can be started by either software or hardware (configurable
28         through option byte).
29 
30     (+) The IWDG is clocked by the Low-Speed Internal clock (LSI) and thus stays
31         active even if the main clock fails.
32 
33     (+) Once the IWDG is started, the LSI is forced ON and both cannot be
34         disabled. The counter starts counting down from the reset value (0xFFF).
35         When it reaches the end of count value (0x000) a reset signal is
36         generated (IWDG reset).
37 
38     (+) Whenever the key value 0x0000 AAAA is written in the IWDG_KR register,
39         the IWDG_RLR value is reloaded into the counter and the watchdog reset
40         is prevented.
41 
42     (+) The IWDG is implemented in the VDD voltage domain that is still functional
43         in STOP and STANDBY mode (IWDG reset can wake up the CPU from STANDBY).
44         IWDGRST flag in RCC_CSR register can be used to inform when an IWDG
45         reset occurs.
46 
47     (+) Debug mode: When the microcontroller enters debug mode (core halted),
48         the IWDG counter either continues to work normally or stops, depending
49         on DBG_IWDG_STOP configuration bit in DBG module, accessible through
50         __HAL_DBGMCU_FREEZE_IWDG() and __HAL_DBGMCU_UNFREEZE_IWDG() macros.
51 
52     [..] Min-max timeout value @32KHz (LSI): ~125us / ~131.04s
53          The IWDG timeout may vary due to LSI clock frequency dispersion.
54          STM32WBAxx devices provide the capability to measure the LSI clock
55          frequency (LSI clock is internally connected to TIM16 CH1 input capture).
56          The measured value can be used to have an IWDG timeout with an
57          acceptable accuracy.
58 
59     [..] Default timeout value (necessary for IWDG_SR status register update):
60          Constant LSI_VALUE is defined based on the nominal LSI clock frequency.
61          This frequency being subject to variations as mentioned above, the
62          default timeout value (defined through constant HAL_IWDG_DEFAULT_TIMEOUT
63          below) may become too short or too long.
64          In such cases, this default timeout value can be tuned by redefining
65          the constant LSI_VALUE at user-application level (based, for instance,
66          on the measured LSI clock frequency as explained above).
67 
68                      ##### How to use this driver #####
69   ==============================================================================
70   [..]
71     (#) Register callback to treat Iwdg interrupt and MspInit using HAL_IWDG_RegisterCallback().
72       (++) Provide exiting handle as first parameter.
73       (++) Provide which callback will be registered using one value from
74            HAL_IWDG_CallbackIDTypeDef.
75       (++) Provide callback function pointer.
76 
77     (#) Use IWDG using HAL_IWDG_Init() function to :
78       (++) Enable instance by writing Start keyword in IWDG_KEY register. LSI
79            clock is forced ON and IWDG counter starts counting down.
80       (++) Enable write access to configuration registers:
81           IWDG_PR, IWDG_RLR, IWDG_WINR and EWCR.
82       (++) Configure the IWDG prescaler and counter reload value. This reload
83            value will be loaded in the IWDG counter each time the watchdog is
84            reloaded, then the IWDG will start counting down from this value.
85       (++) Depending on window parameter:
86         (+++) If Window Init parameter is same as Window register value,
87              nothing more is done but reload counter value in order to exit
88              function with exact time base.
89         (+++) Else modify Window register. This will automatically reload
90              watchdog counter.
91       (++) Depending on Early Wakeup Interrupt parameter:
92         (+++) If EWI is set to disable, comparator is set to 0, interrupt is
93              disable & flag is clear.
94         (+++) Else modify EWCR register, setting comparator value, enable
95              interrupt & clear flag.
96       (++) Wait for status flags to be reset.
97 
98     (#) Then the application program must refresh the IWDG counter at regular
99         intervals during normal operation to prevent an MCU reset, using
100         HAL_IWDG_Refresh() function.
101 
102      *** IWDG HAL driver macros list ***
103      ====================================
104      [..]
105        Below the list of most used macros in IWDG HAL driver:
106       (+) __HAL_IWDG_START: Enable the IWDG peripheral
107       (+) __HAL_IWDG_RELOAD_COUNTER: Reloads IWDG counter with value defined in
108           the reload register
109 
110   @endverbatim
111   */
112 
113 /* Includes ------------------------------------------------------------------*/
114 #include "stm32wbaxx_hal.h"
115 
116 /** @addtogroup STM32WBAxx_HAL_Driver
117   * @{
118   */
119 
120 #ifdef HAL_IWDG_MODULE_ENABLED
121 /** @addtogroup IWDG
122   * @brief IWDG HAL module driver.
123   * @{
124   */
125 
126 /* Private typedef -----------------------------------------------------------*/
127 /* Private define ------------------------------------------------------------*/
128 /** @defgroup IWDG_Private_Defines IWDG Private Defines
129   * @{
130   */
131 /* Status register needs up to 5 LSI clock periods to be updated. However a
132    synchronisation is added on prescaled LSI clock rising edge, so we only
133    consider a highest prescaler cycle.
134    The timeout value is calculated using the highest prescaler (1024) and
135    the LSI_VALUE constant. The value of this constant can be changed by the user
136    to take into account possible LSI clock period variations.
137    The timeout value is multiplied by 1000 to be converted in milliseconds.
138    LSI startup time is also considered here by adding LSI_STARTUP_TIME
139    converted in milliseconds. */
140 #define HAL_IWDG_DEFAULT_TIMEOUT        (((1UL * 1024UL * 1000UL) / LSI_VALUE) + ((LSI_STARTUP_TIME / 1000UL) + 1UL))
141 #define IWDG_KERNEL_UPDATE_FLAGS        (IWDG_SR_EWU | IWDG_SR_WVU | IWDG_SR_RVU | IWDG_SR_PVU)
142 /**
143   * @}
144   */
145 
146 /* Private macro -------------------------------------------------------------*/
147 /* Private variables ---------------------------------------------------------*/
148 /* Private function prototypes -----------------------------------------------*/
149 /* Exported functions --------------------------------------------------------*/
150 
151 /** @addtogroup IWDG_Exported_Functions
152   * @{
153   */
154 
155 /** @addtogroup IWDG_Exported_Functions_Group1
156   *  @brief    Initialization and Start functions.
157   *
158 @verbatim
159  ===============================================================================
160           ##### Initialization and Start functions #####
161  ===============================================================================
162  [..]  This section provides functions allowing to:
163       (+) Initialize the IWDG according to the specified parameters in the
164           IWDG_InitTypeDef of associated handle.
165       (+) Manage Window option.
166       (+) Once initialization is performed in HAL_IWDG_Init function, Watchdog
167           is reloaded in order to exit function with correct time base.
168 
169 @endverbatim
170   * @{
171   */
172 
173 /**
174   * @brief  Initialize the IWDG according to the specified parameters in the
175   *         IWDG_InitTypeDef and start watchdog. Before exiting function,
176   *         watchdog is refreshed in order to have correct time base.
177   * @param  hiwdg  pointer to a IWDG_HandleTypeDef structure that contains
178   *                the configuration information for the specified IWDG module.
179   * @retval HAL status
180   */
HAL_IWDG_Init(IWDG_HandleTypeDef * hiwdg)181 HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg)
182 {
183   uint32_t tickstart;
184 
185   /* Check the IWDG handle allocation */
186   if (hiwdg == NULL)
187   {
188     return HAL_ERROR;
189   }
190 
191   /* Check the parameters */
192   assert_param(IS_IWDG_ALL_INSTANCE(hiwdg->Instance));
193   assert_param(IS_IWDG_PRESCALER(hiwdg->Init.Prescaler));
194   assert_param(IS_IWDG_RELOAD(hiwdg->Init.Reload));
195   assert_param(IS_IWDG_WINDOW(hiwdg->Init.Window));
196   assert_param(IS_IWDG_EWI(hiwdg->Init.EWI));
197 
198 #if (USE_HAL_IWDG_REGISTER_CALLBACKS == 1)
199   /* Reset Callback pointers */
200   if (hiwdg->EwiCallback == NULL)
201   {
202     hiwdg->EwiCallback = HAL_IWDG_EarlyWakeupCallback;
203   }
204   if (hiwdg->MspInitCallback == NULL)
205   {
206     hiwdg->MspInitCallback = HAL_IWDG_MspInit;
207   }
208 
209   /* Init the low level hardware */
210   hiwdg->MspInitCallback(hiwdg);
211 #else
212   /* Init the low level hardware */
213   HAL_IWDG_MspInit(hiwdg);
214 #endif /* USE_HAL_IWDG_REGISTER_CALLBACKS */
215 
216   /* Enable IWDG. LSI is turned on automatically */
217   __HAL_IWDG_START(hiwdg);
218 
219   /* Enable write access to IWDG_PR, IWDG_RLR, IWDG_WINR and EWCR registers by writing
220   0x5555 in KR */
221   IWDG_ENABLE_WRITE_ACCESS(hiwdg);
222 
223   /* Write to IWDG registers the Prescaler & Reload values to work with */
224   hiwdg->Instance->PR = hiwdg->Init.Prescaler;
225   hiwdg->Instance->RLR = hiwdg->Init.Reload;
226 
227   /* Check Reload update flag, before performing any reload of the counter, else previous value
228   will be taken. */
229   tickstart = HAL_GetTick();
230 
231   /* Wait for register to be updated */
232   while ((hiwdg->Instance->SR & IWDG_SR_RVU) != 0x00u)
233   {
234     if ((HAL_GetTick() - tickstart) > HAL_IWDG_DEFAULT_TIMEOUT)
235     {
236       if ((hiwdg->Instance->SR & IWDG_SR_RVU) != 0x00u)
237       {
238         return HAL_TIMEOUT;
239       }
240     }
241   }
242 
243   if (hiwdg->Init.EWI == IWDG_EWI_DISABLE)
244   {
245     /* EWI comparator value equal 0, disable the early wakeup interrupt
246      * acknowledge the early wakeup interrupt in any cases. it clears the EWIF flag in SR register
247      * Set Watchdog Early Wakeup Comparator to 0x00 */
248     hiwdg->Instance->EWCR = IWDG_EWCR_EWIC;
249   }
250   else
251   {
252     /* EWI comparator value different from 0, enable the early wakeup interrupt,
253      * acknowledge the early wakeup interrupt in any cases. it clears the EWIF flag in SR register
254      * Set Watchdog Early Wakeup Comparator value */
255     hiwdg->Instance->EWCR = IWDG_EWCR_EWIE | IWDG_EWCR_EWIC | hiwdg->Init.EWI;
256   }
257 
258   /* Check pending flag, if previous update not done, return timeout */
259   tickstart = HAL_GetTick();
260 
261   /* Wait for register to be updated */
262   while ((hiwdg->Instance->SR & IWDG_KERNEL_UPDATE_FLAGS) != 0x00u)
263   {
264     if ((HAL_GetTick() - tickstart) > HAL_IWDG_DEFAULT_TIMEOUT)
265     {
266       if ((hiwdg->Instance->SR & IWDG_KERNEL_UPDATE_FLAGS) != 0x00u)
267       {
268         return HAL_TIMEOUT;
269       }
270     }
271   }
272 
273   /* If window parameter is different than current value, modify window
274   register */
275   if (hiwdg->Instance->WINR != hiwdg->Init.Window)
276   {
277     /* Write to IWDG WINR the IWDG_Window value to compare with. In any case,
278     even if window feature is disabled, Watchdog will be reloaded by writing
279     windows register */
280     hiwdg->Instance->WINR = hiwdg->Init.Window;
281   }
282   else
283   {
284     /* Reload IWDG counter with value defined in the reload register */
285     __HAL_IWDG_RELOAD_COUNTER(hiwdg);
286   }
287 
288   /* Return function status */
289   return HAL_OK;
290 }
291 
292 
293 /**
294   * @brief  Initialize the IWDG MSP.
295   * @param  hiwdg  pointer to a IWDG_HandleTypeDef structure that contains
296   *                the configuration information for the specified IWDG module.
297   * @note   When rewriting this function in user file, mechanism may be added
298   *         to avoid multiple initialize when HAL_IWDG_Init function is called
299   *         again to change parameters.
300   * @retval None
301   */
HAL_IWDG_MspInit(IWDG_HandleTypeDef * hiwdg)302 __weak void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg)
303 {
304   /* Prevent unused argument(s) compilation warning */
305   UNUSED(hiwdg);
306 
307   /* NOTE: This function should not be modified, when the callback is needed,
308            the HAL_IWDG_MspInit could be implemented in the user file
309    */
310 }
311 
312 
313 #if (USE_HAL_IWDG_REGISTER_CALLBACKS == 1)
314 /**
315   * @brief  Register a User IWDG Callback
316   *         To be used instead of the weak (surcharged) predefined callback
317   * @param  hiwdg IWDG handle
318   * @param  CallbackID ID of the callback to be registered
319   *         This parameter can be one of the following values:
320   *           @arg @ref HAL_IWDG_EWI_CB_ID Early WakeUp Interrupt Callback ID
321   *           @arg @ref HAL_IWDG_MSPINIT_CB_ID MspInit callback ID
322   * @param  pCallback pointer to the Callback function
323   * @retval status
324   */
HAL_IWDG_RegisterCallback(IWDG_HandleTypeDef * hiwdg,HAL_IWDG_CallbackIDTypeDef CallbackID,pIWDG_CallbackTypeDef pCallback)325 HAL_StatusTypeDef HAL_IWDG_RegisterCallback(IWDG_HandleTypeDef *hiwdg, HAL_IWDG_CallbackIDTypeDef CallbackID,
326                                             pIWDG_CallbackTypeDef pCallback)
327 {
328   HAL_StatusTypeDef status = HAL_OK;
329 
330   if (pCallback == NULL)
331   {
332     status = HAL_ERROR;
333   }
334   else
335   {
336     switch (CallbackID)
337     {
338       case HAL_IWDG_EWI_CB_ID:
339         hiwdg->EwiCallback = pCallback;
340         break;
341       case HAL_IWDG_MSPINIT_CB_ID:
342         hiwdg->MspInitCallback = pCallback;
343         break;
344 
345       default:
346         status = HAL_ERROR;
347         break;
348     }
349   }
350 
351   return status;
352 }
353 
354 
355 /**
356   * @brief  Unregister a IWDG Callback
357   *         IWDG Callback is redirected to the weak (surcharged) predefined callback
358   * @param  hiwdg IWDG handle
359   * @param  CallbackID ID of the callback to be registered
360   *         This parameter can be one of the following values:
361   *           @arg @ref HAL_IWDG_EWI_CB_ID Early WakeUp Interrupt Callback ID
362   *           @arg @ref HAL_IWDG_MSPINIT_CB_ID MspInit callback ID
363   * @retval status
364   */
HAL_IWDG_UnRegisterCallback(IWDG_HandleTypeDef * hiwdg,HAL_IWDG_CallbackIDTypeDef CallbackID)365 HAL_StatusTypeDef HAL_IWDG_UnRegisterCallback(IWDG_HandleTypeDef *hiwdg, HAL_IWDG_CallbackIDTypeDef CallbackID)
366 {
367   HAL_StatusTypeDef status = HAL_OK;
368 
369   switch (CallbackID)
370   {
371     case HAL_IWDG_EWI_CB_ID:
372       hiwdg->EwiCallback = HAL_IWDG_EarlyWakeupCallback;
373       break;
374     case HAL_IWDG_MSPINIT_CB_ID:
375       hiwdg->MspInitCallback = HAL_IWDG_MspInit;
376       break;
377 
378     default:
379       status = HAL_ERROR;
380       break;
381   }
382 
383   return status;
384 }
385 #endif /* USE_HAL_IWDG_REGISTER_CALLBACKS */
386 
387 
388 /**
389   * @}
390   */
391 
392 
393 /** @addtogroup IWDG_Exported_Functions_Group2
394   *  @brief   IO operation functions
395   *
396 @verbatim
397  ===============================================================================
398                       ##### IO operation functions #####
399  ===============================================================================
400  [..]  This section provides functions allowing to:
401       (+) Refresh the IWDG.
402 
403 @endverbatim
404   * @{
405   */
406 
407 /**
408   * @brief  Refresh the IWDG.
409   * @param  hiwdg  pointer to a IWDG_HandleTypeDef structure that contains
410   *                the configuration information for the specified IWDG module.
411   * @retval HAL status
412   */
HAL_IWDG_Refresh(IWDG_HandleTypeDef * hiwdg)413 HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg)
414 {
415   /* Reload IWDG counter with value defined in the reload register */
416   __HAL_IWDG_RELOAD_COUNTER(hiwdg);
417 
418   /* Return function status */
419   return HAL_OK;
420 }
421 
422 
423 /**
424   * @brief  Get back IWDG running status
425   * @note   This API allows to know if IWDG has been started by other master, thread
426   *         or by hardware.
427   * @param  hiwdg  pointer to a IWDG_HandleTypeDef structure that contains
428   *                the configuration information for the specified IWDG module.
429   * @retval can be one of following value :
430   *           @arg @ref IWDG_STATUS_DISABLE
431   *           @arg @ref IWDG_STATUS_ENABLE
432   */
HAL_IWDG_GetActiveStatus(const IWDG_HandleTypeDef * hiwdg)433 uint32_t HAL_IWDG_GetActiveStatus(const IWDG_HandleTypeDef *hiwdg)
434 {
435   uint32_t status;
436 
437   /* Get back ONF flag */
438   status = (hiwdg->Instance->SR & IWDG_SR_ONF);
439 
440   /* Return status */
441   return status;
442 }
443 
444 
445 /**
446   * @brief  Handle IWDG interrupt request.
447   * @note   The Early Wakeup Interrupt (EWI) can be used if specific safety operations
448   *         or data logging must be performed before the actual reset is generated.
449   *         The EWI interrupt is enabled by calling HAL_IWDG_Init function with
450   *         EWIMode set to IWDG_EWI_ENABLE.
451   *         When the downcounter reaches the value 0x40, and EWI interrupt is
452   *         generated and the corresponding Interrupt Service Routine (ISR) can
453   *         be used to trigger specific actions (such as communications or data
454   *         logging), before resetting the device.
455   * @param  hiwdg  pointer to a IWDG_HandleTypeDef structure that contains
456   *                the configuration information for the specified IWDG module.
457   * @retval None
458   */
HAL_IWDG_IRQHandler(IWDG_HandleTypeDef * hiwdg)459 void HAL_IWDG_IRQHandler(IWDG_HandleTypeDef *hiwdg)
460 {
461   /* Check if IWDG Early Wakeup Interrupt occurred */
462   if ((hiwdg->Instance->SR & IWDG_SR_EWIF) != 0x00u)
463   {
464     /* Clear the IWDG Early Wakeup flag */
465     hiwdg->Instance->EWCR |= IWDG_EWCR_EWIC;
466 
467 #if (USE_HAL_IWDG_REGISTER_CALLBACKS == 1)
468     /* Early Wakeup registered callback */
469     hiwdg->EwiCallback(hiwdg);
470 #else
471     /* Early Wakeup callback */
472     HAL_IWDG_EarlyWakeupCallback(hiwdg);
473 #endif /* USE_HAL_IWDG_REGISTER_CALLBACKS */
474   }
475 }
476 
477 
478 /**
479   * @brief  IWDG Early Wakeup callback.
480   * @param  hiwdg  pointer to a IWDG_HandleTypeDef structure that contains
481   *                the configuration information for the specified IWDG module.
482   * @retval None
483   */
HAL_IWDG_EarlyWakeupCallback(IWDG_HandleTypeDef * hiwdg)484 __weak void HAL_IWDG_EarlyWakeupCallback(IWDG_HandleTypeDef *hiwdg)
485 {
486   /* Prevent unused argument(s) compilation warning */
487   UNUSED(hiwdg);
488 
489   /* NOTE: This function should not be modified, when the callback is needed,
490            the HAL_IWDG_EarlyWakeupCallback could be implemented in the user file
491    */
492 }
493 
494 
495 /**
496   * @}
497   */
498 
499 /**
500   * @}
501   */
502 
503 #endif /* HAL_IWDG_MODULE_ENABLED */
504 /**
505   * @}
506   */
507 
508 /**
509   * @}
510   */
511