1:设置中断分组
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
2:使能用作串口(RX/TX)的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA,ENABLE); //串口时钟和GPIO时钟都需要设置
3:GPIO模式设置
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9; //TX
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; //特别注意
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10; //RX
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING; //特别注意
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStruct);
4:开启并初始化中断控制器
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn; //中断通道
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 3; //优先级
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0; //响应级
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE; //使能
NVIC_Init(&NVIC_InitStruct);
5:串口参数初始化
USART_InitTypeDef USART_InitStruct;
USART_InitStruct.USART_BaudRate = 9600; //波特率
USART_InitStruct.USART_WordLength = USART_WordLength_8b; //长度选择
USART_InitStruct.USART_Mode = USART_Mode_Rx|USART_Mode_Tx; //TX/RX模式
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Parity = USART_Parity_No; //检验位
USART_InitStruct.USART_StopBits = USART_StopBits_1; //停止位
USART_Init(USART1,&USART_InitStruct);
6:使能中断模式(接收模式)
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
7:使能串口
USART_Cmd(USART1,ENABLE);
8:编写中断服务函数
void USART1_IRQHandler(void){
uint16_t ret = 0;
if(USART_GetITStatus(USART1,USART_IT_RXNE) != RESET){ //检查中断是否发生
ret = USART_ReceiveData(USART1); //获取接收数据
USART_SendData(USART1,ret); //发送数据
}
}