usart.c
#include "usart.h"
void USART1_Init(u32 baud)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
//1*开启串口1时钟和其连接的引脚时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
//2*配置引脚输入输出结构体
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA,&GPIO_InitStructure);
//3*配置串口
USART_InitStructure.USART_BaudRate = baud; //波特率设置
USART_InitStructure.USART_WordLength = USART_WordLength_8b; //字长为8位数据格式
USART_InitStructure.USART_StopBits = USART_StopBits_1;//一个停止位
USART_InitStructure.USART_Mode = USART_Mode_Rx|USART_Mode_Tx; //收发模式
USART_InitStructure.USART_Parity = USART_Parity_No;//无奇偶校验位
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制
USART_Init(USART1,&USART_InitStructure);
//4*打开串口使能
USART_Cmd(USART1,ENABLE);
USART_ClearFlag(USART1, USART_FLAG_TC); //清除发送标志位
//5*设置串口中断类型
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
//6*配置中断优先级
NVIC_InitStructure.NVIC_IRQChannel =USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE ;
NVIC_Init(&NVIC_InitStructure);
}
void USART1_IRQHandler()
{
u8 r;
if(USART_GetITStatus(USART1,USART_IT_RXNE)==1)
{
r = USART_ReceiveData(USART1);
USART_SendData(USART1,r);
while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=1); //没有开启中断只是获取状态标志
}
USART_ClearFlag(USART1,USART_FLAG_TC);
}
usart.h
#ifndef _usart_H
#define _usart_H
#include "system.h"
void USART1_Init(u32 baud);
#endif
main.c
#include "systick.h"
#include "led.h"
#include "system.h"
#include "usart.h"
int main()
{
u8 i;
SysTick_Init(72); //系统时钟初始
LED_INIT();
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
USART1_Init(9600);
while(1)
{
i++;
if(i%20==0)
{
led1=!led1;
}
delay_ms(10);
}
}
网友评论