← all lessons
Components · #7 of 48

Transistors/MOSFETs as Switches

Why GPIO Can't Drive Everything

Why it matters

GPIO pins can only source/sink ~40mA. Motors, high-power LEDs, and relays need more current. Transistors and MOSFETs act as switches controlled by GPIO.

The idea

The Problem

ESP32 GPIO pins have limits:

The Solution: Transistors

Transistors act as switches:

MOSFETs vs BJTs

Common Applications

Demo

Transistors are switches, not demos. Review before designing high-current circuits.

Key takeaways

Going deeper

For motor control, use an H-bridge (4 MOSFETs) to control direction and speed. Always include flyback diodes to protect against back-EMF. For PWM motor control, use MOSFETs with low R_ds(on) to minimize heat. Common logic-level MOSFETs: IRLZ44N, IRF540N (but check V_gs threshold — must be < 3.3V).

Math details

MOSFET as switch:
  When V_gs > V_threshold: MOSFET turns ON (low resistance)
  When V_gs < V_threshold: MOSFET turns OFF (high resistance)

Power dissipation in MOSFET:
  P = I² × R_ds(on)

  Example:
  I = 1A (motor current)
  R_ds(on) = 0.1Ω (typical for logic-level MOSFET)
  P = (1A)² × 0.1Ω = 0.1W (may need heatsink if >0.5W)

Gate current (MOSFET):
  I_gate ≈ 0 (voltage-controlled, negligible current)

  vs BJT base current:
  I_base = I_collector / β (β = current gain, typically 100-300)
  I_base = 1A / 100 = 10mA (needs base resistor!)

Implementation

LLM Prompt: MOSFET Switch Driver

Write Rust code to control a logic-level MOSFET from ESP32 GPIO.
Include: GPIO setup (output mode), turn ON/OFF functions, and safety
check to ensure GPIO is not driving more than 40mA (MOSFET gate current
is negligible, so this is fine). Target: esp-hal crate.

Lab Exercise: High-Power LED

  1. Get logic-level MOSFET (e.g., IRLZ44N)
  2. Connect: GPIO → MOSFET gate, 5V → LED → MOSFET drain, MOSFET source → GND
  3. Program ESP32: GPIO HIGH = LED ON, GPIO LOW = LED OFF
  4. Measure current through LED (should be limited by power supply, not GPIO)
  5. Verify GPIO current is negligible (< 1mA)

full glossary →