USART简介
USART即为通用同步异步收发器,简单而言就是单片机用来和外部设备进行串行通信的工具,这种利用USART进行的通信的方式就是我们常说的串口通信。串口通信是利用串行通信协议在计算机与外部设备之间进行异步通信的一种技术。
提示:串行通信是按照时间顺序,按位依次发送通信字节的通信方式。
代码流程
#include "stm32f10x.h" // Device header
void Serial_Init(void){
RCC_APB2PeriphClockCmd (RCC_APB2Periph_USART1,ENABLE);//开启外设时钟
RCC_APB2PeriphClockCmd (RCC_APB2Periph_GPIOA,ENABLE);//开启GPIO时钟
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //配置PA9成复用推挽输出,供TX使用
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 9600;;//波特率位9600
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件控制流
USART_InitStructure.USART_Mode = USART_Mode_Tx;//只发送
USART_InitStructure.USART_Parity = USART_Parity_No;//无校验位
USART_InitStructure.USART_StopBits = USART_StopBits_1;//1个停止位
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_Init(USART1,&USART_InitStructure);//初始化串口配置
USART_Cmd(USART1,ENABLE);//开启USART1
}
添加头文件,接下来进行功能的初始化配置。开启时钟,配置要用到的GPIO引脚,配置要用到USART1,最后使能USART1,这样就开启串口通信功能了。
发送单个字节的数据
编写一个发送单个字节的函数,用作发送数据的基本函数
void Serial_SendByte(uint8_t Byte){