正点原子stm32f103 nano串口
时间: 2024-12-29 11:14:37 浏览: 31
正点原子 STM32F103 Nano 开发板串口使用教程
一、硬件连接
对于正点原子 STM32F103 Nano 开发板而言,要实现通过USART与外部设备通信的功能,需先完成相应的硬件连线工作。通常情况下,该款开发板已经内置了USB转TTL芯片用于调试目的,这意味着可以直接利用USB线缆将计算机同开发板相连[^2]。
二、软件配置
为了使能并初始化串口,在main.c
文件中的main()
函数里调用了uart_init(72,115200)
来设置波特率为115200bps,并指定APB2时钟频率为72MHz作为参数传递给此API[^5]。
// 初始化串口
void uart_init(u8 ubaud)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);
// 配置 PA9 为 USART1_TX
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);
// 配置 PA10 为 USART1_RX
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = ubaud * 1000;
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);
USART_Cmd(USART1, ENABLE);
}
上述代码片段展示了如何具体地去初始化USART1接口,包括但不限于端口映射及时钟分频等操作。
三、数据发送接收测试
当完成了基本的初始化之后,则可以通过简单的循环向终端打印字符串来进行初步验证:
while (1) {
printf("OK\n");
delay_ms(1000);
}
这段程序会每隔一秒向连接至电脑上的虚拟COM端口中写入一次“OK”的消息。
相关推荐


















