stm32f103c8t6 USART3怎么配置
时间: 2025-03-05 16:35:47 浏览: 118
### STM32F103C8T6 USART3 配置指南
对于STM32F103C8T6单片机而言,USART3接口的初始化和配置涉及多个方面,包括使能时钟、设置波特率、数据位、停止位以及校验方式等参数。具体实现如下:
#### 1. 初始化库与头文件引入
为了简化外设操作,在程序开发过程中通常会采用标准外设库或HAL库来完成硬件抽象层的设计。这里假设使用的是官方提供的Standard Peripheral Library (SPL),则需先包含必要的头文件。
```c
#include "stm32f1xx.h"
```
#### 2. 使能相关功能模块与时钟源
在实际应用中,需要确保USART3及其关联GPIO端口所在的APB1总线处于激活状态,并开启相应的RCC时钟控制寄存器中的对应位。
```c
// Enable GPIOA and UART clock
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
```
#### 3. 配置引脚复用功能
根据具体的电路连接情况,选择合适的I/O引脚作为UART通信线路(TX/RX)。在此基础上,还需通过修改AFIO寄存器来设定这些引脚的功能属性。
```c
GPIO_InitTypeDef GPIO_InitStructure;
/* Configure USART Tx as alternate function push-pull */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Configure USART Rx as input floating */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
```
#### 4. 设置串行通讯参数
接下来就是针对USART本身的一些基本特性进行定义了,比如传输速率(即波特率)、字符长度、奇偶检验选项等等。这部分可以通过调用`USART_Init()`函数轻松搞定。
```c
USART_InitTypeDef USART_InitStructure;
// Set the baud rate to 115200 bps.
USART_InitStructure.USART_BaudRate = 115200;
// Word length is set to 8 bits per frame.
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
// One stop bit used at end of each transmitted byte.
USART_InitStructure.USART_StopBits = USART_StopBits_1;
// No parity checking performed during transmission/reception.
USART_InitStructure.USART_Parity = USART_Parity_No ;
// Hardware flow control disabled here.
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
// Select standard asynchronous mode without LIN protocol support.
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
// Apply above settings to USART peripheral instance.
USART_Init(USART3, &USART_InitStructure);
```
#### 5. 启动USART设备并启用中断服务例程(可选)
最后一步便是正式打开该串行接口以便于后续的数据交换活动;如果希望利用中断机制处理收发事件,则还需要额外注册对应的ISR入口地址至向量表内。
```c
// Enable USART3 interrupt on receive not empty flag.
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
// Finally enable both transmitter and receiver circuits within USART module itself.
USART_Cmd(USART3, ENABLE);
```
以上步骤涵盖了从最基础到较为复杂的几个层面,能够帮助开发者快速建立起稳定可靠的异步串行通信链路[^1]。
阅读全文
相关推荐

















