1.配置串口IO、中斷等底層的東西需要在用戶文件中重寫HAL_UART_MspInit函數
2.hal庫是在stm32f4xx_hal_msp.c文件中重寫的HAL_UART_MspInit函數,分析如下:
stm32f4xx_hal_msp.c通過間接方式最終包含了stm32f4xx_hal_uart.h,包含關系如下:
stm32f4xx_hal_msp.c
-->#include "main.h"
-->#include "stm32f4xx_hal.h"
-->#include "stm32f4xx_hal_conf.h"
-->#define HAL_UART_MODULE_ENABLED //是否使用串口模塊的開關,打開開關則包含頭文件 #include "stm32f4xx_hal_uart.h"
3.stm32f4xx_hal_uart.h頭文件中有HAL_UART_MspInit函數的聲明
-->void HAL_UART_MspInit(UART_HandleTypeDef *huart);//定義在stm32f4xx_hal_uart.h頭文件中
4.stm32f4xx_hal_uart.c源文件中有HAL_UART_MspInit的弱實現
-->__weak修飾的函數其作用是將當前文件的對應函數聲明為弱函數符號,如果外部文件出現相同的函數名,最終編譯出來的
文件會優先指向外部文件的函數符號;因此HAL_UART_MspInit函數實現了重寫。
/**
* @brief UART MSP Init.
* @param huart Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @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 could be implemented in the user file
*/
}
4.重寫后的函數
1 /** 2 * @brief UART MSP Initialization 3 * This function configures the hardware resources used in this example: 4 * - Peripheral's clock enable 5 * - Peripheral's GPIO Configuration 6 * @param huart: UART handle pointer 7 * @retval None 8 */ 9 void HAL_UART_MspInit(UART_HandleTypeDef *huart) 10 { 11 GPIO_InitTypeDef GPIO_InitStruct; 12 13 /*##-1- Enable peripherals and GPIO Clocks #################################*/ 14 /* Enable GPIO TX/RX clock */ 15 USARTx_TX_GPIO_CLK_ENABLE(); 16 USARTx_RX_GPIO_CLK_ENABLE(); 17 /* Enable USART2 clock */ 18 USARTx_CLK_ENABLE(); 19 20 /*##-2- Configure peripheral GPIO ##########################################*/ 21 /* UART TX GPIO pin configuration */ 22 GPIO_InitStruct.Pin = USARTx_TX_PIN; 23 GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; 24 GPIO_InitStruct.Pull = GPIO_NOPULL; 25 GPIO_InitStruct.Speed = GPIO_SPEED_FAST; 26 GPIO_InitStruct.Alternate = USARTx_TX_AF; 27 28 HAL_GPIO_Init(USARTx_TX_GPIO_PORT, &GPIO_InitStruct); 29 30 /* UART RX GPIO pin configuration */ 31 GPIO_InitStruct.Pin = USARTx_RX_PIN; 32 GPIO_InitStruct.Alternate = USARTx_RX_AF; 33 34 HAL_GPIO_Init(USARTx_RX_GPIO_PORT, &GPIO_InitStruct); 35 }
