微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > STM32学习笔记(7):USART串口的使用

STM32学习笔记(7):USART串口的使用

时间:11-25 来源:互联网 点击:

始化

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);

}

}

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top