CUBE里配置成异步模式,设置波特率,打开中断(先配置LCD再配置串口):
串口发送
main.c
#include "string.h"
char temp[20];
sprintf(temp,"Hello World\r\n");
HAL_UART_Transmit(&huart1,(uint8_t *)temp,strlen(temp),50);
串口接收
interrupt.c
#include "usart.h"
char rxdata[30];
uint8_t rxdat;
uint8_t rx_index;
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
rxdata[rx_index++] = rxdat;
HAL_UART_Receive_IT(&huart1, &rxdat, 1);
}
main.c
extern char rxdata[30];
extern uint8_t rxdat;
extern uint8_t rx_index;
char car_type[5];
char car_data[5];
char car_time[13];
注:sscanf()里的1s不能去掉,1代表数据的长度为1
void Uart_RX_Pro(void)
{
if(rx_index > 0)
{
if(rx_index == 5)
{
sscanf(rxdata,"%1s:%1s:%1s",car_type,car_data,car_time);//1s中的1不能去掉,因为此处演示的数为1:2:3
}
else
{
char temp[20];
sprintf(temp,"Error");
HAL_UART_Transmit(&huart1,(uint8_t *)temp,strlen(temp),50);
}
rx_index = 0;
memset(rxdata,0,30);
}
}
HAL_UART_Receive_IT(&huart1, &rxdat, 1);//初始化运行时需要进去一次
if(rx_index > 0)
{
int temp = rx_index;
HAL_Delay(1);
if(temp == rx_index)
Uart_RX_Pro();
}
char text[30];
sprintf(text,"car_type = %s ",car_type);
LCD_DisplayStringLine(Line0, (u8 *)text);
sprintf(text,"car_dat = %s ",car_data);
LCD_DisplayStringLine(Line4, (u8 *)text);
sprintf(text,"car_time = %s ",car_time);
LCD_DisplayStringLine(Line9, (u8 *)text);
串口接收最终实现功能:串口发送a:b:c时屏幕会显示对应的数字,若不是这5个字符串口则会接收到Error。