← all lessons
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:

Connecting 5V signals can destroy the ESP32!

The Solution: Level Shifters

Level shifters convert between voltage levels:

Common Scenarios

Voltage Divider for Input

Simple but only works one way:

Demo

Level shifting is about safety, not demos. Review this before connecting any 5V devices.

Key takeaways

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

  1. Identify sensor/logic voltage (check datasheet)
  2. If 5V: design voltage divider or use level shifter
  3. Build circuit: 5V device → level shifter → ESP32
  4. Measure voltage at ESP32 input (should be < 3.6V)
  5. Test communication — verify data integrity

full glossary →