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:
- Source: ~40mA (driving HIGH)
- Sink: ~28mA (driving LOW)
- Motors need hundreds of milliamps
- High-power LEDs need 100mA+
The Solution: Transistors
Transistors act as switches:
- Base/Gate: Control pin (connected to GPIO)
- Collector/Drain: High-current path
- Emitter/Source: Ground/reference
- Small current at base → large current flows through collector
MOSFETs vs BJTs
- BJT (Bipolar Junction Transistor): Current-controlled, needs base resistor
- MOSFET: Voltage-controlled, very low gate current, better for GPIO
- For ESP32, use logic-level MOSFETs (turn on at 3.3V)
Common Applications
- Motor control — H-bridge with MOSFETs
- High-power LEDs — MOSFET switches
- Relays — transistor drives relay coil
- Power gating — turn subsystems on/off
Demo
Transistors are switches, not demos. Review before designing high-current circuits.
Key takeaways
- GPIO pins have current limits (~40mA source, ~28mA sink)
- Transistors/MOSFETs act as switches controlled by GPIO
- MOSFETs are voltage-controlled and better for GPIO than BJTs
- Use logic-level MOSFETs for 3.3V ESP32 GPIO
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
- Get logic-level MOSFET (e.g., IRLZ44N)
- Connect: GPIO → MOSFET gate, 5V → LED → MOSFET drain, MOSFET source → GND
- Program ESP32: GPIO HIGH = LED ON, GPIO LOW = LED OFF
- Measure current through LED (should be limited by power supply, not GPIO)
- Verify GPIO current is negligible (< 1mA)
Mastery