简单说明:
1、RCC开启时钟
2、GPIO口配置
3、串口配置
4、使能串口
基础配置
void USART1_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd( RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //选择对应的引脚
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure); //初始化PC端口
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; //选择对应的引脚
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure); //初始化PC端口
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx|USART_Mode_Tx;
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);
USART_Cmd( USART1, ENABLE);
}
简单说明:重点认识
USART_SendData:发送数据
USART_GetFlagStatus:检查标志位设置
USART_FLAG_TXE:发送数据寄存器空
0:RESET 数据还没有转移,循环等待
1:SET 已经被转移到移位寄存器
TC一样
发送字符
//发送字符
void USART1_SendData(uint16_t Byte)
{
USART_SendData(USART1, Byte);
//0为数据未转移到移位寄存器,1为数据已经移位
while(USART_GetFlagStatus(USART1, USART_FLAG_TC)==RESET);
}
发送字符串
//发送字符串
void USAR1_SendlongData(unsigned char *Data)
{
int i = 0;
USART_ClearFlag(USART1, USART_FLAG_TC);
while(Data[i] != '\0')
{
USART_SendData(USART1,Data[i]);
while(USART_GetFlagStatus(USART1, USART_FLAG_TC)==RESET);
//USART_ClearFlag(USART1, USART_FLAG_TC);
i++;
}
}
接收一般采用中断处理
重点认识:
USART_FLAG_RXNE:读数据寄存器非空
0:RESET 数据没有收到
1:SET 收到数据,可以读出
USART_ReceiveData:接收到的数据
//单个字符接收中断
//uint8_t temp=0;
void USART1_IRQHandler(void)
{
//0表示无数据,1表示收到数据可以读取
if(USART_GetITStatus(USART1,USART_IT_RXNE)==SET)
{
Rx_Data = USART_ReceiveData(USART1);
temp = 1;
USART_ClearFlag(USART1,USART_FLAG_RXNE);//清除RXNE标志位
}
}
正点原子接收理解:
以下程序结合图来看
bit15-0x0A为最高位,代表接收完成,bit14-为0x0D,bit13-0为数据位。
![](https://img-blog.csdnimg.cn/img_convert/bbe8762d2067cf3c89a1a7f149e5bc14.png)
看到USART_RX_STA & 0x8000 表示最高位0x0A
USART_RX_STA & 0x4000 表示最高位0x0D,就很好理解了
unsigned char USART_BUFF[1024];//接收缓冲区
uint16_t USART_RX_STA=0;//接收标志位
uint8_t USART_LEN = 0;
void USART1_IRQHandler(void)
{
u8 temp;
if(USART_GetITStatus(USART1,USART_IT_RXNE)==SET)//0表示无数据,1表示收到数据可以读取
{
temp = USART_ReceiveData(USART1);
if((USART_RX_STA & 0x8000)==0)//最高位15-0x0A
{
if(USART_RX_STA & 0x4000)//bit14-0x0D 为1 接收标志位为1
{
if(temp != 0x0a)
{
USART_RX_STA = 0; //接收错误,清零
}
else
{
USART_RX_STA |= 0x8000; //接收完成
}
}
else //bit14-0x0D为0,没有接收到
{
if(temp == 0x0d)
{
USART_RX_STA |= 0x4000;//标志位置1
}
else //存储数据
{
USART_BUFF[USART_LEN] = temp;
USART_LEN++;
}
}
}
}
}