keil5 stm32串口3初始化
时间: 2023-11-08 18:56:17 浏览: 34
以下是Keil5中针对STM32的串口3初始化代码示例:
```c
#include "stm32f4xx.h"
void Init_USART3(void)
{
// 使能 USART3 时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
// 配置 USART3 引脚
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource10, GPIO_AF_USART3);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource11, GPIO_AF_USART3);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// 配置 USART3 参数
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 115200; // 波特率
USART_InitStructure.USART_WordLength = USART_WordLength_8b; // 字长为8位数据格式
USART_InitStructure.USART_StopBits = USART_StopBits_1; // 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(USART3, &USART_InitStructure); // 初始化串口3
// 使能 USART3
USART_Cmd(USART3, ENABLE);
}
```
以上代码中,我们首先要使能USART3的时钟,然后配置USART3的引脚。接着,我们可以通过USART_InitTypeDef结构体配置USART3的参数,包括波特率、数据格式、停止位、奇偶校验位等。最后,我们使能USART3即可。需要注意的是,以上代码中使用的是GPIOB的引脚10和11作为USART3的TX和RX引脚,如果你需要使用其他引脚,需要修改相应的代码。