以stm32的USART1来举例
默认使用的是PA9为TX,PA10为RX,当需要开启复用功能时,需要注意修改以下几个地方的代码
1 时钟的开启
当使用复用功能后,就需要开启复用时钟RCC_APB2Periph_AFIO
2 初始化引脚的不同,原来的是PA9,PA10,但是现在要初始化PB6,PB7,这一部分就不贴代码了。
3 调用GPIO_PinRemapConfig()函数
GPIO_PinRemapConfig(GPIO_Remap_USART1,ENABLE);
USART1的重映射开启
注意:GPIO_PinRemapConfig()函数的参数是不能随便写的,在《stm32固件库使用手册》里面给出了可用参数的列表
GPIO_PinRemapConfig(GPIO_FullRemap_USART3, ENABLE); //USART3的复用功能完全重映射
GPIO_PinRemapConfig(GPIO_PartialRemap_USART3, ENABLE); //USART3的部分重映射
部分重映射和完全重映射有什么区别那?在网上我也没找到确定的答案,但是建议开启完全重映射,因为网上有资料说部分重映射在发送消息时候不正常(我自己没有做实验)
还需要注意,在开启重映射功能之前一定要先查看一下自己的单片机是否支持重映射功能。
附:初始化串口的程序
void USART1_Config(void)
{
<span style="white-space:pre"> </span>GPIO_InitTypeDef GPIO_InitStructure;
<span style="white-space:pre"> </span>USART_InitTypeDef USART_InitStructure;
/* config USART1 clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO, ENABLE);
/* USART1 GPIO config */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_PinRemapConfig(GPIO_Remap_USART1,ENABLE);
//GPIO_AFIODeInit();
/* USART1 mode config */
USART_InitStructure.USART_BaudRate = 115200;
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);
}