文章主要参考了 https://blog.csdn.net/qq_42810361/article/details/106570373
Cubemx的配置
跳过基本的配置 1USART1 配置 中断配置 其他默认配置不改变
代码块
usart.c 这里要添加头文件#include<string.h>
ts_usart_type usart_nb_type;
void hal_uart_recv_init(void)
{
__HAL_UART_ENABLE_IT(&huart1 ,UART_IT_IDLE );
HAL_UART_Receive_DMA(&huart1 ,usart_nb_type.usart_dma_recv_buffer, USART_DMA_RECV_SIZE);
}
void hal_uart_irq_prejudge(void)
{
uint32_t temp;
if(__HAL_UART_GET_FLAG(&huart1 , UART_FLAG_IDLE) != RESET)
{
__HAL_UART_CLEAR_IDLEFLAG(&huart1);
HAL_UART_DMAStop(&huart1);
temp = huart1.Instance->ICR;
temp = huart1.Instance->RDR;
temp = USART_DMA_RECV_SIZE -__HAL_DMA_GET_COUNTER(&hdma_usart1_rx);
usart_nb_type.usart_dma_recv_len = temp;
HAL_UART_RxCpltCallback(&huart1);
}
}
void hal_uart_recv_judge(void)
{
if(usart_nb_type.usart_recv_flag == 1)
{
HAL_UART_Transmit(&huart1 ,usart_nb_type.usart_recv_buffer ,usart_nb_type.usart_recv_len ,100 );
memset(usart_nb_type.usart_recv_buffer ,0 ,usart_nb_type.usart_recv_len);
usart_nb_type.usart_recv_flag = 0;
usart_nb_type.usart_recv_len = 0;
}
}
usart.h
#define USART_DMA_RECV_SIZE 256
#define USART_RECV_SIZE 1024
typedef struct
{
uint8_t usart_recv_flag;
uint16_t usart_recv_len;
uint16_t usart_dma_recv_len;
uint8_t usart_recv_buffer [USART_RECV_SIZE];
uint8_t usart_dma_recv_buffer [USART_DMA_RECV_SIZE];
}ts_usart_type;
extern ts_usart_type usart_nb_type;
void hal_uart_recv_judge(void);
void hal_uart_recv_init(void);
void hal_uart_irq_prejudge(void);
stm32g4xx_it.c中 添加usart.h头文件
void USART1_IRQHandler(void)
{
hal_uart_irq_prejudge();
HAL_UART_IRQHandler(&huart1);
HAL_UART_Receive_DMA(&huart1 ,usart_nb_type.usart_dma_recv_buffer ,USART_DMA_RECV_SIZE);
}
修改这个处理函数
main.c 中 添加头文件string.h
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance == huart1.Instance)
{
if(usart_nb_type.usart_recv_len > 0)
{
memcpy(&usart_nb_type.usart_recv_buffer[usart_nb_type.usart_recv_len] ,usart_nb_type.usart_dma_recv_buffer ,usart_nb_type.usart_dma_recv_len);
usart_nb_type.usart_recv_len += usart_nb_type.usart_dma_recv_len;
}
else
{
memcpy(usart_nb_type.usart_recv_buffer ,usart_nb_type.usart_dma_recv_buffer ,usart_nb_type.usart_dma_recv_len);
usart_nb_type.usart_recv_len = usart_nb_type.usart_dma_recv_len;
}
memset(usart_nb_type.usart_dma_recv_buffer ,0 ,usart_nb_type.usart_dma_recv_len);
usart_nb_type.usart_dma_recv_len = 0;
usart_nb_type.usart_recv_flag = 1;
hal_uart_recv_judge();
}
}
在while(1)之前初始化
hal_uart_recv_init();
while (1)
结果
|