← all lessons
Microcontrollers · #13 of 20

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!
        <h3>The Solution: Level Shifters</h3>
        Level shifters convert between voltage levels:
        <ul>
          <li><strong>Bidirectional</strong>: Works for both input and output</li>
          <li><strong>Unidirectional</strong>: One direction only (cheaper)</li>
          <li><strong>Voltage divider</strong>: Simple but only works one way (input only)</li>
        </ul>

        <h3>Common Scenarios</h3>
        <ul>
          <li><strong>5V sensor → ESP32</strong>: Use level shifter or voltage divider</li>
          <li><strong>ESP32 → 5V device</strong>: Use level shifter (ESP32 output is too low)</li>
          <li><strong>3.3V sensor → ESP32</strong>: Direct connection (no shifter needed)</li>
        </ul>

        <h3>Voltage Divider for Input</h3>
        Simple but only works one way:
        <ul>
          <li>5V → 10kΩ → ESP32 input</li>
          <li>ESP32 input → 20kΩ → GND</li>
          <li>Output: 5V × (20k / (10k + 20k)) = 3.33V (safe!)</li>
        </ul>

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