STM32学习笔记(7):USART串口的使用
始化
void USART_cfg()
{
USART_InitTypeDef USART_InitStructure;
//将结构体设置为缺省状态
USART_StructInit(&USART_InitStructure);
//波特率设置为115200
USART_InitStructure.USART_BaudRate = 115200;
//一帧数据的宽度设置为8bits
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
//在帧结尾传输1个停止位
USART_InitStructure.USART_StopBits = USART_StopBits_1;
//奇偶失能模式,无奇偶校验
USART_InitStructure.USART_Parity = USART_Parity_No;
//发送/接收使能
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
//硬件流控制失能
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
//设置串口1
USART_Init(USART1, &USART_InitStructure);
//打开串口1的中断响应函数
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
//打开串口1
USART_Cmd(USART1, ENABLE);
}
//配置中断
void NVIC_cfg()
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //选择中断分组2
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQChannel; //选择串口1中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //抢占式中断优先级设置为0
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //响应式中断优先级设置为0
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //使能中断
NVIC_Init(&NVIC_InitStructure);
}
然后在stm32f10x_it.c文件中找到相应的中断处理函数,并填入一下内容。注意在stm32f10x_it.c中,要声明一下外部变量RX_status
extern FlagStatus RX_status;
void USART1_IRQHandler(void)
{
GPIO_SetBits(GPIOB, GPIO_Pin_5);
//确认是否接收到数据
RX_status = USART_GetFlagStatus(USART1, USART_FLAG_RXNE);
//接收到数据
if(RX_status == SET)
{
//将数据回送至超级终端
USART_SendData(USART1, USART_ReceiveData(USART1));
//等待数据发送完毕
while(USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
GPIO_ResetBits(GPIOB, GPIO_Pin_5);
}
}
STM32学习笔记USART串 相关文章:
- Windows CE 进程、线程和内存管理(11-09)
- RedHatLinux新手入门教程(5)(11-12)
- uClinux介绍(11-09)
- openwebmailV1.60安装教学(11-12)
- Linux嵌入式系统开发平台选型探讨(11-09)
- Windows CE 进程、线程和内存管理(二)(11-09)