在此之前,先引入知识点:
- 一般情况下,学习使用的书一般使用以下格式进行结构体类型定义
struct [结构体类型名]
{
数据类型 成员名1;
数据类型 成员名2;
};
可先定义结构体类型,再用该类型名定义结构体变量。 - 类型定义的格式:
typedef 类型 标识符;
类型定义不是定义一种新的数据类型,而是给已有的数据类型起一个新名称。
即标识符是类型的新名称。
一、一般情况下的定义方法
1)定义结构体类型的同时定义结构体类型变量
struct GPIO
{
uint32_t GPIO_Pin;
GPIOMode_TypeDef GPIO_Mode;
GPIOSpeed_TypeDef GPIO_Speed;
GPIOOType_TypeDef GPIO_OType;
GPIOPuPd_TypeDef GPIO_PuPd;
}GPIO_InitTypeDef;
GPIO_InitTypeDef是结构体变量
2)定义结构体类型的时候缺省结构体类型名
struct
{
uint32_t GPIO_Pin;
GPIOMode_TypeDef GPIO_Mode;
GPIOSpeed_TypeDef GPIO_Speed;
GPIOOType_TypeDef GPIO_OType;
GPIOPuPd_TypeDef GPIO_PuPd;
}GPIO_InitTypeDef;
GPIO_InitTypeDef是结构体变量;相比1)缺省了结构体类型名。
二、加了typedef之后的定义方法
1)定义结构体类型的同时定义结构体类型变量
typedef struct GPIO
{
uint32_t GPIO_Pin;
GPIOMode_TypeDef GPIO_Mode;
GPIOSpeed_TypeDef GPIO_Speed;
GPIOOType_TypeDef GPIO_OType;
GPIOPuPd_TypeDef GPIO_PuPd;
}GPIO_InitTypeDef;
GPIO_InitTypeDef为一个结构体类型,即GPIO_InitTypeDef=struct GPIO.
以直接用GPIO_InitTypeDef来定义变量,同时也可以根据 struct GPIO [结构体类型变量];GPIO_InitTypeDef [结构体类型变量];这两种类型定义,因为GPIO_InitTypeDef 等同于 struct GPIO。
2)定义结构体类型的时候缺省结构体类型名
typedef struc
{
uint32_t GPIO_Pin;
GPIOMode_TypeDef GPIO_Mode;
GPIOSpeed_TypeDef GPIO_Speed;
GPIOOType_TypeDef GPIO_OType;
GPIOPuPd_TypeDef GPIO_PuPd;
}GPIO_InitTypeDef;
GPIO_InitTypeDef是一个结构体类型,即GPIO_InitTypeDef=struct
所以STM32的例程里,关于GPIO或者其他的初始结构定义中对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;
void XXX_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;//定义结构体变量
//通过结构体变量访问成员
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_x;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOX, &GPIO_InitStructure); //初始化GPIOXx
}