我们在初始化IO口的过程中,需要初始化好几个变量,例如引脚、速度、模式
我们可以把几个变量组合在一起,成一组,想布线总线一样,提高代码可读性
typedef为现有类型创建一个新的名字,方便阅读和理解
官方库里面用了很多结构体,例如IO口初始化结构体定义:
/** * @brief GPIO Init structure definition */ 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;
这段代码含义:把含有3个变量的结构体,使用GPIO_InitTypeDef这个名字来替代
GPIO_InitTypeDef可以联想到U16,这样比较好理解
函数里面定义了两个变量,变量使用了指针,第一个指针指向了GPIOx,第二个指针指向了GPIO_InitStruct
void GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_InitTypeDef* GPIO_InitStruct)
例如下面这一段代码,第一句写的是:
GPIO_Init(GPIOA,&GPIO_InitStructure); //初始化PA口
根据函数定义,第二个变量
&GPIO_InitStructure 意思是把变量GPIO_InitStructure的地址给指针GPIO_InitStruct
/*****初始化SW的IO口*****/ //A1 两泵浦开关,高电平为关 //B7 风扇开关 // 光开关,还没有连接,暂时没写 void SW_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB,ENABLE); //GPIOA GPIOB //GPIOA1 GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP; //推挽模式 GPIO_InitStructure.GPIO_Pin=GPIO_Pin_1; //初始化A1 GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz; //速度50M GPIO_Init(GPIOA,&GPIO_InitStructure); //初始化PA口 GPIO_SetBits(GPIOA,GPIO_Pin_1); //设置高电平输出 //GPIOB7 GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP; //推挽模式 GPIO_InitStructure.GPIO_Pin=GPIO_Pin_7; //初始化A1 GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz; //速度50M GPIO_Init(GPIOB,&GPIO_InitStructure); //初始化PA口 GPIO_ResetBits(GPIOB,GPIO_Pin_7); //设置低电平输出 }
这三个变量就是结构体里面的三个变量
原文:https://www.cnblogs.com/lb24001/p/13754271.html