流心
发布于 2024-06-14 / 3 阅读
0

GPIO配置方法

1. 浮空输入(Floating Input)

特点:无上下拉,管脚处于高阻态,信号来源不确定时容易受干扰

GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = GPIO_PIN_X;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;   // 不上拉、不下拉
HAL_GPIO_Init(GPIOX, &GPIO_InitStruct);

2. 上拉输入(Input Pull-Up)

  • 特点:输入状态默认拉高,外部按键常接 GND

GPIO_InitStruct.Pin = GPIO_PIN_X;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;   // 上拉
HAL_GPIO_Init(GPIOX, &GPIO_InitStruct);

3. 下拉输入(Input Pull-Down)

  • 特点:输入状态默认拉低,外部按键常接 VCC

GPIO_InitStruct.Pin = GPIO_PIN_X;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLDOWN;   // 下拉
HAL_GPIO_Init(GPIOX, &GPIO_InitStruct);

4. 模拟输入(Analog Input)

  • 特点:用于 ADC,管脚模拟功能,关闭数字输入输出电路,功耗最低

GPIO_InitStruct.Pin = GPIO_PIN_X;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOX, &GPIO_InitStruct);

5. 开漏输出(Open-Drain Output)

  • 特点:只能输出低电平或悬空,需外部上拉才能输出高电平。常用于 I²C、线与功能

GPIO_InitStruct.Pin = GPIO_PIN_X;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;  // 开漏输出
GPIO_InitStruct.Pull = GPIO_NOPULL;          // 外部接上拉电阻
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOX, &GPIO_InitStruct);

6. 推挽输出(Push-Pull Output)

  • 特点:能直接输出高/低电平,驱动能力强。常用于普通 IO 控制

GPIO_InitStruct.Pin = GPIO_PIN_X;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;  // 推挽输出
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOX, &GPIO_InitStruct);

7. 复用开漏输出(Alternate Function Open-Drain)

  • 特点:外设功能引脚(如 I²C)需要开漏模式

GPIO_InitStruct.Pin = GPIO_PIN_X;
GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;   // 复用功能开漏
GPIO_InitStruct.Pull = GPIO_PULLUP;       // I²C 常用上拉
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF4_I2C1; // 指定外设复用功能
HAL_GPIO_Init(GPIOX, &GPIO_InitStruct);

8. 复用推挽输出(Alternate Function Push-Pull)

  • 特点:外设功能引脚(如 USART、SPI、PWM),通常为推挽模式

GPIO_InitStruct.Pin = GPIO_PIN_X;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;   // 复用功能推挽
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF7_USART1; // 指定外设复用功能
HAL_GPIO_Init(GPIOX, &GPIO_InitStruct);

总结:

  • 输入模式GPIO_MODE_INPUT / GPIO_MODE_ANALOG + Pull

  • 输出模式GPIO_MODE_OUTPUT_PP / GPIO_MODE_OUTPUT_OD

  • 复用模式GPIO_MODE_AF_PP / GPIO_MODE_AF_OD + Alternate