Using a BJT as a switch
A small NPN transistor such as a 2N2222, BC337 or 2N3904 lets a microcontroller pin switch a relay coil, an LED strip or a small motor. To act as a good switch the transistor must be saturated: fully on, with only about 0.1 to 0.3 V across it. That requires enough base current, set by the base resistor.
The formulas
- Base current needed: I_b = I_c ÷ h_FE(min) × overdrive factor
- Base resistor: R_b = (V_in − V_be) ÷ I_b
The minimum h_FE from the datasheet is used, at the actual collector current, because gain varies widely between parts and with temperature. An overdrive factor of 3 to 10 guarantees saturation; many designers aim for a forced gain I_c ÷ I_b of about 10 to 20.
Example
Switching a 100 mA load from a 5 V pin with h_FE(min) = 100 and 5× overdrive needs 5 mA of base current, so R_b = (5 − 0.7) ÷ 0.005 = 860 Ω. Choosing the next lower standard value, 820 Ω, gives 5.24 mA, a forced gain of 19 and 22.5 mW in the resistor.
Check the drive pin
- Most microcontroller pins supply 10 to 20 mA at most, and much less in total across all pins.
- A 3.3 V pin needs a smaller resistor: (3.3 − 0.7) ÷ 0.005 = 520 Ω, so 470 Ω.
- Above a few hundred milliamps, the base current gets large. A Darlington transistor, a logic-level MOSFET or a driver chip such as the ULN2003 is usually better.
Don’t forget
- Put a flyback diode across relay coils and motors to absorb the voltage spike when the transistor turns off.
- Add a 10 to 100 kΩ pull-down from base to ground so the transistor stays off while the microcontroller boots.
- The transistor dissipates about V_ce(sat) × I_c, small when saturated but large if it is only partly on.
- For a PNP high-side switch, the same calculation applies with the base pulled low.