学习笔记——串口配置

 1 /**********串口1初始化函数**********/
 2 //bound:波特率
 3 void My_USART1_Init(u32 bound)
 4 {
 5 //定义结构体变量
 6 GPIO_InitTypeDef GPIO_InitStructure;
 7 USART_InitTypeDef USART_InitStructure;
 8 NVIC_InitTypeDef NVIC_InitStructure;
 9 RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE); //使能 GPIOA 时钟
10 RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE); //使能 USART1 时钟(只有串口1和6是挂在APB2上)
11 //对应引脚复用映射
12 GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1);
13 GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1);
14 //GPIO端口模式设置
15 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10; //GPIOA9 与 GPIOA10
16 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;             //复用功能
17 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;       //速度 50MHz
18 GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;          //推挽复用输出
19 GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;            //上拉
20 GPIO_Init(GPIOA,&GPIO_InitStructure);                    //初始化 PA9, PA10
21 //串口参数初始化
22 USART_InitStructure.USART_BaudRate = bound;                           //一般设置为 9600;
23 USART_InitStructure.USART_WordLength = USART_WordLength_8b;         //字长为 8 位
24 USART_InitStructure.USART_StopBits = USART_StopBits_1;              //一个停止位
25 USART_InitStructure.USART_Parity = USART_Parity_No;                 //无奇偶校验位
26 USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制
27 USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;   //收发
28 USART_Init(USART1, &USART_InitStructure);                           //初始化串口1
29 
30 USART_Cmd(USART1, ENABLE);                                           //使能串口1
31 USART_ClearFlag(USART1, USART_FLAG_TC);                             //清除数据发送完成标识符
32 USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//开启接收中断,在接受移位寄存器中有数据时产生(一般与PC机通信只使能这个就行)
33 //需要时开启中断,初始化NVIC 
34 NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;            //USART1中断配置
35 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3;     //抢占优先级 3
36 NVIC_InitStructure.NVIC_IRQChannelSubPriority =3;               //响应优先级 3
37 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;                 //IRQ 通道使能
38 NVIC_Init(&NVIC_InitStructure);                                  //根据指定的参数初始化 VIC 寄存器、
39 }
40 
41 /**********中断处理函数**********/
42 void USART1_IRQHandler(void) //串口 1 中断服务程序
43 {
44   if(USART_GetITStatus(USARTy, USART_IT_RXNE) != RESET)//如果寄存器中有数据
45   {
46 /* 从接收数据寄存器中读取一个字节 */
47   RxBuffer1[RxCounter1++] = USART_ReceiveData(USART1);
48   }
49   if(USART_GetITStatus(USARTy, USART_IT_TXE) != RESET)
50   {
51   USART_SendData(USARTy, TxBuffer1[TxCounter1++]);
52   } 
53 }

主函数:

1 int main(void)
2 {
3     NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//设置系统中断优先级分组2
4     My_USART1_Init();
5     While(1);
6 }

 

posted @ 2019-12-09 15:51  迪迦奥特快  阅读(690)  评论(0编辑  收藏  举报