Use a jumper cap to connect PA9 to RXD, and PA10 to TXD.
software design
void uart_init(u32 baud)
{
//UART 初始化设置
UART1_Handler.Instance=USART1; //USART1
UART1_Handler.Init.BaudRate=bound; //波特率
UART1_Handler.Init.WordLength=UART_WORDLENGTH_8B; //字长为 8 位数据格式
UART1_Handler.Init.StopBits=UART_STOPBITS_1; //一个停止位
UART1_Handler.Init.Parity=UART_PARITY_NONE; //无奇偶校验位
UART1_Handler.Init.HwFlowCtl=UART_HWCONTROL_NONE; //无硬件流控
UART1_Handler.Init.Mode=UART_MODE_TX_RX; //收发模式
HAL_UART_Init(&UART1_Handler);
HAL_UART_Receive_IT(&UART1_Handler, (u8 *)aRxBuffer, RXBUFFERSIZE);
}
HAL_UART_MspInit() is defined;
//GPIO 端口设置
GPIO_InitTypeDef GPIO_Initure;
if(huart->Instance==USART1) //如果是串口 1,进行串口 1 MSP 初始化
{
__HAL_RCC_GPIOA_CLK_ENABLE(); //使能 GPIOA 时钟
__HAL_RCC_USART1_CLK_ENABLE(); //使能 USART1 时钟
__HAL_RCC_AFIO_CLK_ENABLE();
GPIO_Initure.Pin=GPIO_PIN_9; //PA9
GPIO_Initure.Mode=GPIO_MODE_AF_PP; //复用推挽输出
GPIO_Initure.Pull=GPIO_PULLUP; //上拉
GPIO_Initure.Speed=GPIO_SPEED_FREQ_HIGH; //高速
HAL_GPIO_Init(GPIOA,&GPIO_Initure); //初始化 PA9
GPIO_Initure.Pin=GPIO_PIN_10; //PA10
GPIO_Initure.Mode=GPIO_MODE_AF_INPUT;//模式要设置为复用输入模式!
HAL_GPIO_Init(GPIOA,&GPIO_Initure); //初始化 PA10
#if EN_USART1_RX
HAL_NVIC_EnableIRQ(USART1_IRQn);
HAL_NVIC_SetPrioority(USART1_IRQn,3,3);//抢占优先级3,子优先级3
#endif
Write interrupt service function
void USART1_IRQHandler(void)
{
HAL_UART_IRQHandler(&UART1_Handler);
}
void HAL_UART_IRQHandler(UART_HandleTypeDef *huart)
{
uint32_t isrflags = READ_REG(huart->Instance->SR);
uint32_t cr1its = READ_REG(huart->Instance->CR1);
uint32_t cr3its = READ_REG(huart->Instance->CR3);
uint32_t errorflags = 0x00U;
uint32_t dmarequest = 0x00U;
errorflags = (isrflags & (uint32_t)(USART_SR_PE | USART_SR_FE |
USART_SR_ORE | USART_SR_NE));
if (errorflags == RESET)
{
if (((isrflags & USART_SR_RXNE) != RESET) &&
((cr1its & USART_CR1_RXNEIE) != RESET))
{
UART_Receive_IT(huart);
return;
}
}
…//此处省略部分代码
}
In the function HAL_UART_IRQHandler, by judging whether the interrupt type is a receive completion interrupt, determine whether to call another HAL function UART_Receive_IT().
The function of the function UART_Receive_IT() is to store the characters received by each interrupt in the cache pointer pRxBuffPtr of the serial port handle, and at the same time, each time a character is received, the counter RxXferCount will be decremented by 1 until RxXferSize characters are received and RxXferCount is set to 0. At the same time call the receiving completion callback function HAL_UART_RxCpltCallback for processing.