STM32学习-9-[串口]为串口初始化IO引脚
USART模块有哪些引脚

主要包括Tx和Rx引脚,其他引脚基本用不傲
引脚分布表
这是数据手册里面的图

包含了不同封装类型对应的不同引脚功能,上电后默认的功能和可复用的功能

从图中找到了USART对应的复用引脚
如果上面图中的引脚已经被占用了,那么可以重映射到其他引脚,如图所示

就是下图的那种关系

重映射表
看一眼表格

在数据手册里面有这些引脚的复用映射
IO配置表
表中记录了使用该功能,引脚要配置什么模式

编写代码(使用默认配置)
#include "stm32f10x.h"
int main(void)
{
GPIO_InitTypeDef GPIO_InitStruct; // 定义初始化结构体
// Tx PA9 复用输出推挽
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); // 开启时钟
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9; // 设置配置的引脚编号
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; // 模式
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_10MHz; // 最大速度
GPIO_Init(GPIOA.&GPIO_InitStruct);
// Rx PA10 输入浮空 输入上拉
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU; // 模式
GPIO_Init(GPIOA, &GPIO_InitStruct);
while(1)
{
}
}
编写代码(重映射)
#include "stm32f10x.h"
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE); // 使能AFIO模块的时钟
GPIO_PinRemapConfig(GPIO_Remap_USART1,ENABLE); // USART1_REMAP=1,启动重映射USART1
GPIO_InitTypeDef GPIO_InitStruct;
// Tx PB6 输出推挽
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; // 模式
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_10MHz; // 最大速度
GPIO_Init(GPIOB,&GPIO_InitStruct);
// Rx PB7 输入浮空 输入上拉
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU; // 模式
GPIO_Init(GPIOB, &GPIO_InitStruct);
while(1)
{
}
}
映射需要使用到AFIO这个边上外设模块,所以启动他的时钟

浙公网安备 33010602011771号