5. 串口通信程序实现(发送什么,就接收什么)
1. 串口时钟使能:RCC_APBxPeriphClockCmd(); GPIO时钟使能:RCC_AHB1PeriphClockCmd();
2. 引脚复用映射:GPIO_PinAFConfig();
3. GPIO端口模式设置:GPIO_Init(); 模式设置:GPIO_Mode_AF;
4. 串口参数初始化:USART_Init();
5. 开启中断并且初始化NVIC:NVIC_Init(); USART_ITConfig();
6. 使能串口:USART_Cmd();
7. 编写中断服务函数:USARTx_IQRHandler();
8. 串口数据收发:void USART_SendData(); uint16_t USART_ReceiveData();
9. 串口传输状态获取:FlagStatic USART_GetFlagStatus(); void USART_ClearITPendingBit();
- #include "stm32f4xx.h"
- #include "delay.h"
- #include "LED.h"
- #include "BEEP.h"
- #include "Key.h"
- #include "usart.h"
-
-
- void My_USART1_Init(void)
- {
- GPIO_InitTypeDef GPIO_InitStructure;//设置GPIOA结构体变量
- USART_InitTypeDef USART_InitStructure;//设置串口结构体变量
- NVIC_InitTypeDef NVIC_InitStructure;//设置中断优先级NVIC结构体变量
-
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);//使能串口1时钟
- RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);//GPIOA使能
-
- GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1);//PA9引脚映射为串口1
- GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1);//PA10引脚映射为串口1
-
-
- GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;//初始化引脚
- GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF;//设置模式为复用功能
- GPIO_InitStructure.GPIO_OType=GPIO_OType_PP;//推挽输出
- GPIO_InitStructure.GPIO_PuPd=GPIO_PuPd_UP;//上拉
- GPIO_InitStructure.GPIO_Speed=GPIO_Speed_100MHz;//速度
- GPIO_Init(GPIOA,&GPIO_InitStructure);//GPIOA初始化
-
- GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;//初始化引脚
- GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF;//设置模式为复用功能
- GPIO_InitStructure.GPIO_OType=GPIO_OType_PP;//推挽输出
- GPIO_InitStructure.GPIO_PuPd=GPIO_PuPd_UP;//上拉
- GPIO_InitStructure.GPIO_Speed=GPIO_Speed_100MHz;//速度
- GPIO_Init(GPIOA,&GPIO_InitStructure);//GPIOA初始化
-
-
- USART_InitStructure.USART_BaudRate=115200;//设置波特率
- USART_InitStructure.USART_Mode=USART_Mode_Rx|USART_Mode_Tx;//设置串口模式使能Tx/Rx
- USART_InitStructure.USART_Parity=USART_Parity_No;//设置奇偶校验位
- USART_InitStructure.USART_StopBits=USART_StopBits_1;//设置停止位
- USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;//硬件流控制
- USART_InitStructure.USART_WordLength=USART_WordLength_8b;//设置8位字长(设置9位字长通常最后一位是奇偶校验位)
- USART_Init(USART1,&USART_InitStructure);//串口初始化
- USART_Cmd(USART1,ENABLE);//使能串口1
-
- USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//开启相关中断 USART_IT_RXNE使能非空
- NVIC_InitStructure.NVIC_IRQChannel=USART1_IRQn;//串口1中断通道
- NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;//IQR通道使能
- NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=1;//抢占优先级1
- NVIC_InitStructure.NVIC_IRQChannelSubPriority=1;//子优先级1
- NVIC_Init(&NVIC_InitStructure);//初始化NVIC中断优先级
-
-
-
- }
- void USART1_IRQHandler(void)//中断服务函数
- {
- u8 res;
- if(USART_GetITStatus(USART1, USART_IT_RXNE))//判断开启的中断是否接收到了相关信息,当该寄存器是1时,表示有数据接收到了
- {
- res=USART_ReceiveData(USART1);//将串口1接收到的数据给res
- USART_SendData(USART1,res);//将res在发送给串口1
- }
- }
- int main()
- {
- NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//设置系统中断优先级分组,2位抢占优先级,2位响应优先级
- My_USART1_Init();
- while(1)
- {
-
- }
-
- }
|