在分析GPIO之前,我们应当了解STM32开发方式。
常规开发方式有:软件库开发方式与直接配置寄存器方式
大部分情况下,我们采用软件库开发方式,即用户在调取软件库的API时,无需了解底层的寄存器操作,实际上库是架在寄存器与用户驱动之间的代码。
一、GPIO简介
GPIO(Gerneral Purpose Input Output)即微处理器通用输入/输出接口,可以实现对某些设备的控制或信号采集功能。另外,也可以将GPIO进行复用配置,实现较复杂的并行通信和总线通信等功能。
STM32F407IG系列的GPIO被分为GPIOA-GPIOI共9组,每组有16个引脚(Pin),对于任一引脚都可以进行如下操作:
(一)模式设置(Mode)
typedef enum
{
GPIO_Mode_IN = 0x00, /*!< GPIO Input Mode */
GPIO_Mode_OUT = 0x01, /*!< GPIO Output Mode */
GPIO_Mode_AF = 0x02, /*!< GPIO Alternate function Mode */
GPIO_Mode_AN = 0x03 /*!< GPIO Analog Mode */
}GPIOMode_TypeDef;
GPIO的端口模式共有四种:
输入模式(Input)、
输出模式(Output)、
复用模式(Alternate function)、
模拟输入模式(Analog)
(二)输出模式(OType)
typedef enum
{
GPIO_OType_PP = 0x00,
GPIO_OType_OD = 0x01
}GPIOOType_TypeDef;
GPIO的输出模式共有两种:推挽输出(PP)和开漏输出(OD)
推挽输出:是根据图中这两个MOS管来命名的,
当 IN 为高电平时,上方PNP三极管导通,下方NPN三极管截止,对外输出高电平;
当 IN 为低电平时,下方NPN三极管导通,上方PNP三极管截止,对外输出低电平。
当引脚高低电平切换时,两个三极管轮流导通,一个负责灌电流,一个负责拉电流。因此,得名推挽输出。
开漏输出:
当 IN 为低电平时,NPN三极管导通,对外输出低电平。
当 IN 为高电平时,NPN三极管截止,对外输出高电平,但由于。
(三)输入模式(PuPd)
typedef enum
{
GPIO_PuPd_NOPULL = 0x00,
GPIO_PuPd_UP = 0x01,
GPIO_PuPd_DOWN = 0x02
}GPIOPuPd_TypeDef;
输入模式:NoPULL(浮空)电压即不为0(低电平,也不为3.3V(高电平),约在1V左右。
UP(上拉)电压为3.3V(高电平)
DOWN(下拉)电压为0V(低电平)
(四)端口速度(Speed)
typedef enum
{
GPIO_Low_Speed = 0x00, /*!< Low speed */
GPIO_Medium_Speed = 0x01, /*!< Medium speed */
GPIO_Fast_Speed = 0x02, /*!< Fast speed */
GPIO_High_Speed = 0x03 /*!< High speed */
}GPIOSpeed_TypeDef;
GPIO端口速度有四种:低速、中速、快速、超快速。
用户可根据不同需要配置端口速度,以节省功耗。
#define GPIO_Speed_2MHz GPIO_Low_Speed
#define GPIO_Speed_25MHz GPIO_Medium_Speed
#define GPIO_Speed_50MHz GPIO_Fast_Speed
#define GPIO_Speed_100MHz GPIO_High_Speed
值得注意的是:low、medium、fast、high分别被宏定义为2M、25M、50M、100M。调用端口速度结构体 GPIO_Speed_Typedef时,应当用上述表示法。
二、端口初始化
对端口进行使用前需要对端口进行初始化,并指定端口各项参数,各参数的确定将用到前文所讲到的四个结构体。
typedef struct
{
uint32_t GPIO_Pin; /*!< Specifies the GPIO pins to be configured.
This parameter can be any value of @ref GPIO_pins_define */
GPIOMode_TypeDef GPIO_Mode; /*!< Specifies the operating mode for the selected pins.
This parameter can be a value of @ref GPIOMode_TypeDef */
GPIOSpeed_TypeDef GPIO_Speed; /*!< Specifies the speed for the selected pins.
This parameter can be a value of @ref GPIOSpeed_TypeDef */
GPIOOType_TypeDef GPIO_OType; /*!< Specifies the operating output type for the selected pins.
This parameter can be a value of @ref GPIOOType_TypeDef */
GPIOPuPd_TypeDef GPIO_PuPd; /*!< Specifies the operating Pull-up/Pull down for the selected pins.
This parameter can be a value of @ref GPIOPuPd_TypeDef */
}GPIO_InitTypeDef;
端口初始化结构体(GPIO_InitTypeDef)定义了如下内容:
Pin:使用的端口(任一)
Mode: 端口模式 (前文已分析)
Speed:端口速度(前文已分析)
OType:输出模式(前文已分析)
PuPd: 输入模式(前文已分析)