完善资料让更多小伙伴认识你,还能领取20积分哦, 立即完善>
电子发烧友论坛|
一、应用简介 根据原理图及数据手册初始化串口进行串口通信。 二、串口通信 2.1 原理图 开发板中的 CH340G 的收发引脚默认通过跳帽连接到 USART1,如果想使用其他串口,可以把 CH340G 跟 USART1 直接的连接跳帽拔掉,然后再把其他串口的 IO 用杜邦线接到 CH340G 的收发引脚即可。 这里我们使用 USART1,设定波特率为 115200,选定 USART 的 GPIO 为 PA9 和 PA10。 2.2 配置代码 2.2.1 NVIC配置 /** @brief NVIC初始化 @param 无 @return 无 */ static void NVIC_Configuration(void) { NVIC_InitTypeDef NVIC_InitStructure; /* 嵌套向量中断控制器组选择 */ NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); /* 配置 USART 为中断源 */ NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; /* 抢断优先级为 1 */ NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; /* 子优先级为 1 */ NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; /* 使能中断 */ NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; /* 初始化配置 NVIC */ NVIC_Init(&NVIC_InitStructure); } 2.2.2 串口初始化 /** @brief 串口初始化 @param 无 @return 无 */ void USART_Config(void) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; // 打开串口 GPIO 的时钟 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); // 打开串口外设的时钟 RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); // 将 USART Tx 的 GPIO 配置为推挽复用模式 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); // 将 USART Rx 的 GPIO 配置为浮空输入模式 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA, &GPIO_InitStructure); // 配置串口的工作参数 // 配置波特率 USART_InitStructure.USART_BaudRate = 115200; // 配置 针数据字长 USART_InitStructure.USART_WordLength = USART_WordLength_8b; // 配置停止位 USART_InitStructure.USART_StopBits = USART_StopBits_1; // 配置校验位 USART_InitStructure.USART_Parity = USART_Parity_No ; // 配置硬件流控制 USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; // 配置工作模式,收发一起 USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; // 完成串口的初始化配置 USART_Init(USART1, &USART_InitStructure); // 串口中断优先级配置 NVIC_Configuration(); // 使能串口接收中断 USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); // 使能串口 USART_Cmd(USART1, ENABLE); } 2.2.3 串口发送(不发送可跳过此步骤) /***************** 发送一个字符 **********************/ /** @brief 发送一个字符 @param pUSARTx - [in] 串口 @param ch- [in] 字符 @return 无 */ void Usart_SendByte(USART_TypeDef * pUSARTx, uint8_t ch) { /* 发送一个字节数据到 USART */ USART_SendData(pUSARTx,ch); /* 等待发送数据寄存器为空 */ while(USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET); } /***************** 发送字符串 **********************/ /** @brief 发送字符串 @param pUSARTx - [in] 串口 @param str- [in] 字符串 @return 无 */ void Usart_SendString(USART_TypeDef * pUSARTx, char *str) { unsigned int k = 0; do { Usart_SendByte(pUSARTx, *(str + k)); k++; }while(*(str + k) != ' |

淘帖
2041