Sensors and I/O

GPIO in and out

Buttons, relays, level detect. The I/O baseline.

Sensors and I/O GPIOButton / relay ESP32 family

Official path: examples/peripherals/gpio/generic_gpio

01 Overview

GPIO is the most basic way for the ESP32 to exchange signals with the outside world. Each pin can be configured as input or output, with internal pull-up/pull-down, interrupt triggers (rising, falling, any edge), and open-drain mode.

This example demonstrates how to initialize GPIO, read button states, control relays, and handle interrupts. It solves the most common I/O needs in products: detecting external level changes and driving actuators.

Typical applications include: device panel buttons, door/magnetic alarm inputs, relay control (e.g., lights, pumps, fans), and simple level detection (e.g., comparator output for battery voltage).

GPIO is suitable for low-speed, non-timing-critical signals. For protocols requiring precise timing (e.g., WS2812, DHT11, or high-speed SPI), use dedicated peripherals like RMT, SPI, or I2S.

This example does not cover analog sampling (ADC), PWM output, or communication protocols; those are covered by other examples.

Understanding GPIO electrical characteristics and software configuration is fundamental to product stability; incorrect pull-ups or drive circuits can cause false triggers or device damage.

02 Hardware

  • MCU: ESP32 family, 3.3V logic levels, most GPIO pins are 5V-tolerant (see datasheet), but avoid direct 5V signals.
  • Power: 3.3V main supply; relays and other heavy loads need external power, never draw from GPIO.
  • Button input: Button connects between GPIO and GND (or VCC), enable internal pull-up/pull-down to avoid floating.
  • Relay output: Relay coil requires an external driver transistor (e.g., NPN or MOSFET) and a flyback diode (e.g., 1N4148) across the coil to absorb back EMF. GPIO cannot drive a relay directly.
  • Level detection: Input signals must be divided down to 3.3V or below; consider Schmitt trigger or filter capacitor to suppress noise.
  • ESD protection: For long cable inputs (e.g., door sensors), add TVS diodes and series resistors.
  • Connectors: Choose pin headers, terminal blocks, or FPC based on product needs; mind pitch and current rating.
  • Layout watch: Keep inductive loads like relays away from MCU and crystal to avoid EMI.

03 Software flow

1. Select GPIO pins per schematic, avoiding strapping pins (e.g., GPIO0, GPIO2, GPIO12) or confirm their boot state doesn't affect function.

2. Use gpio_config() to set direction, pull-ups/downs, and interrupt type. For buttons, enable internal pull-up (button to GND); for relays, set as push-pull output.

3. For buttons, use polling or interrupts. In the ISR, only set a flag; handle the actual logic in the main loop or a task.

4. Implement software debounce: after detecting a level change, wait 10-20ms and confirm, to avoid mechanical bounce.

5. For relays, add interlock logic: ensure conflicting relays (e.g., forward/reverse) are never on simultaneously.

6. In the main loop, act on button events, e.g., toggle relay state.

7. Error handling: if GPIO config fails, log and retry; if overcurrent is detected (via external circuit), turn off relays and alarm.

8. For low power: before sleep, set GPIOs to appropriate states (e.g., input pull-up or output low) and configure wake-up sources (e.g., EXT1).

04 Core points

  • Strapping pins are not casual buttons. They have special functions at boot (e.g., GPIO0 affects download mode, GPIO12 affects voltage).
  • Never drive a relay directly from GPIO. Use a driver transistor and flyback diode; otherwise you risk damaging the pin or causing system resets.
  • Input signals must meet 3.3V logic levels. 5V signals need level shifting or division.
  • Long cable inputs need ESD and filtering. Otherwise ESD or noise can cause false triggers or damage.
  • Software debounce and interlock are mandatory for product quality. Ignoring them leads to false button presses or relay conflicts.
  • Custom work: I/O map, protection circuitry, key/relay logic.

中文

传感器与外设

GPIO 通用输入输出

按键、继电器、电平检测。产品 IO 的基础课。

传感器与外设 GPIO按键 / 继电器 ESP32 family

官方路径: examples/peripherals/gpio/generic_gpio

01 项目概述

GPIO 是 ESP32 与外部世界交换信号的最基本通道。每个引脚可配置为输入或输出,支持内部上拉/下拉、中断触发(上升沿、下降沿、任意沿)以及开漏模式。

本示例演示如何初始化 GPIO、读取按键状态、控制继电器,并处理中断。它解决的是产品中最常见的 IO 需求:检测外部电平变化、驱动执行器。

典型应用包括:设备面板按键、门磁/报警输入、继电器控制(如灯光、水泵、风扇)、以及简单的电平检测(如电池电压比较器输出)。

GPIO 适合低速、非时序严格的信号。对于需要精确时序的协议(如 WS2812、DHT11 或高速 SPI),应使用 RMT、SPI 或 I2S 等专用外设。

本示例不涉及模拟采样(ADC)、PWM 输出或通信协议,这些由其他示例覆盖。

理解 GPIO 的电气特性和软件配置是产品稳定性的基础,错误的上下拉或驱动电路可能导致误触发或器件损坏。

02 项目硬件描述

  • MCU: ESP32 系列,3.3V 逻辑电平,GPIO 引脚多数为 5V 容忍(见数据手册),但建议避免直接接 5V 信号。
  • 电源: 3.3V 主供电,继电器等大负载需外部电源,不可从 GPIO 取电。
  • 按键输入: 按键一端接 GPIO,另一端接 GND(或 VCC),启用内部上拉/下拉,避免悬空。
  • 继电器输出: 继电器线圈需要外部驱动管(如 NPN 三极管或 MOSFET),并在线圈两端并联续流二极管(如 1N4148)以吸收反向电动势。GPIO 不能直接驱动继电器。
  • 电平检测: 输入信号需分压至 3.3V 以下,并考虑施密特触发器或滤波电容以消除噪声。
  • ESD 保护: 长线输入(如门磁)建议加 TVS 管和串联电阻。
  • 连接器: 根据产品需求选择排针、接线端子或 FPC,注意引脚间距和电流承载。
  • 布局注意: 继电器等感性负载远离 MCU 和晶振,避免电磁干扰。

03 项目软件流程描述

1. 根据原理图选择 GPIO 引脚,避开 strapping 引脚(如 GPIO0、GPIO2、GPIO12 等)或确认其启动状态不影响功能。

2. 使用 gpio_config() 设置方向、上下拉、中断类型。输入按键启用内部上拉(按下接地),继电器输出设为推挽输出。

3. 对于按键,采用轮询或中断方式读取。中断服务程序(ISR)中只置标志位,具体处理放在主循环或任务中。

4. 实现软件防抖:检测到电平变化后延时 10-20ms 再确认,避免机械抖动。

5. 对于继电器,添加互锁逻辑:确保同一时刻不会同时开启冲突的继电器(如正反转)。

6. 主循环中根据按键事件执行相应动作,如切换继电器状态。

7. 错误处理:若 GPIO 配置失败,记录错误并重试;若检测到过流(通过外部电路),关闭继电器并报警。

8. 低功耗场景:进入睡眠前配置 GPIO 为适当状态(如输入上拉或输出低),并设置唤醒源(如 EXT1)。

04 项目核心点

  • Strapping 引脚上电有特殊功能,不能随便当按键。 例如 GPIO0 影响下载模式,GPIO12 影响电压。
  • 继电器不能直驱 GPIO。 必须使用驱动管和续流二极管,否则会损坏引脚或引起系统复位。
  • 输入信号必须满足 3.3V 逻辑电平。 5V 信号需分压或使用电平转换。
  • 长线输入必须加 ESD 和滤波。 否则静电或噪声可能导致误触发或损坏。
  • 软件防抖和互锁是产品级必需。 忽略它们会导致按键误动作或继电器冲突。
  • 可定制: IO 表、保护电路、按键/继电器逻辑。