基于hal库的stm32f411re的GPIO输出模式下电平的读取
1.硬件的配置
对GPIO的参数配置
首先需要创建一个结构体指针:
GPIO_InitTypeDef GPIO_InitStruct = {0};
该结构体主要是对GPIO管脚的配置:
typedef struct
{
uint32_t Pin; /*!< Specifies the GPIO pins to be configured.
This parameter can be any value of @ref GPIO_pins_define */
uint32_t Mode; /*!< Specifies the operating mode for the selected pins.
This parameter can be a value of @ref GPIO_mode_define */
uint32_t Pull; /*!< Specifies the Pull-up or Pull-Down activation for the selected pins.
This parameter can be a value of @ref GPIO_pull_define */
uint32_t Speed; /*!< Specifies the speed for the selected pins.
This parameter can be a value of @ref GPIO_speed_define */
uint32_t Alternate; /*!< Peripheral to be connected to the selected pins.
This parameter can be a value of @ref GPIO_Alternate_function_selection */
}GPIO_InitTypeDef;
在STM32的所有外设都需要使能时钟,
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
最后,初始化GPIO,调用函数
void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init);
由于该函数需要传入结构体指针,需要配置好再调用。
assert_param(IS_GPIO_ALL_INSTANCE(GPIOx));
assert_param(IS_GPIO_PIN(GPIO_Init->Pin));
assert_param(IS_GPIO_MODE(GPIO_Init->Mode));
assert_param(IS_GPIO_PULL(GPIO_Init->Pull));
在该函数的开头都回判断参数是否存在,所有需要配置以上参数。
GPIO_InitStruct.Pin = GPIO_PIN_4;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT ;
GPIO_InitStruct.Pull = GPIO_PULLUP ;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
而对于作为输入引脚用来读取电平时,需要配置成输入模式GPIO_MODE_INPUT,并将上下拉设置为上拉电阻GPIO_PULLUP,最后调用该函数。
接着通过设置另一个管脚为高电平,输入该引脚,用来读取电平。调用
GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)