1 /**
2   ******************************************************************************
3   * @file    stm32n6xx_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) 2023 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          STM32N6xx 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 "stm32n6xx_hal.h"
115 
116 /** @addtogroup STM32N6xx_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   /* Acknowledge the early wakeup interrupt in any cases. it clears the EWIF flag in SR register */
244   hiwdg->Instance->ICR = IWDG_ICR_EWIC;
245 
246   if (hiwdg->Init.EWI != IWDG_EWI_DISABLE)
247   {
248     /* EWI comparator value different from 0, Enable the early wakeup interrupt
249      * Set Watchdog Early Wakeup Comparator value
250      */
251     hiwdg->Instance->EWCR = IWDG_EWCR_EWIE | hiwdg->Init.EWI;
252   }
253   else
254   {
255     hiwdg->Instance->EWCR = 0x00U;
256   }
257   /* Check pending flag, if previous update not done, return timeout */
258   tickstart = HAL_GetTick();
259 
260   /* Wait for register to be updated */
261   while ((hiwdg->Instance->SR & IWDG_KERNEL_UPDATE_FLAGS) != 0x00u)
262   {
263     if ((HAL_GetTick() - tickstart) > HAL_IWDG_DEFAULT_TIMEOUT)
264     {
265       if ((hiwdg->Instance->SR & IWDG_KERNEL_UPDATE_FLAGS) != 0x00u)
266       {
267         return HAL_TIMEOUT;
268       }
269     }
270   }
271 
272   /* If window parameter is different than current value, modify window
273   register */
274   if (hiwdg->Instance->WINR != hiwdg->Init.Window)
275   {
276     /* Write to IWDG WINR the IWDG_Window value to compare with. In any case,
277     even if window feature is disabled, Watchdog will be reloaded by writing
278     windows register */
279     hiwdg->Instance->WINR = hiwdg->Init.Window;
280   }
281   else
282   {
283     /* Reload IWDG counter with value defined in the reload register */
284     __HAL_IWDG_RELOAD_COUNTER(hiwdg);
285   }
286 
287   /* Return function status */
288   return HAL_OK;
289 }
290 
291 
292 /**
293   * @brief  Initialize the IWDG MSP.
294   * @param  hiwdg  pointer to a IWDG_HandleTypeDef structure that contains
295   *                the configuration information for the specified IWDG module.
296   * @note   When rewriting this function in user file, mechanism may be added
297   *         to avoid multiple initialize when HAL_IWDG_Init function is called
298   *         again to change parameters.
299   * @retval None
300   */
HAL_IWDG_MspInit(IWDG_HandleTypeDef * hiwdg)301 __weak void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg)
302 {
303   /* Prevent unused argument(s) compilation warning */
304   UNUSED(hiwdg);
305 
306   /* NOTE: This function should not be modified, when the callback is needed,
307            the HAL_IWDG_MspInit could be implemented in the user file
308    */
309 }
310 
311 
312 #if (USE_HAL_IWDG_REGISTER_CALLBACKS == 1)
313 /**
314   * @brief  Register a User IWDG Callback
315   *         To be used instead of the weak (surcharged) predefined callback
316   * @param  hiwdg IWDG handle
317   * @param  CallbackID ID of the callback to be registered
318   *         This parameter can be one of the following values:
319   *           @arg @ref HAL_IWDG_EWI_CB_ID Early WakeUp Interrupt Callback ID
320   *           @arg @ref HAL_IWDG_MSPINIT_CB_ID MspInit callback ID
321   * @param  pCallback pointer to the Callback function
322   * @retval status
323   */
HAL_IWDG_RegisterCallback(IWDG_HandleTypeDef * hiwdg,HAL_IWDG_CallbackIDTypeDef CallbackID,pIWDG_CallbackTypeDef pCallback)324 HAL_StatusTypeDef HAL_IWDG_RegisterCallback(IWDG_HandleTypeDef *hiwdg, HAL_IWDG_CallbackIDTypeDef CallbackID,
325                                             pIWDG_CallbackTypeDef pCallback)
326 {
327   HAL_StatusTypeDef status = HAL_OK;
328 
329   if (pCallback == NULL)
330   {
331     status = HAL_ERROR;
332   }
333   else
334   {
335     switch (CallbackID)
336     {
337       case HAL_IWDG_EWI_CB_ID:
338         hiwdg->EwiCallback = pCallback;
339         break;
340       case HAL_IWDG_MSPINIT_CB_ID:
341         hiwdg->MspInitCallback = pCallback;
342         break;
343 
344       default:
345         status = HAL_ERROR;
346         break;
347     }
348   }
349 
350   return status;
351 }
352 
353 
354 /**
355   * @brief  Unregister a IWDG Callback
356   *         IWDG Callback is redirected to the weak (surcharged) predefined callback
357   * @param  hiwdg IWDG handle
358   * @param  CallbackID ID of the callback to be registered
359   *         This parameter can be one of the following values:
360   *           @arg @ref HAL_IWDG_EWI_CB_ID Early WakeUp Interrupt Callback ID
361   *           @arg @ref HAL_IWDG_MSPINIT_CB_ID MspInit callback ID
362   * @retval status
363   */
HAL_IWDG_UnRegisterCallback(IWDG_HandleTypeDef * hiwdg,HAL_IWDG_CallbackIDTypeDef CallbackID)364 HAL_StatusTypeDef HAL_IWDG_UnRegisterCallback(IWDG_HandleTypeDef *hiwdg, HAL_IWDG_CallbackIDTypeDef CallbackID)
365 {
366   HAL_StatusTypeDef status = HAL_OK;
367 
368   switch (CallbackID)
369   {
370     case HAL_IWDG_EWI_CB_ID:
371       hiwdg->EwiCallback = HAL_IWDG_EarlyWakeupCallback;
372       break;
373     case HAL_IWDG_MSPINIT_CB_ID:
374       hiwdg->MspInitCallback = HAL_IWDG_MspInit;
375       break;
376 
377     default:
378       status = HAL_ERROR;
379       break;
380   }
381 
382   return status;
383 }
384 #endif /* USE_HAL_IWDG_REGISTER_CALLBACKS */
385 
386 
387 /**
388   * @}
389   */
390 
391 
392 /** @addtogroup IWDG_Exported_Functions_Group2
393   *  @brief   IO operation functions
394   *
395 @verbatim
396  ===============================================================================
397                       ##### IO operation functions #####
398  ===============================================================================
399  [..]  This section provides functions allowing to:
400       (+) Refresh the IWDG.
401 
402 @endverbatim
403   * @{
404   */
405 
406 /**
407   * @brief  Refresh the IWDG.
408   * @param  hiwdg  pointer to a IWDG_HandleTypeDef structure that contains
409   *                the configuration information for the specified IWDG module.
410   * @retval HAL status
411   */
HAL_IWDG_Refresh(IWDG_HandleTypeDef * hiwdg)412 HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg)
413 {
414   /* Reload IWDG counter with value defined in the reload register */
415   __HAL_IWDG_RELOAD_COUNTER(hiwdg);
416 
417   /* Return function status */
418   return HAL_OK;
419 }
420 
421 
422 /**
423   * @brief  Get back IWDG running status
424   * @note   This API allows to know if IWDG has been started by other master, thread
425   *         or by hardware.
426   * @param  hiwdg  pointer to a IWDG_HandleTypeDef structure that contains
427   *                the configuration information for the specified IWDG module.
428   * @retval can be one of following value :
429   *           @arg @ref IWDG_STATUS_DISABLE
430   *           @arg @ref IWDG_STATUS_ENABLE
431   */
HAL_IWDG_GetActiveStatus(const IWDG_HandleTypeDef * hiwdg)432 uint32_t HAL_IWDG_GetActiveStatus(const IWDG_HandleTypeDef *hiwdg)
433 {
434   uint32_t status;
435 
436   /* Get back ONF flag */
437   status = (hiwdg->Instance->SR & IWDG_SR_ONF);
438 
439   /* Return status */
440   return status;
441 }
442 
443 
444 /**
445   * @brief  Handle IWDG interrupt request.
446   * @note   The Early Wakeup Interrupt (EWI) can be used if specific safety operations
447   *         or data logging must be performed before the actual reset is generated.
448   *         The EWI interrupt is enabled by calling HAL_IWDG_Init function with
449   *         EWIMode set to IWDG_EWI_ENABLE.
450   *         When the downcounter reaches the value 0x40, and EWI interrupt is
451   *         generated and the corresponding Interrupt Service Routine (ISR) can
452   *         be used to trigger specific actions (such as communications or data
453   *         logging), before resetting the device.
454   * @param  hiwdg  pointer to a IWDG_HandleTypeDef structure that contains
455   *                the configuration information for the specified IWDG module.
456   * @retval None
457   */
HAL_IWDG_IRQHandler(IWDG_HandleTypeDef * hiwdg)458 void HAL_IWDG_IRQHandler(IWDG_HandleTypeDef *hiwdg)
459 {
460   /* Check if IWDG Early Wakeup Interrupt occurred */
461   if ((hiwdg->Instance->SR & IWDG_SR_EWIF) != 0x00u)
462   {
463     /* Clear the IWDG Early Wakeup flag */
464     hiwdg->Instance->ICR = IWDG_ICR_EWIC;
465 
466 #if (USE_HAL_IWDG_REGISTER_CALLBACKS == 1)
467     /* Early Wakeup registered callback */
468     hiwdg->EwiCallback(hiwdg);
469 #else
470     /* Early Wakeup callback */
471     HAL_IWDG_EarlyWakeupCallback(hiwdg);
472 #endif /* USE_HAL_IWDG_REGISTER_CALLBACKS */
473   }
474 }
475 
476 
477 /**
478   * @brief  IWDG Early Wakeup callback.
479   * @param  hiwdg  pointer to a IWDG_HandleTypeDef structure that contains
480   *                the configuration information for the specified IWDG module.
481   * @retval None
482   */
HAL_IWDG_EarlyWakeupCallback(IWDG_HandleTypeDef * hiwdg)483 __weak void HAL_IWDG_EarlyWakeupCallback(IWDG_HandleTypeDef *hiwdg)
484 {
485   /* Prevent unused argument(s) compilation warning */
486   UNUSED(hiwdg);
487 
488   /* NOTE: This function should not be modified, when the callback is needed,
489            the HAL_IWDG_EarlyWakeupCallback could be implemented in the user file
490    */
491 }
492 
493 
494 /**
495   * @}
496   */
497 
498 /**
499   * @}
500   */
501 
502 #endif /* HAL_IWDG_MODULE_ENABLED */
503 /**
504   * @}
505   */
506 
507 /**
508   * @}
509   */
510