← all lessons
Components · #7 of 20

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:
        <h3>The Solution: Transistors</h3>
        Transistors act as <strong>switches</strong>:
        <ul>
          <li><strong>Base/Gate</strong>: Control pin (connected to GPIO)</li>
          <li><strong>Collector/Drain</strong>: High-current path</li>
          <li><strong>Emitter/Source</strong>: Ground/reference</li>
          <li>Small current at base → large current flows through collector</li>
        </ul>

        <h3>MOSFETs vs BJTs</h3>
        <ul>
          <li><strong>BJT (Bipolar Junction Transistor)</strong>: Current-controlled, needs base resistor</li>
          <li><strong>MOSFET</strong>: Voltage-controlled, very low gate current, better for GPIO</li>
          <li>For ESP32, use <strong>logic-level MOSFETs</strong> (turn on at 3.3V)</li>
        </ul>

        <h3>Common Applications</h3>
        <ul>
          <li><strong>Motor control</strong> — H-bridge with MOSFETs</li>
          <li><strong>High-power LEDs</strong> — MOSFET switches</li>
          <li><strong>Relays</strong> — transistor drives relay coil</li>
          <li><strong>Power gating</strong> — turn subsystems on/off</li>
        </ul>

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