串口概述
一个串口数据帧有起始位、可配置长度的停止位、可选择的校验位,以及有效载荷部分。可配置为8位或9位字长(包括校验位)。串口是异步的通信协议需要通信双方约定好通信速率(波特率),发送方按照通信速率生成波形,接收方按照速率对波形采样。
使用stm32串口外设,开启时钟初始化好之后,直接读写发送接收寄存器就可以实现数据的发送和接收了(USART外设自动完成)。读写寄存器是有时机的,需要等待发送接收寄存器空和非空的标志位。
USART外设简介
USART外设基本结构
USART框图
数据帧
USART初始化结构体成员变量
typedef struct
{
uint32_t USART_BaudRate; //波特率
uint16_t USART_WordLength; //字长8b9b
uint16_t USART_StopBits; //停止位长度
uint16_t USART_Parity; //校验位
uint16_t USART_Mode; //发送接收模式选择
uint16_t USART_HardwareFlowControl; //硬件流控
} USART_InitTypeDef;
串口发送+接收代码
#include "stm32f10x.h" // Device header
#include <stdio.h>
#include <stdarg.h>
uint8_t Serial_RxData;
uint8_t Serial_RxFlag;
void Serial_Init(void)
{
//1.开启时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
//2.GPIO初始化
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//3.USART初始化
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_Init(USART1, &USART_InitStructure);
//4.中断输出控制,开启USART_IT_RXNE中断
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
//5.配置NVIC
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_Init(&NVIC_InitStructure);
//6.启动串口
USART_Cmd(USART1, ENABLE);
}
//7.等待TXE、RXNE标志位、读写发送接收数据寄存器
void Serial_SendByte(uint8_t Byte)
{
USART_SendData(USART1, Byte);
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}
uint8_t Serial_GetRxFlag(void)
{
if (Serial_RxFlag == 1)
{
Serial_RxFlag = 0;
return 1;
}
return 0;
}
uint8_t Serial_GetRxData(void)
{
return Serial_RxData;
}
void USART1_IRQHandler(void)
{
if (USART_GetITStatus(USART1, USART_IT_RXNE) == SET)
{
Serial_RxData = USART_ReceiveData(USART1);
Serial_RxFlag = 1;
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
}
}