串口
串行接口简称串口,也称串行通信接口或串行通讯接口(通常指COM接口),是采用串行通信方式的扩展接口。串行接口 (Serial Interface) 是指数据一位一位地顺序传送,其特点是通信线路简单,只要一对传输线就可以实现双向通信
STM32cube
一、配置
1、新建工程,选择对应开发板
我使用的是STM32F407
2、时钟配置
这里要根据自己对应的开发板去配置
3、配置串口,波特率设置为115200
开启串口中断
4、生成代码
二、修改代码
1、打开生成的代码,编译一遍
2、函数介绍
HAL_UART_Transmit_IT:以中断的方式发送数据
HAL_UART_Receive_IT:开启中断,接收数据
3、修改代码
在主函数添加相关变量
在main函数中初始化变量和开启串口中断
重写接收完成之后中断的回调函数
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(huart);
/* NOTE: This function Should not be modified, when the callback is needed,
the HAL_UART_TxCpltCallback could be implemented in the user file
*/
if(huart->Instance == USART1)
{
if(UART1_Length>254)
{
UART1_Length=0;
HAL_UART_Transmit(&huart1,(uint8_t *)"Too Long!\r\n",11,1000);
memset(UART1_DatBuff,0,255);
}
else
{
UART1_DatBuff[UART1_Length++]=UART1_Dat;
if(UART1_DatBuff[UART1_Length-1]==0x0A&&UART1_DatBuff[UART1_Length-2]==0x0D)
{
HAL_UART_Transmit(&huart1,UART1_DatBuff,UART1_Length,1000);
UART1_Length=0;
memset(UART1_DatBuff,0,255);
}
}
HAL_UART_Receive_IT(&huart1,&UART1_Dat,1);
}
}
三、下载测试
将程序烧入开发板,并打开串口调试助手测试
效果如图