STM32笔者这里之STM32F1XX和F4XX系列的M3,M4的内核。
库函数的名字一般叫做STM32Fxxx_GPIO.c和.h
以F107为例,
初始化GPIO的程序如下:
void BSP_GPIO_Init( void )
{
GPIO_InitTypeDef s_GPIO_InitStructure;
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOC \
| RCC_APB2Periph_GPIOD| RCC_APB2Periph_GPIOE|RCC_APB2Periph_AFIO, ENABLE);/* 使能GPIOB&GPIOC&GPIOD时钟*/
s_GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 \
| GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_12;
s_GPIO_InitStructure.e_GPIO_Speed = GPIO_Speed_50MHz;
s_GPIO_InitStructure.e_GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &s_GPIO_InitStructure);
}
首先是使能CMD时钟,
之后选择对应的管脚,
配置速度和模式,然后初始化。
s_GPIO_InitStructure.e_GPIO_Speed = GPIO_Speed_50MHz;
这句话经常会漏掉,导致GPIO口配置失败。
初始化之后,一般可以使用宏定义使用对应的IO口
#define LED_WORK_ON() (GPIO_ResetBits(GPIOC, GPIO_Pin_6))
#define LED_WORK_OFF() (GPIO_SetBits(GPIOC, GPIO_Pin_6))
这两个函数在库函数里有给出。
输入的话可以使用这个函数
GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_14)
关于GPIO的模式,如下
/* Configuration Mode enumeration */
typedef enum /* 模式类型*/
{ GPIO_Mode_AIN = 0x0, /* 模拟输入*/
GPIO_Mode_IN_FLOATING = 0x04, /* 浮空输入*/
GPIO_Mode_IPD = 0x28, /* 下拉输入*/
GPIO_Mode_IPU = 0x48, /* 上拉输入*/
GPIO_Mode_Out_OD = 0x14, /* 开漏输出*/
GPIO_Mode_Out_PP = 0x10, /* 推免输出*/
GPIO_Mode_AF_OD = 0x1C, /* 附加*/
GPIO_Mode_AF_PP = 0x18 /* 附加*/
}GPIOMode_TypeDef;
最后说明一点,GPIO一定要在初始化之后再用,否则会有意想不到的事情,程序的BUG发生。
与M0的NUC不同,STM32的GPIO没有准双向,
这样的话,也就没有做准双向时,读取数据前要先写1这个操作了。