觉得不错分享给大家,学习!
转载地址:http://www.eeworld.com.cn/mcu/article_2017091234363.html
http://blog.csdn.net/liucheng_34/article/details/48175505
以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)
-
{
-
GPIO_InitTypeDef GPIO_InitStructure;
-
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);
-
}
重映射步骤为:
1.打开重映射时钟和USART重映射后的I/O口引脚时钟,
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO,ENABLE);
2.I/O口重映射开启.
GPIO_PinRemapConfig(GPIO_Remap_USART1,ENABLE);
3.配制重映射引脚, 这里只需配置重映射后的I/O,原来的不需要去配置.
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);
只需要这三步
简单的说 STM32的 io 有3个功能 一个是默认的 一个是复用 一个是重映射功能(这个其实也属于复用)
如果配置成复用 则将使用第2个功能 如果配置成复用 同时 相应的重映射配置了 则将使用第3个功能
通常一个口的 复用+重映射有好多 不止两个 这时候就看你使能哪个设备了
开复用 + 使能设备+ 是否重映射 就可以决定这个io口 到底使用哪个功能