Microcontrollers · #13 of 48
5V vs 3.3V Logic + Level Shifting
ESP32 Rules of Engagement
Why it matters
ESP32 GPIO pins are 3.3V logic. Connecting 5V signals can damage the chip. Level shifters convert between voltage levels safely.
The idea
The Problem
ESP32 GPIO pins:
- Maximum input voltage: 3.6V (absolute max)
- Logic HIGH: ~2.4V minimum
- Logic LOW: ~0.8V maximum
Connecting 5V signals can destroy the ESP32!
The Solution: Level Shifters
Level shifters convert between voltage levels:
- Bidirectional: Works for both input and output
- Unidirectional: One direction only (cheaper)
- Voltage divider: Simple but only works one way (input only)
Common Scenarios
- 5V sensor → ESP32: Use level shifter or voltage divider
- ESP32 → 5V device: Use level shifter (ESP32 output is too low)
- 3.3V sensor → ESP32: Direct connection (no shifter needed)
Voltage Divider for Input
Simple but only works one way:
- 5V → 10kΩ → ESP32 input
- ESP32 input → 20kΩ → GND
- Output: 5V × (20k / (10k + 20k)) = 3.33V (safe!)
Demo
Level shifting is about safety, not demos. Review this before connecting any 5V devices.
Key takeaways
- ESP32 GPIO is 3.3V logic — never connect 5V directly
- Level shifters convert between voltage levels safely
- Voltage dividers work for 5V → 3.3V input (one way only)
- Always check sensor/logic voltage before connecting
Going deeper
For bidirectional communication (like I²C), use a dedicated level shifter IC (e.g., TXB0104, PCA9306). For one-way signals, a simple voltage divider or resistor + zener diode works. For production, prefer dedicated level shifter ICs — they’re more reliable and handle edge cases better.
Math details
Voltage divider (5V → 3.3V):
R1 = 10kΩ (top resistor)
R2 = 20kΩ (bottom resistor)
V_out = V_in × (R2 / (R1 + R2))
V_out = 5V × (20k / 30k) = 3.33V
Current through divider:
I = V_in / (R1 + R2) = 5V / 30kΩ = 167µA (negligible)
Power dissipation:
P_R1 = I² × R1 = (0.000167A)² × 10kΩ = 0.28mW
P_R2 = I² × R2 = (0.000167A)² × 20kΩ = 0.56mW
Implementation
LLM Prompt: Level Shifter Interface
Write Rust code for ESP32 to interface with 5V device via level shifter.
Include: voltage divider calculation helper, safety check to warn if
input voltage > 3.6V, and documentation on when to use level shifter
vs voltage divider.
Lab Exercise
- Identify sensor/logic voltage (check datasheet)
- If 5V: design voltage divider or use level shifter
- Build circuit: 5V device → level shifter → ESP32
- Measure voltage at ESP32 input (should be < 3.6V)
- Test communication — verify data integrity
Mastery