串口收发(完结)

发布于 2024-03-29  175 次阅读


cubemx配置

使能中断

#include "stm32g4xx.h"                  // Device header
#include "usart.h"
#include "string.h"

char receive[20];//接收结果
uint8_t rx;
uint8_t pointer;
//指针

void Send_Data(char *Data)
{
	HAL_UART_Transmit(&huart1,(uint8_t *)Data,strlen(Data),50);//50:发送延迟
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)//回调函数stm32g4xx_hal_uart.h中可找到
{
	receive[pointer++] = rx;
	HAL_UART_Receive_IT(&huart1,&rx,1);//1:只能读一位
}
/*main.c中开启串口中断*/
	HAL_UART_Receive_IT(&huart1,&rx,1);

例:

extern  char receive[20];
extern uint8_t rx;
extern uint8_t pointer;

void Uart_Proc(void)
{
	if(pointer > 0)
	{
		char text[30];	
		sprintf(text, "      Receive:%s",receive);
		LCD_DisplayStringLine(Line6, (uint8_t *)text);
		pointer = 0;
		memset(receive,0,sizeof receive);//接收后清空接收字符串
	}
	
}
最后更新于 2024-03-29