main
#include "stdio.h"
#include "string.h"
#include <stdarg.h>
uint8_t rx_buff[BUFF_SIZE]; // 定义array
volatile uint8_t rx_len = 0; // 接收到的数据长度
volatile uint8_t recv_end_flag = 0; // 接收完成标志
//初始化完成之后
HAL_UARTEx_ReceiveToIdle_DMA(&huart1,rx_buffer,BUF_SIZE);
开启DMA传输
串口中断函数
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 */
HAL_UARTEx_ReceiveToIdle_DMA(&huart1,rx_buffer,BUF_SIZE);
/* USER CODE END USART1_IRQn 1 */
}
UART接收事件回调函数
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
if (huart == &huart3)
{
if (Size < BUFF_SIZE)
{
Size = BUF_SIZE - __HAL_DMA_GET_COUNTER(&hdma_usart1_rx);
HAL_UART_Transmit(&huart1, rx_buffer, Size, 0xffff); //将接受到的数据再发回上位机
memset(rx_buffer, 0, Size);
}
//放在void USART1_IRQHandler(void)函数里,不要放在这
//HAL_UARTEx_ReceiveToIdle_DMA(&huart1,rx_buffer,BUF_SIZE);不要放在这里,如果放在这里,不仅上位机的波特率改变不能正常接收,就算改回去了也会接收不了
}
}
UART错误回调函数
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
if (huart == &huart3)
{
HAL_UARTEx_ReceiveToIdle_DMA(&huart3, rx_buff, BUFF_SIZE); // 接收发生错误后重启
memset(rx_buff, 0, BUFF_SIZE);
}
}