最新教程下載:http://www.armbbs.cn/forum.php?mod=viewthread&tid=93255
第12章 STM32F407的HAL庫框架設計學習
通過本章節,主要是想讓大家對HAL庫程序設計的基本套路有個了解,防止踩坑。
12.1 初學者重要提示
12.2 HAL庫的配置文件
12.3 HAL庫的時間基准
12.4 HAL庫的啟動流程
12.5 HAL庫初始化外設
12.6 HAL庫的中斷處理思路
12.7 HAL庫的DMA處理思路
12.8 總結
12.1 初學者重要提示
- 學習使用HAL庫前,有必要對他們的基本設計框架有所了解,然后深入學習,效果更好。
- 為了方便調用,HAL庫為各種外設基本都配了三套API,查詢,中斷和DMA。
12.2 HAL庫的配置文件
HAL庫有一個專門的配置文件叫stm32f4xx_hal_conf.h,這個文件里面有一個很重要的參數,就是HSE_VALUE,大家所設計板子使用的實際晶振大小一定要與這個數值一致。比如V6的外置晶振是8MHz,那么這里就務必配置宏定義為:
#define HSE_VALUE ((uint32_t)8000000)
完整的代碼如下:
1. /* ########################## Module Selection ############################## */ 2. /** 3. * @brief This is the list of modules to be used in the HAL driver 4. */ 5. #define HAL_MODULE_ENABLED 6. #define HAL_ADC_MODULE_ENABLED 7. #define HAL_CAN_MODULE_ENABLED 8. #define HAL_HCD_MODULE_ENABLED 9. 10. /* 省略未寫 */ 11. 12. /* ########################## HSE/HSI Values adaptation ##################### */ 13. /** 14. * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. 15. * This value is used by the RCC HAL module to compute the system frequency 16. * (when HSE is used as system clock source, directly or through the PLL). 17. */ 18. #if !defined (HSE_VALUE) 19. #define HSE_VALUE (25000000U) /*!< Value of the External oscillator in Hz */ 20. #endif /* HSE_VALUE */ 21. 22. #if !defined (HSE_STARTUP_TIMEOUT) 23. #define HSE_STARTUP_TIMEOUT (100U) /*!< Time out for HSE start up, in ms */ 24. #endif /* HSE_STARTUP_TIMEOUT */ 25. 26. /** 27. * @brief Internal High Speed oscillator (HSI) value. 28. * This value is used by the RCC HAL module to compute the system frequency 29. * (when HSI is used as system clock source, directly or through the PLL). 30. */ 31. #if !defined (HSI_VALUE) 32. #define HSI_VALUE (16000000U) /*!< Value of the Internal oscillator in Hz*/ 33. #endif /* HSI_VALUE */ 34. 35. /** 36. * @brief Internal Low Speed oscillator (LSI) value. 37. */ 38. #if !defined (LSI_VALUE) 39. #define LSI_VALUE (32000U) 40. #endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz 41. The real value may vary depending on the variations 42. in voltage and temperature. */ 43. /** 44. * @brief External Low Speed oscillator (LSE) value. 45. */ 46. #if !defined (LSE_VALUE) 47. #define LSE_VALUE (32768U) /*!< Value of the External Low Speed oscillator in Hz */ 48. #endif /* LSE_VALUE */ 49. 50. #if !defined (LSE_STARTUP_TIMEOUT) 51. #define LSE_STARTUP_TIMEOUT (5000U) /*!< Time out for LSE start up, in ms */ 52. #endif /* LSE_STARTUP_TIMEOUT */ 53. 54. /** 55. * @brief External clock source for I2S peripheral 56. * This value is used by the I2S HAL module to compute the I2S clock source 57. * frequency, this source is inserted directly through I2S_CKIN pad. 58. */ 59. #if !defined (EXTERNAL_CLOCK_VALUE) 60. #define EXTERNAL_CLOCK_VALUE (12288000U) /*!< Value of the External oscillator in Hz*/ 61. #endif /* EXTERNAL_CLOCK_VALUE */ 62. 63. /* Tip: To avoid modifying this file each time you need to use different HSE, 64. === you can define the HSE value in your toolchain compiler preprocessor. */ 65. 66. /* ########################### System Configuration ######################### */ 67. /** 68. * @brief This is the HAL system configuration section 69. */ 70. #define VDD_VALUE (3300U) /*!< Value of VDD in mv */ 71. #define TICK_INT_PRIORITY (0x0FU) /*!< tick interrupt priority */ 72. #define USE_RTOS 0U 73. #define PREFETCH_ENABLE 1U 74. #define INSTRUCTION_CACHE_ENABLE 1U 75. #define DATA_CACHE_ENABLE 1U 76. 77. #define USE_HAL_ADC_REGISTER_CALLBACKS 0U /* ADC register callback disabled */ 78. #define USE_HAL_CAN_REGISTER_CALLBACKS 0U /* CAN register callback disabled */ 79. #define USE_HAL_CEC_REGISTER_CALLBACKS 0U /* CEC register callback disabled */ 80. /* 省略未寫 */ 81. #define USE_HAL_UART_REGISTER_CALLBACKS 0U /* UART register callback disabled */ 82. #define USE_HAL_USART_REGISTER_CALLBACKS 0U /* USART register callback disabled */ 83. #define USE_HAL_WWDG_REGISTER_CALLBACKS 0U /* WWDG register callback disabled */ 84. 85. /* ########################## Assert Selection ############################## */ 86. /** 87. * @brief Uncomment the line below to expanse the "assert_param" macro in the 88. * HAL drivers code 89. */ 90. /* #define USE_FULL_ASSERT 1U */ 91. 92. /* ################## Ethernet peripheral configuration ##################### */ 93. 94. /* Section 1 : Ethernet peripheral configuration */ 95. 96. /* MAC ADDRESS: MAC_ADDR0:MAC_ADDR1:MAC_ADDR2:MAC_ADDR3:MAC_ADDR4:MAC_ADDR5 */ 97. #define MAC_ADDR0 2U 98. #define MAC_ADDR1 0U 99. #define MAC_ADDR2 0U 100. #define MAC_ADDR3 0U 101. #define MAC_ADDR4 0U 102. #define MAC_ADDR5 0U 103. 104. /* Definition of the Ethernet driver buffers size and count */ 105. #define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for receive */ 106. #define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for transmit */ 107. #define ETH_RXBUFNB (4U) /* 4 Rx buffers of size ETH_RX_BUF_SIZE */ 108. #define ETH_TXBUFNB (4U) /* 4 Tx buffers of size ETH_TX_BUF_SIZE */ 109. 110. /* Section 2: PHY configuration section */ 111. 112. /* DP83848 PHY Address*/ 113. #define DP83848_PHY_ADDRESS 0x01U 114. /* PHY Reset delay these values are based on a 1 ms Systick interrupt*/ 115. #define PHY_RESET_DELAY (0x000000FFU) 116. /* PHY Configuration delay */ 117. #define PHY_CONFIG_DELAY (0x00000FFFU) 118. 119. #define PHY_READ_TO (0x0000FFFFU) 120. #define PHY_WRITE_TO (0x0000FFFFU) 121. 122. /* Section 3: Common PHY Registers */ 123. 124. #define PHY_BCR ((uint16_t)0x00) /*!< Transceiver Basic Control Register */ 125. #define PHY_BSR ((uint16_t)0x01) /*!< Transceiver Basic Status Register */ 126. 127. #define PHY_RESET ((uint16_t)0x8000) /*!< PHY Reset */ 128. #define PHY_LOOPBACK ((uint16_t)0x4000) /*!< Select loop-back mode */ 129. #define PHY_FULLDUPLEX_100M ((uint16_t)0x2100) /*!< Set the full-duplex mode at 100 Mb/s */ 130. #define PHY_HALFDUPLEX_100M ((uint16_t)0x2000) /*!< Set the half-duplex mode at 100 Mb/s */ 131. #define PHY_FULLDUPLEX_10M ((uint16_t)0x0100) /*!< Set the full-duplex mode at 10 Mb/s */ 132. #define PHY_HALFDUPLEX_10M ((uint16_t)0x0000) /*!< Set the half-duplex mode at 10 Mb/s */ 133. #define PHY_AUTONEGOTIATION ((uint16_t)0x1000) /*!< Enable auto-negotiation function */ 134. #define PHY_RESTART_AUTONEGOTIATION ((uint16_t)0x0200) /*!< Restart auto-negotiation function */ 135. #define PHY_POWERDOWN ((uint16_t)0x0800) /*!< Select the power down mode */ 136. #define PHY_ISOLATE ((uint16_t)0x0400) /*!< Isolate PHY from MII */ 137. 138. #define PHY_AUTONEGO_COMPLETE ((uint16_t)0x0020) /*!< Auto-Negotiation process completed */ 139. #define PHY_LINKED_STATUS ((uint16_t)0x0004) /*!< Valid link established */ 140. #define PHY_JABBER_DETECTION ((uint16_t)0x0002) /*!< Jabber condition detected */ 141. 142. /* Section 4: Extended PHY Registers */ 143. 144. #define PHY_SR ((uint16_t)0x10) /*!< PHY status register Offset */ 145. #define PHY_MICR ((uint16_t)0x11) /*!< MII Interrupt Control Register */ 146. #define PHY_MISR ((uint16_t)0x12) /*!< MII Interrupt Status and Misc. Control Register */ 147. 148. #define PHY_LINK_STATUS ((uint16_t)0x0001) /*!< PHY Link mask */ 149. #define PHY_SPEED_STATUS ((uint16_t)0x0002) /*!< PHY Speed mask */ 150. #define PHY_DUPLEX_STATUS ((uint16_t)0x0004) /*!< PHY Duplex mask */ 151. 152. #define PHY_MICR_INT_EN ((uint16_t)0x0002) /*!< PHY Enable interrupts */ 153. #define PHY_MICR_INT_OE ((uint16_t)0x0001) /*!< PHY Enable output interrupt events */ 154. 155. #define PHY_MISR_LINK_INT_EN ((uint16_t)0x0020) /*!< Enable Interrupt on change of link status */ 156. #define PHY_LINK_INTERRUPT ((uint16_t)0x2000) /*!< PHY link status interrupt mask */ 157. 158. /* ################## SPI peripheral configuration ########################## */ 159. 160. /* CRC FEATURE: Use to activate CRC feature inside HAL SPI Driver 161. * Activated: CRC code is present inside driver 162. * Deactivated: CRC code cleaned from driver 163. */ 164. 165. #define USE_SPI_CRC 1U 166. 167. /* Includes ------------------------------------------------------------------*/ 168. /** 169. * @brief Include module's header file 170. */ 171. 172. #ifdef HAL_RCC_MODULE_ENABLED 173. #include "stm32f4xx_hal_rcc.h" 174. #endif /* HAL_RCC_MODULE_ENABLED */ 175. 176. #ifdef HAL_GPIO_MODULE_ENABLED 177. #include "stm32f4xx_hal_gpio.h" 178. #endif /* HAL_GPIO_MODULE_ENABLED */ 179. 180. /* 省略未寫 */ 181. 182. #ifdef HAL_HCD_MODULE_ENABLED 183. #include "stm32f4xx_hal_hcd.h" 184. #endif /* HAL_HCD_MODULE_ENABLED */ 185. 186. /* Exported macro ------------------------------------------------------------*/ 187. #ifdef USE_FULL_ASSERT 188. /** 189. * @brief The assert_param macro is used for function's parameters check. 190. * @param expr: If expr is false, it calls assert_failed function 191. * which reports the name of the source file and the source 192. * line number of the call that failed. 193. * If expr is true, it returns no value. 194. * @retval None 195. */ 196. #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) 197. /* Exported functions ------------------------------------------------------- */ 198. void assert_failed(uint8_t* file, uint32_t line); 199. #else 200. #define assert_param(expr) ((void)0U) 201. #endif /* USE_FULL_ASSERT */
除了HSE_VALUE,下面幾個也要作為了解:
- 第71行,滴答定時器的優先級設置。這個優先級的設置至關重要。因為HAL庫中各個外設驅動里面的延遲實現是基於此文件提供的時間基准。
如果在中斷服務程序里面調用基於此時間基准的延遲函數HAL_Delay要特別注意,因為這個函數的時間基准是基於滴答定時器或者其他通用定時器實現,實現方式是滴答定時器或者其他通用定時器里面對變量計數。如此以來,結果是顯而易見的,如果其他中斷服務程序調用了此函數,且中斷優先級高於滴答定時器,會導致滴答定時器中斷服務程序一直得不到執行,從而卡死在里面。所以滴答定時器的中斷優先級一定要比他們高。
另外這個時間基准既可以使用滴答定時器實現也可以使用通用的定時器實現,默認情況下是用的滴答定時器。
- 第72行,當前HAL庫還不支持RTOS方式。
- 第187行,用於使能斷言功能,在HAL庫的API里面都有用到,用來判斷函數形參是否有效。默認情況下是關閉的。
- 第198行,使能斷言功能后,實際對應的代碼位置。這里沒有對函數
void assert_failed(uint8_t* file, uint32_t line)做具體實現,大家可以根據自己的需求去實現,這里提供一個參考:
/* ST庫函數使用了C編譯器的斷言功能,如果定義了USE_FULL_ASSERT,那么所有的ST庫函數將檢查函數形參 是否正確。如果不正確將調用 assert_failed() 函數,這個函數是一個死循環,便於用戶檢查代碼。 關鍵字 __LINE__ 表示源代碼行號。 關鍵字__FILE__表示源代碼文件名。 斷言功能使能后將增大代碼大小,推薦用戶僅在調試時使能,在正式發布軟件是禁止。 用戶可以選擇是否使能ST固件庫的斷言供能。使能斷言的方法有兩種: (1) 在C編譯器的預定義宏選項中定義USE_FULL_ASSERT。 (2) 在本文件取消"#define USE_FULL_ASSERT 1"行的注釋。 */ /* ********************************************************************************************************* * 函 數 名: assert_failed * 形 參:file : 源代碼文件名稱。關鍵字__FILE__表示源代碼文件名。 * line :代碼行號。關鍵字 __LINE__ 表示源代碼行號 * 返 回 值: 無 ********************************************************************************************************* */ void assert_failed(uint8_t* file, uint32_t line) { /* 用戶可以添加自己的代碼報告源代碼文件名和代碼行號,比如將錯誤文件和行號打印到串口 printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ */ /* 這是一個死循環,斷言失敗時程序會在此處死機,以便於用戶查錯 */ while (1) { } }
12.3 HAL庫的時間基准
為了方便各種外設延遲的實現,HAL庫專門搞了一個時間基准,默認來源是滴答定時器,也可以通過重定向使用其他定時器實現。相關函數全部集中在stm32f4xx_hal.c文件里面實現,關於這些函數在本教程的第16章有詳細講解。
12.4 HAL庫的啟動流程
這里通過V6板子初始化流程做個說明:
1. /* 2. ****************************************************************************************************** 3. * 函 數 名: bsp_Init 4. * 功能說明: 初始化所有的硬件設備。該函數配置CPU寄存器和外設的寄存器並初始化一些全局變量。 5. * 只需要調用一次 6. * 形 參:無 7. * 返 回 值: 無 8. ****************************************************************************************************** 9. */ 10. void bsp_Init(void) 11. { 12. /* 13. STM32H429 HAL 庫初始化,此時系統用的還是F429自帶的16MHz,HSI時鍾: 14. - 調用函數HAL_InitTick,初始化滴答時鍾中斷1ms。 15. - 設置NVIV優先級分組為4。 16. */ 17. HAL_Init(); 18. 19. /* 20. 配置系統時鍾到168MHz 21. - 切換使用HSE。 22. - 此函數會更新全局變量SystemCoreClock,並重新配置HAL_InitTick。 23. */ 24. SystemClock_Config(); 25. 26. /* 27. Event Recorder: 28. - 可用於代碼執行時間測量,MDK5.25及其以上版本才支持,IAR不支持。 29. - 默認不開啟,如果要使能此選項,務必看V6開發板用戶手冊第8章 30. */ 31. #if Enable_EventRecorder == 1 32. /* 初始化EventRecorder並開啟 */ 33. EventRecorderInitialize(EventRecordAll, 1U); 34. EventRecorderStart(); 35. #endif 36. 37. bsp_InitKey(); /* 按鍵初始化,要放在滴答定時器之前,因為按鈕檢測是通過滴答定時器掃描 */ 38. bsp_InitTimer(); /* 初始化滴答定時器 */ 39. bsp_InitUart(); /* 初始化串口 */ 40. bsp_InitLed(); /* 初始化LED */ 41. }
- 第17行,調用函數HAL_Init時,系統依然使用的16MHz HSI時鍾,這點要特別注意。此函數會調用函數HAL_InitTick,初始化滴答時鍾中斷1ms,並設置NVIV優先級分組為4。
這里就隱含了一個知識點,就是它會開啟滴答定時器中斷,如果用戶也要使用滴答定時器中斷,此問題就要引起注意,我們的bsp_timer.C文件解決辦法如下:
/* ********************************************************************************************************* * 函 數 名: SysTick_Handler * 功能說明: 系統嘀嗒定時器中斷服務程序。啟動文件中引用了該函數。 * 形 參: 無 * 返 回 值: 無 ********************************************************************************************************* */ void SysTick_Handler(void) { HAL_IncTick(); /* ST HAL庫的滴答定時中斷服務程序 */ if (g_ucEnableSystickISR == 0) /* 做了一個變量標志,調用了函數bsp_InitTimer才置位此變量 */ { return; } SysTick_ISR(); /* 安富萊bsp庫的滴答定時中斷服務程序 */ }
- 第30行,通過此函數切換HSI到外部高速時鍾HSE,並配置系統時鍾到168MHz。調用這個函數會更新全局變量SystemCoreClock,並重新配置HAL_InitTick。
- 前面幾步執行完畢后就可以初始化外設了。
12.5 HAL庫初始化外設
HAL庫為外設初始化提供了一套框架,這里以串口為例進行說明,調用函數HAL_UART_Init初始化串口,此函數就會調用HAL_UART_MspInit,這個函數是弱定義的,在stm32f4xx_hal_uart.c文件里面:
/** * @brief Initialize the UART MSP. * @param huart: UART handle. * @retval None */ __weak void HAL_UART_MspInit(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_UART_MspInit can be implemented in the user file */ }
如果要初始化,直接將此函數在其它源文件里面實現即可,如果用到了中斷和DMA,也是直接在這里填寫。
void HAL_UART_MspInit(UART_HandleTypeDef* huart) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(huart->Instance==USART1) { __HAL_RCC_USART1_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); GPIO_InitStruct.Pin = GPIO_PIN_7; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; GPIO_InitStruct.Alternate = GPIO_AF7_USART1; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_14; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; GPIO_InitStruct.Alternate = GPIO_AF4_USART1; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); } else if(huart->Instance==USART2) { __HAL_RCC_USART2_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitStruct.Pin = GPIO_PIN_6; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; GPIO_InitStruct.Alternate = GPIO_AF7_USART2; HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_2; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; GPIO_InitStruct.Alternate = GPIO_AF7_USART2; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); } }
由於所有串口都是通過函數HAL_UART_Init做初始化,所以函數HAL_UART_MspInit也是共用的。因此需要大家在這個里面區分是配置的哪個串口。
12.6 HAL庫的中斷處理思路
為了加強對中斷的管理,HAL庫也為各種外設中斷也配套一個函數,比如串口就是函數HAL_UART_IRQHandler。
void USART1_IRQHandler(void) { /* USER CODE BEGIN USART1_IRQn 0 */ 此處可以添加用戶代碼 /* USER CODE END USART1_IRQn 0 */ /* 參數是串口句柄 */ HAL_UART_IRQHandler(&huart1); /* USER CODE BEGIN USART1_IRQn 1 */ 此處可以添加用戶代碼 /* USER CODE END USART1_IRQn 1 */ }
那么問題來了,如果要實現功能,用戶的應用程序怎么寫入中斷?用戶可以直接在函數HAL_UART_IRQHandler的前面或者后面添加新代碼,也可以直接在HAL_UART_IRQHandler調用的各種回調函數里面執行,這些回調都是弱定義的,方便用戶直接在其它文件里面重定義(下面回調主要是用於串口DMA時調用的):
HAL_UART_TxHalfCpltCallback()
HAL_UART_TxCpltCallback()
HAL_UART_RxHalfCpltCallback()
HAL_UART_RxCpltCallback()
HAL_UART_ErrorCallback()
12.7 HAL庫的DMA處理思路
為了方便各種外設直接啟動DMA,HAL庫專門為支持DMA操作的外設都提供了對應的DMA函數,比如串口的:
HAL_UART_Transmit_DMA()
HAL_UART_Receive_DMA()
HAL_UART_DMAPause()
HAL_UART_DMAResume()
HAL_UART_DMAStop()
這里特別注意一點,針對外設的DMA函數基本都有開啟中斷,如果用戶使能此外設的NVIC,使用中務必別忘了寫DMA的中斷服務程序,比如使用DMA1_Stream1:
void DMA1_Stream1_IRQHandler(void) { /* USER CODE BEGIN USART1_IRQn 0 */ 此處可以添加用戶代碼 /* USER CODE END USART1_IRQn 0 */ /* 參數是DMA句柄 */ HAL_DMA_IRQHandler(&hdma_usart1_tx); /* USER CODE BEGIN USART1_IRQn 1 */ 此處可以添加用戶代碼 /* USER CODE END USART1_IRQn 1 */ }
如果要在DMA傳輸完成,半傳輸完成等中斷里面執行功能,也是通過HAL_DMA_IRQHandler調用的各種回調函數里面實現,這些回調都是弱定義的,方便用戶直接在其它文件里面重定義:
HAL_UART_TxHalfCpltCallback()
HAL_UART_TxCpltCallback()
HAL_UART_RxHalfCpltCallback()
HAL_UART_RxCpltCallback()
12.8 總結
先從整體框架上把握HAL庫,然后具體外設具體學習,后面做應用會得心應手些。