stm32的LED初始化函数
建立led.c,并在其中配置LED初始化需要的参数
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure; //定义了一个GPIO_InitTypeDef类型的结构体,名字叫GPIO_InitStructure
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //使能端口时钟B,要使能多个时钟的话用 或'|'
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; //GPIO_InitTypeDef的三个成员变量
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //PP是推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口速度为50MHz
GPIO_Init(GPIOB, &GPIO_InitStructure); //根据上面设定的三个参数初始化GPIOB.5
GPIO_SetBits(GPIOB,GPIO_Pin_5); //GPIOB.5输出高电平(电路图中显示高电平导通)
}
首先来看看GPIO_InitTypeDef这个结构体包含了哪些成员变量:(跳转至stm32f10x_gpio.h)
typedef struct
{
uint16_t GPIO_Pin; /*!< Specifies the GPIO pins to be configured.
This parameter can be any value of @ref GPIO_pins_define */
GPIOSpeed_TypeDef GPIO_Speed; /*!< Specifies the speed for the selected pins.
This parameter can be a value of @ref GPIOSpeed_TypeDef */
GPIOMode_TypeDef GPIO_Mode; /*!< Specifies the operating mode for the selected pins.
This parameter can be a value of @ref GPIOMode_TypeDef */
}GPIO_InitTypeDef;
而第一个成员变量,GPIO_Pin可以是任一GPIO_pins_define的值,在stm32f10x_gpio.h中找到了定义:
#define GPIO_Pin_0 ((uint16_t)0x0001) /*!< Pin 0 selected */
#define GPIO_Pin_1 ((uint16_t)0x0002) /*!< Pin 1 selected */
//中间这部分不啰嗦了
#define GPIO_Pin_15 ((uint16_t)0x8000) /*!< Pin 15 selected */
#define GPIO_Pin_All ((uint16_t)0xFFFF) /*!< All pins selected */
同样,第二个成员变量GPIO_Speed,其类型是GPIOSpeed_TypeDef:(原来是枚举,有三个可选择的变量)
typedef enum
{
GPIO_Speed_10MHz = 1, //为啥有个=1啊...删掉了后依然可以运行
GPIO_Speed_2MHz,
GPIO_Speed_50MHz
}GPIOSpeed_TypeDef;
最后是第三个成员变量,GPIO_Mode
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_InitTypeDef类型的结构体?因为GPIO_Init函数的定义中明确需要这个类型的参数:
void GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_InitTypeDef* GPIO_InitStruct)
所以我们的LED_Init函数总共干了三件事:
- 初始化端口时钟(不初始化不能用的,任何外设都一样)
- 初始化IO口(上面的栗子中初始化了GPIOB.5)
- 拉高对应端口电平
看下电路图:


资料来源于正点原子,如侵删

浙公网安备 33010602011771号