1 /**
2   ******************************************************************************
3   * @file    stm32f4xx_hal.c
4   * @author  MCD Application Team
5   * @brief   HAL module driver.
6   *          This is the common part of the HAL initialization
7   *
8   ******************************************************************************
9   * @attention
10   *
11   * Copyright (c) 2017 STMicroelectronics.
12   * All rights reserved.
13   *
14   * This software is licensed under terms that can be found in the LICENSE file
15   * in the root directory of this software component.
16   * If no LICENSE file comes with this software, it is provided AS-IS.
17   *
18   ******************************************************************************
19   @verbatim
20   ==============================================================================
21                      ##### How to use this driver #####
22   ==============================================================================
23     [..]
24     The common HAL driver contains a set of generic and common APIs that can be
25     used by the PPP peripheral drivers and the user to start using the HAL.
26     [..]
27     The HAL contains two APIs' categories:
28          (+) Common HAL APIs
29          (+) Services HAL APIs
30 
31   @endverbatim
32   ******************************************************************************
33   */
34 
35 /* Includes ------------------------------------------------------------------*/
36 #include "stm32f4xx_hal.h"
37 
38 /** @addtogroup STM32F4xx_HAL_Driver
39   * @{
40   */
41 
42 /** @defgroup HAL HAL
43   * @brief HAL module driver.
44   * @{
45   */
46 
47 /* Private typedef -----------------------------------------------------------*/
48 /* Private define ------------------------------------------------------------*/
49 /** @addtogroup HAL_Private_Constants
50   * @{
51   */
52 /**
53   * @brief STM32F4xx HAL Driver version number V1.8.1
54   */
55 #define __STM32F4xx_HAL_VERSION_MAIN   (0x01U) /*!< [31:24] main version */
56 #define __STM32F4xx_HAL_VERSION_SUB1   (0x08U) /*!< [23:16] sub1 version */
57 #define __STM32F4xx_HAL_VERSION_SUB2   (0x01U) /*!< [15:8]  sub2 version */
58 #define __STM32F4xx_HAL_VERSION_RC     (0x00U) /*!< [7:0]  release candidate */
59 #define __STM32F4xx_HAL_VERSION         ((__STM32F4xx_HAL_VERSION_MAIN << 24U)\
60                                         |(__STM32F4xx_HAL_VERSION_SUB1 << 16U)\
61                                         |(__STM32F4xx_HAL_VERSION_SUB2 << 8U )\
62                                         |(__STM32F4xx_HAL_VERSION_RC))
63 
64 #define IDCODE_DEVID_MASK    0x00000FFFU
65 
66 /* ------------ RCC registers bit address in the alias region ----------- */
67 #define SYSCFG_OFFSET             (SYSCFG_BASE - PERIPH_BASE)
68 /* ---  MEMRMP Register ---*/
69 /* Alias word address of UFB_MODE bit */
70 #define MEMRMP_OFFSET             SYSCFG_OFFSET
71 #define UFB_MODE_BIT_NUMBER       SYSCFG_MEMRMP_UFB_MODE_Pos
72 #define UFB_MODE_BB               (uint32_t)(PERIPH_BB_BASE + (MEMRMP_OFFSET * 32U) + (UFB_MODE_BIT_NUMBER * 4U))
73 
74 /* ---  CMPCR Register ---*/
75 /* Alias word address of CMP_PD bit */
76 #define CMPCR_OFFSET              (SYSCFG_OFFSET + 0x20U)
77 #define CMP_PD_BIT_NUMBER         SYSCFG_CMPCR_CMP_PD_Pos
78 #define CMPCR_CMP_PD_BB           (uint32_t)(PERIPH_BB_BASE + (CMPCR_OFFSET * 32U) + (CMP_PD_BIT_NUMBER * 4U))
79 
80 /* ---  MCHDLYCR Register ---*/
81 /* Alias word address of BSCKSEL bit */
82 #define MCHDLYCR_OFFSET            (SYSCFG_OFFSET + 0x30U)
83 #define BSCKSEL_BIT_NUMBER         SYSCFG_MCHDLYCR_BSCKSEL_Pos
84 #define MCHDLYCR_BSCKSEL_BB        (uint32_t)(PERIPH_BB_BASE + (MCHDLYCR_OFFSET * 32U) + (BSCKSEL_BIT_NUMBER * 4U))
85 /**
86   * @}
87   */
88 
89 /* Private macro -------------------------------------------------------------*/
90 /* Private variables ---------------------------------------------------------*/
91 /** @addtogroup HAL_Private_Variables
92   * @{
93   */
94 __IO uint32_t uwTick;
95 uint32_t uwTickPrio   = (1UL << __NVIC_PRIO_BITS); /* Invalid PRIO */
96 HAL_TickFreqTypeDef uwTickFreq = HAL_TICK_FREQ_DEFAULT;  /* 1KHz */
97 /**
98   * @}
99   */
100 /* Private function prototypes -----------------------------------------------*/
101 /* Private functions ---------------------------------------------------------*/
102 
103 /** @defgroup HAL_Exported_Functions HAL Exported Functions
104   * @{
105   */
106 
107 /** @defgroup HAL_Exported_Functions_Group1 Initialization and de-initialization Functions
108  *  @brief    Initialization and de-initialization functions
109  *
110 @verbatim
111  ===============================================================================
112               ##### Initialization and Configuration functions #####
113  ===============================================================================
114     [..]  This section provides functions allowing to:
115       (+) Initializes the Flash interface the NVIC allocation and initial clock
116           configuration. It initializes the systick also when timeout is needed
117           and the backup domain when enabled.
118       (+) De-Initializes common part of the HAL.
119       (+) Configure the time base source to have 1ms time base with a dedicated
120           Tick interrupt priority.
121         (++) SysTick timer is used by default as source of time base, but user
122              can eventually implement his proper time base source (a general purpose
123              timer for example or other time source), keeping in mind that Time base
124              duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and
125              handled in milliseconds basis.
126         (++) Time base configuration function (HAL_InitTick ()) is called automatically
127              at the beginning of the program after reset by HAL_Init() or at any time
128              when clock is configured, by HAL_RCC_ClockConfig().
129         (++) Source of time base is configured  to generate interrupts at regular
130              time intervals. Care must be taken if HAL_Delay() is called from a
131              peripheral ISR process, the Tick interrupt line must have higher priority
132             (numerically lower) than the peripheral interrupt. Otherwise the caller
133             ISR process will be blocked.
134        (++) functions affecting time base configurations are declared as __weak
135              to make  override possible  in case of other  implementations in user file.
136 @endverbatim
137   * @{
138   */
139 
140 /**
141   * @brief  This function is used to initialize the HAL Library; it must be the first
142   *         instruction to be executed in the main program (before to call any other
143   *         HAL function), it performs the following:
144   *           Configure the Flash prefetch, instruction and Data caches.
145   *           Configures the SysTick to generate an interrupt each 1 millisecond,
146   *           which is clocked by the HSI (at this stage, the clock is not yet
147   *           configured and thus the system is running from the internal HSI at 16 MHz).
148   *           Set NVIC Group Priority to 4.
149   *           Calls the HAL_MspInit() callback function defined in user file
150   *           "stm32f4xx_hal_msp.c" to do the global low level hardware initialization
151   *
152   * @note   SysTick is used as time base for the HAL_Delay() function, the application
153   *         need to ensure that the SysTick time base is always set to 1 millisecond
154   *         to have correct HAL operation.
155   * @retval HAL status
156   */
HAL_Init(void)157 HAL_StatusTypeDef HAL_Init(void)
158 {
159   /* Configure Flash prefetch, Instruction cache, Data cache */
160 #if (INSTRUCTION_CACHE_ENABLE != 0U)
161   __HAL_FLASH_INSTRUCTION_CACHE_ENABLE();
162 #endif /* INSTRUCTION_CACHE_ENABLE */
163 
164 #if (DATA_CACHE_ENABLE != 0U)
165   __HAL_FLASH_DATA_CACHE_ENABLE();
166 #endif /* DATA_CACHE_ENABLE */
167 
168 #if (PREFETCH_ENABLE != 0U)
169   __HAL_FLASH_PREFETCH_BUFFER_ENABLE();
170 #endif /* PREFETCH_ENABLE */
171 
172   /* Set Interrupt Group Priority */
173   HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
174 
175   /* Use systick as time base source and configure 1ms tick (default clock after Reset is HSI) */
176   HAL_InitTick(TICK_INT_PRIORITY);
177 
178   /* Init the low level hardware */
179   HAL_MspInit();
180 
181   /* Return function status */
182   return HAL_OK;
183 }
184 
185 /**
186   * @brief  This function de-Initializes common part of the HAL and stops the systick.
187   *         This function is optional.
188   * @retval HAL status
189   */
HAL_DeInit(void)190 HAL_StatusTypeDef HAL_DeInit(void)
191 {
192   /* Reset of all peripherals */
193   __HAL_RCC_APB1_FORCE_RESET();
194   __HAL_RCC_APB1_RELEASE_RESET();
195 
196   __HAL_RCC_APB2_FORCE_RESET();
197   __HAL_RCC_APB2_RELEASE_RESET();
198 
199   __HAL_RCC_AHB1_FORCE_RESET();
200   __HAL_RCC_AHB1_RELEASE_RESET();
201 
202   __HAL_RCC_AHB2_FORCE_RESET();
203   __HAL_RCC_AHB2_RELEASE_RESET();
204 
205   __HAL_RCC_AHB3_FORCE_RESET();
206   __HAL_RCC_AHB3_RELEASE_RESET();
207 
208   /* De-Init the low level hardware */
209   HAL_MspDeInit();
210 
211   /* Return function status */
212   return HAL_OK;
213 }
214 
215 /**
216   * @brief  Initialize the MSP.
217   * @retval None
218   */
HAL_MspInit(void)219 __weak void HAL_MspInit(void)
220 {
221   /* NOTE : This function should not be modified, when the callback is needed,
222             the HAL_MspInit could be implemented in the user file
223    */
224 }
225 
226 /**
227   * @brief  DeInitializes the MSP.
228   * @retval None
229   */
HAL_MspDeInit(void)230 __weak void HAL_MspDeInit(void)
231 {
232   /* NOTE : This function should not be modified, when the callback is needed,
233             the HAL_MspDeInit could be implemented in the user file
234    */
235 }
236 
237 /**
238   * @brief This function configures the source of the time base.
239   *        The time source is configured  to have 1ms time base with a dedicated
240   *        Tick interrupt priority.
241   * @note This function is called  automatically at the beginning of program after
242   *       reset by HAL_Init() or at any time when clock is reconfigured  by HAL_RCC_ClockConfig().
243   * @note In the default implementation, SysTick timer is the source of time base.
244   *       It is used to generate interrupts at regular time intervals.
245   *       Care must be taken if HAL_Delay() is called from a peripheral ISR process,
246   *       The SysTick interrupt must have higher priority (numerically lower)
247   *       than the peripheral interrupt. Otherwise the caller ISR process will be blocked.
248   *       The function is declared as __weak  to be overwritten  in case of other
249   *       implementation  in user file.
250   * @param TickPriority Tick interrupt priority.
251   * @retval HAL status
252   */
HAL_InitTick(uint32_t TickPriority)253 __weak HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
254 {
255   /* Configure the SysTick to have interrupt in 1ms time basis*/
256   if (HAL_SYSTICK_Config(SystemCoreClock / (1000U / uwTickFreq)) > 0U)
257   {
258     return HAL_ERROR;
259   }
260 
261   /* Configure the SysTick IRQ priority */
262   if (TickPriority < (1UL << __NVIC_PRIO_BITS))
263   {
264     HAL_NVIC_SetPriority(SysTick_IRQn, TickPriority, 0U);
265     uwTickPrio = TickPriority;
266   }
267   else
268   {
269     return HAL_ERROR;
270   }
271 
272   /* Return function status */
273   return HAL_OK;
274 }
275 
276 /**
277   * @}
278   */
279 
280 /** @defgroup HAL_Exported_Functions_Group2 HAL Control functions
281  *  @brief    HAL Control functions
282  *
283 @verbatim
284  ===============================================================================
285                       ##### HAL Control functions #####
286  ===============================================================================
287     [..]  This section provides functions allowing to:
288       (+) Provide a tick value in millisecond
289       (+) Provide a blocking delay in millisecond
290       (+) Suspend the time base source interrupt
291       (+) Resume the time base source interrupt
292       (+) Get the HAL API driver version
293       (+) Get the device identifier
294       (+) Get the device revision identifier
295       (+) Enable/Disable Debug module during SLEEP mode
296       (+) Enable/Disable Debug module during STOP mode
297       (+) Enable/Disable Debug module during STANDBY mode
298 
299 @endverbatim
300   * @{
301   */
302 
303 /**
304   * @brief This function is called to increment  a global variable "uwTick"
305   *        used as application time base.
306   * @note In the default implementation, this variable is incremented each 1ms
307   *       in SysTick ISR.
308  * @note This function is declared as __weak to be overwritten in case of other
309   *      implementations in user file.
310   * @retval None
311   */
HAL_IncTick(void)312 __weak void HAL_IncTick(void)
313 {
314   uwTick += uwTickFreq;
315 }
316 
317 /**
318   * @brief Provides a tick value in millisecond.
319   * @note This function is declared as __weak to be overwritten in case of other
320   *       implementations in user file.
321   * @retval tick value
322   */
HAL_GetTick(void)323 __weak uint32_t HAL_GetTick(void)
324 {
325   return uwTick;
326 }
327 
328 /**
329   * @brief This function returns a tick priority.
330   * @retval tick priority
331   */
HAL_GetTickPrio(void)332 uint32_t HAL_GetTickPrio(void)
333 {
334   return uwTickPrio;
335 }
336 
337 /**
338   * @brief Set new tick Freq.
339   * @retval Status
340   */
HAL_SetTickFreq(HAL_TickFreqTypeDef Freq)341 HAL_StatusTypeDef HAL_SetTickFreq(HAL_TickFreqTypeDef Freq)
342 {
343   HAL_StatusTypeDef status  = HAL_OK;
344   HAL_TickFreqTypeDef prevTickFreq;
345 
346   assert_param(IS_TICKFREQ(Freq));
347 
348   if (uwTickFreq != Freq)
349   {
350     /* Back up uwTickFreq frequency */
351     prevTickFreq = uwTickFreq;
352 
353     /* Update uwTickFreq global variable used by HAL_InitTick() */
354     uwTickFreq = Freq;
355 
356     /* Apply the new tick Freq  */
357     status = HAL_InitTick(uwTickPrio);
358 
359     if (status != HAL_OK)
360     {
361       /* Restore previous tick frequency */
362       uwTickFreq = prevTickFreq;
363     }
364   }
365 
366   return status;
367 }
368 
369 /**
370   * @brief Return tick frequency.
371   * @retval tick period in Hz
372   */
HAL_GetTickFreq(void)373 HAL_TickFreqTypeDef HAL_GetTickFreq(void)
374 {
375   return uwTickFreq;
376 }
377 
378 /**
379   * @brief This function provides minimum delay (in milliseconds) based
380   *        on variable incremented.
381   * @note In the default implementation , SysTick timer is the source of time base.
382   *       It is used to generate interrupts at regular time intervals where uwTick
383   *       is incremented.
384   * @note This function is declared as __weak to be overwritten in case of other
385   *       implementations in user file.
386   * @param Delay specifies the delay time length, in milliseconds.
387   * @retval None
388   */
HAL_Delay(uint32_t Delay)389 __weak void HAL_Delay(uint32_t Delay)
390 {
391   uint32_t tickstart = HAL_GetTick();
392   uint32_t wait = Delay;
393 
394   /* Add a freq to guarantee minimum wait */
395   if (wait < HAL_MAX_DELAY)
396   {
397     wait += (uint32_t)(uwTickFreq);
398   }
399 
400   while((HAL_GetTick() - tickstart) < wait)
401   {
402   }
403 }
404 
405 /**
406   * @brief Suspend Tick increment.
407   * @note In the default implementation , SysTick timer is the source of time base. It is
408   *       used to generate interrupts at regular time intervals. Once HAL_SuspendTick()
409   *       is called, the SysTick interrupt will be disabled and so Tick increment
410   *       is suspended.
411   * @note This function is declared as __weak to be overwritten in case of other
412   *       implementations in user file.
413   * @retval None
414   */
HAL_SuspendTick(void)415 __weak void HAL_SuspendTick(void)
416 {
417   /* Disable SysTick Interrupt */
418   SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk;
419 }
420 
421 /**
422   * @brief Resume Tick increment.
423   * @note In the default implementation , SysTick timer is the source of time base. It is
424   *       used to generate interrupts at regular time intervals. Once HAL_ResumeTick()
425   *       is called, the SysTick interrupt will be enabled and so Tick increment
426   *       is resumed.
427   * @note This function is declared as __weak to be overwritten in case of other
428   *       implementations in user file.
429   * @retval None
430   */
HAL_ResumeTick(void)431 __weak void HAL_ResumeTick(void)
432 {
433   /* Enable SysTick Interrupt */
434   SysTick->CTRL  |= SysTick_CTRL_TICKINT_Msk;
435 }
436 
437 /**
438   * @brief  Returns the HAL revision
439   * @retval version : 0xXYZR (8bits for each decimal, R for RC)
440   */
HAL_GetHalVersion(void)441 uint32_t HAL_GetHalVersion(void)
442 {
443   return __STM32F4xx_HAL_VERSION;
444 }
445 
446 /**
447   * @brief  Returns the device revision identifier.
448   * @retval Device revision identifier
449   */
HAL_GetREVID(void)450 uint32_t HAL_GetREVID(void)
451 {
452   return((DBGMCU->IDCODE) >> 16U);
453 }
454 
455 /**
456   * @brief  Returns the device identifier.
457   * @retval Device identifier
458   */
HAL_GetDEVID(void)459 uint32_t HAL_GetDEVID(void)
460 {
461   return((DBGMCU->IDCODE) & IDCODE_DEVID_MASK);
462 }
463 
464 /**
465   * @brief  Enable the Debug Module during SLEEP mode
466   * @retval None
467   */
HAL_DBGMCU_EnableDBGSleepMode(void)468 void HAL_DBGMCU_EnableDBGSleepMode(void)
469 {
470   SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP);
471 }
472 
473 /**
474   * @brief  Disable the Debug Module during SLEEP mode
475   * @retval None
476   */
HAL_DBGMCU_DisableDBGSleepMode(void)477 void HAL_DBGMCU_DisableDBGSleepMode(void)
478 {
479   CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP);
480 }
481 
482 /**
483   * @brief  Enable the Debug Module during STOP mode
484   * @retval None
485   */
HAL_DBGMCU_EnableDBGStopMode(void)486 void HAL_DBGMCU_EnableDBGStopMode(void)
487 {
488   SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP);
489 }
490 
491 /**
492   * @brief  Disable the Debug Module during STOP mode
493   * @retval None
494   */
HAL_DBGMCU_DisableDBGStopMode(void)495 void HAL_DBGMCU_DisableDBGStopMode(void)
496 {
497   CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP);
498 }
499 
500 /**
501   * @brief  Enable the Debug Module during STANDBY mode
502   * @retval None
503   */
HAL_DBGMCU_EnableDBGStandbyMode(void)504 void HAL_DBGMCU_EnableDBGStandbyMode(void)
505 {
506   SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY);
507 }
508 
509 /**
510   * @brief  Disable the Debug Module during STANDBY mode
511   * @retval None
512   */
HAL_DBGMCU_DisableDBGStandbyMode(void)513 void HAL_DBGMCU_DisableDBGStandbyMode(void)
514 {
515   CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY);
516 }
517 
518 /**
519   * @brief  Enables the I/O Compensation Cell.
520   * @note   The I/O compensation cell can be used only when the device supply
521   *         voltage ranges from 2.4 to 3.6 V.
522   * @retval None
523   */
HAL_EnableCompensationCell(void)524 void HAL_EnableCompensationCell(void)
525 {
526   *(__IO uint32_t *)CMPCR_CMP_PD_BB = (uint32_t)ENABLE;
527 }
528 
529 /**
530   * @brief  Power-down the I/O Compensation Cell.
531   * @note   The I/O compensation cell can be used only when the device supply
532   *         voltage ranges from 2.4 to 3.6 V.
533   * @retval None
534   */
HAL_DisableCompensationCell(void)535 void HAL_DisableCompensationCell(void)
536 {
537   *(__IO uint32_t *)CMPCR_CMP_PD_BB = (uint32_t)DISABLE;
538 }
539 
540 /**
541   * @brief  Returns first word of the unique device identifier (UID based on 96 bits)
542   * @retval Device identifier
543   */
HAL_GetUIDw0(void)544 uint32_t HAL_GetUIDw0(void)
545 {
546   return (READ_REG(*((uint32_t *)UID_BASE)));
547 }
548 
549 /**
550   * @brief  Returns second word of the unique device identifier (UID based on 96 bits)
551   * @retval Device identifier
552   */
HAL_GetUIDw1(void)553 uint32_t HAL_GetUIDw1(void)
554 {
555   return (READ_REG(*((uint32_t *)(UID_BASE + 4U))));
556 }
557 
558 /**
559   * @brief  Returns third word of the unique device identifier (UID based on 96 bits)
560   * @retval Device identifier
561   */
HAL_GetUIDw2(void)562 uint32_t HAL_GetUIDw2(void)
563 {
564   return (READ_REG(*((uint32_t *)(UID_BASE + 8U))));
565 }
566 
567 #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) ||\
568     defined(STM32F469xx) || defined(STM32F479xx)
569 /**
570   * @brief  Enables the Internal FLASH Bank Swapping.
571   *
572   * @note   This function can be used only for STM32F42xxx/43xxx/469xx/479xx devices.
573   *
574   * @note   Flash Bank2 mapped at 0x08000000 (and aliased @0x00000000)
575   *         and Flash Bank1 mapped at 0x08100000 (and aliased at 0x00100000)
576   *
577   * @retval None
578   */
HAL_EnableMemorySwappingBank(void)579 void HAL_EnableMemorySwappingBank(void)
580 {
581   *(__IO uint32_t *)UFB_MODE_BB = (uint32_t)ENABLE;
582 }
583 
584 /**
585   * @brief  Disables the Internal FLASH Bank Swapping.
586   *
587   * @note   This function can be used only for STM32F42xxx/43xxx/469xx/479xx devices.
588   *
589   * @note   The default state : Flash Bank1 mapped at 0x08000000 (and aliased @0x00000000)
590   *         and Flash Bank2 mapped at 0x08100000 (and aliased at 0x00100000)
591   *
592   * @retval None
593   */
HAL_DisableMemorySwappingBank(void)594 void HAL_DisableMemorySwappingBank(void)
595 {
596   *(__IO uint32_t *)UFB_MODE_BB = (uint32_t)DISABLE;
597 }
598 #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */
599 /**
600   * @}
601   */
602 
603 /**
604   * @}
605   */
606 
607 /**
608   * @}
609   */
610 
611 /**
612   * @}
613   */
614 
615