SRM32F103配置uart
时间: 2025-06-05 21:38:46 浏览: 17
### SRM32F103 UART 配置教程
STM32F103系列微控制器内置多个USART模块,用于实现串口通信功能。以下是关于如何在STM32F103芯片上配置UART的具体方法以及示例代码。
#### 1. GPIO初始化
为了使能UART功能,首先需要配置相应的GPIO引脚作为TX(发送)和RX(接收)。这可以通过设置GPIO模式为复用功能来完成[^3]。
```c
void USART_GPIO_Init(void) {
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); // 使能GPIOA时钟
GPIO_InitTypeDef GPIO_InitStruct;
// 配置PA9为USART1_TX
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; // 复用推挽输出
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStruct);
// 配置PA10为USART1_RX
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING; // 浮动输入
GPIO_Init(GPIOA, &GPIO_InitStruct);
}
```
#### 2. USART 初始化
接着需对USART外设本身进行参数设定,比如波特率、字长、停止位等。这里以USART1为例说明。
```c
void USART_Configuration(void){
USART_InitTypeDef USART_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); // 使能USART1时钟
USART_InitStruct.USART_BaudRate = 9600; // 设置波特率为9600bps
USART_InitStruct.USART_WordLength = USART_WordLength_8b;// 字符长度为8bit
USART_InitStruct.USART_StopBits = USART_StopBits_1; // 停止位数为1
USART_InitStruct.USART_Parity = USART_Parity_No ; // 不使用校验
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None; // 关闭硬件流控
USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; // 启用收发模式
USART_Init(USART1,&USART_InitStruct);
USART_Cmd(USART1,ENABLE); // 开启USART1
}
```
#### 3. 数据传输函数定义
最后可以编写简单的数据发送与接收函数以便于后续调用。
```c
// 发送单个字符
void USART_SendChar(char ch){
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE)==RESET);
USART_SendData(USART1,ch);
}
// 接受单个字符
char USART_ReceiveChar(void){
while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE)==RESET);
return USART_ReceiveData(USART1);
}
```
通过上述步骤即可成功配置并使用STM32F103上的UART功能来进行基本的数据通讯操作。
阅读全文
相关推荐


















