具体看下面完整的初始化代码:
//配置串口1
void USART1_Config()
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_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);
//配置接收引脚
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
//接收引脚设置为浮空输入
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//波特率
USART_InitStructure.USART_BaudRate = 9600;
//数据长度
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
//停止位
USART_InitStructure.USART_StopBits = USART_StopBits_1;
//校验位
USART_InitStructure.USART_Parity = USART_Parity_No;
//流控制
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
//打开发送和接收模式
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
//初始化串口1
USART_Init(USART1, &USART_InitStructure);
//USART1->SR寄存器复位后TC位为1,在此清零
USART_ClearFlag(USART1, USART_FLAG_TC);
//串口1使能
USART_Cmd(USART1, ENABLE);
//使能后串口发送一个空闲帧,等待空闲帧发送完毕后将TC标记位清零
while(USART_GetFlagStatus(USART1, USART_FLAG_TC) != SET);
//否则开启TC中断后会马上中断
USART_ClearFlag(USART1, USART_FLAG_TC);
//配置中断优先级
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/***************************************************************
注意:初始化时不要随意打开TXE中断,
因为只要TX-DR寄存器为空,TX和TXE都会马上被置位而立即会产生中断
***************************************************************/
//清除接收中断标记
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
//清除发送完成中断标记
USART_ClearITPendingBit(USART1, USART_IT_TC);
//打开串口1发送完中断
USART_ITConfig(USART1, USART_IT_TC, ENABLE);
//打开串口1接收中断 两个中断不能在一个函数中同时打开!!!太坑了T_T
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
}
|
———————————————— 版权声明:本文为CSDN博主「培培哥」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/u014695839/article/details/62037269