什么是 GPIO
GPIO (General Purpose Input/Output) is a pin on a microcontroller that you can control with software — set it HIGH (3.3V or 5V) or LOW (0V), or read whether an external device is pulling it HIGH or LOW.
Digital I/O Basics
| Mode | What It Does | Example |
|---|---|---|
| OUTPUT | Pin drives voltage HIGH or LOW | Turn on LED, control relay |
| INPUT | Pin reads external voltage level | Read button press, detect motion |
| INPUT_PULLUP | Pin reads, with internal resistor to VCC | Button without external resistor |
Arduino Example
const int ledPin = 13; // OUTPUT
const int buttonPin = 2; // INPUT_PULLUP
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
if (digitalRead(buttonPin) == LOW) { // pressed (pullup inverts)
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
Voltage Levels
| Board | HIGH = | LOW = | Max Input | Notes |
|---|---|---|---|---|
| Arduino Uno | 5V | 0V | 5V | 5V tolerant |
| ESP32 | 3.3V | 0V | 3.6V | NOT 5V tolerant |
| Raspberry Pi | 3.3V | 0V | 3.6V | NOT 5V tolerant |
| STM32 | 3.3V | 0V | 3.6V (some 5V tolerant) | Check datasheet |
5V signal into 3.3V pin = dead board
Always check voltage levels. ESP32 and Raspberry Pi GPIOs are NOT 5V tolerant. Use a level shifter or voltage divider when connecting 5V sensors.
Common Pitfalls
| Problem | Likely Cause | Fix |
|---|---|---|
| Pin always reads HIGH or LOW | No pull-up/down | Use INPUT_PULLUP or add external resistor |
| Pin does not output expected voltage | Wrong pinMode | Must call pinMode() in setup() |
| LED on ESP32 is very dim | 3.3V logic, LED needs resistor | Use 100-220 ohm resistor for 3.3V |
| GPIO pin dead | Overvoltage or short | The pin is physically damaged; use another |