串口配置好即配置好GPIO和NVIC并初始化相应外设,然后每接受一个data就触发一次中断,转到中断入口处处理,然后清除中断标志位。一般情况下只有接受的时候采用中断方式,而发送只是放到buff寄存器里,不需要中断方式。以下是以前学习的时候串口通讯点灯的代码:
#include "usart.h"
void usart_config(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA
| RCC_APB2Periph_AFIO,ENABLE);
usart_release_gpio_init();
usart_nvic_init();
usart_para_init();
}
void usart_release_gpio_init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStruct);//配置好的参数初始化PA9
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStruct);//配置好的参数初始化PA10
}
void usart_para_init(void)
{
USART_InitTypeDef USART_InitStruct;
USART_InitStruct.USART_BaudRate = 9600; //波特率9600
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None; //无硬件流控
USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_InitStruct.USART_WordLength = USART_WordLength_8b; //8
USART_InitStruct.USART_Parity = USART_Parity_No; //n
USART_InitStruct.USART_StopBits = USART_StopBits_1; //1
USART_Init(USART1,&USART_InitStruct);//配置好的参数初始化USART1
USART_ClearFlag(USART1,USART_FLAG_TC);//清除发送完成标志位
USART_Cmd(USART1, ENABLE); //使能USART1
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//使能USART1接收中断
}
void usart_nvic_init(void)
{
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); //设置组优先级
NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn; //设置串口1中断
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0; //抢占优先级0
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0; //子优先级0
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE; //使能
NVIC_Init(&NVIC_InitStruct);//配置好的参数初始化NVIC
}
void USART1_IRQHandler ()
{
u8 RxData;
if(USART_GetFlagStatus(USART1, USART_IT_RXNE) != RESET) //判断是否有中断
{
RxData = USART_ReceiveData(USART1);
if(RxData == 0x00 )
{
GPIO_SetBits(GPIOB, GPIO_Pin_15);
}
else
{
GPIO_ResetBits(GPIOB, GPIO_Pin_15);
}
}
USART_ClearITPendingBit(USART1,USART_IT_RXNE); //清除接收终端标志位
}
免责声明:本平台仅供信息发布交流之途,请谨慎判断信息真伪。如遇虚假诈骗信息,请立即举报
举报