Learn
Wiring an NPN Transistor to a Raspberry Pi 4B (GPIO Switching)
Use an NPN transistor (2N2222 or BC547) to let a Raspberry Pi 4B GPIO pin switch a separate power circuit — wiring, Python code, and what to check if the LED won't turn on.
Try this directly in the free Raspberry Pi 4B simulator — no hardware or signup required. New to the GPIO header? Start with the interactive pinout guide.
What you’ll need
- Raspberry Pi 4B
- Breadboard
- NPN Transistor (start with 2N2222 — you'll repeat this test with BC547 afterward, since their pinouts differ)
- LED
- 2 Resistors (one ~220Ω for the LED, one ~1kΩ for the transistor's base)
Step by step
- Drag Raspberry Pi 4B and Breadboard onto the Canvas.
- Drag the NPN Transistor onto the breadboard. Hover over each of its 3 legs to confirm the labels — you should see Base, Collector, Emitter clearly named (don't guess the layout from memory; trust the on-screen labels, since 2N2222 and BC547 don't share the same physical pin order).
- Drag two Resistors onto the breadboard, and set their values: one to 220Ω, one to 1kΩ (click each to select it, adjust the value in the settings panel).
- Drag an LED onto the breadboard.
- Wire the base circuit (the small “control” signal): Connect a GPIO pin (e.g. pin 37) → through the 1kΩ resistor → to the transistor's Base.
- Wire the load circuit (the thing being switched): Connect the Pi's 5V pin → through the 220Ω resistor → to the LED's anode (+). Connect the LED's cathode (−) → to the transistor's Collector. Connect the transistor's Emitter → to a GND pin.
- Go to the Code tab and write a simple test script:
import RPi.GPIO as GPIOimport asynciobasePin = 37GPIO.setmode(GPIO.BOARD)GPIO.setup(basePin, GPIO.OUT)GPIO.output(basePin, 1) # base HIGH -> transistor conducts -> LED should turn ONawait asyncio.sleep(2)GPIO.output(basePin, 0) # base LOW -> transistor stops conducting -> LED should turn OFFawait asyncio.sleep(2)GPIO.cleanup()- Click Start. You should see the LED turn ON for 2 seconds, then OFF for 2 seconds — controlled entirely by the small signal on the Base pin, even though the LED's actual power is coming from the separate 5V line, not the GPIO pin itself. That's the real thing a transistor does: a small control signal gating a separate, larger circuit.
What “working correctly” looks like
- LED follows the base pin exactly: HIGH → LED on, LOW → LED off, no lag or flicker.
- If you swap to BC547, repeat this same test — the wiring stays identical, but double-check the hover labels again first, since the physical leg order is different even though the behavior should be identical.
If something’s wrong
- LED stays off the whole time → check the Collector/Emitter wiring isn't swapped (a transistor only conducts in the correct orientation).
- LED stays on the whole time regardless of the script → check the base resistor is actually wired to a real GPIO pin, not accidentally tied directly to power.
More component tutorials are in Learn.