Drive a relay with a transistor
Switch a bare relay coil from a pin through an NPN transistor, with a base resistor and a flyback diode.
Basic · Intermediate
In a real product: Garage door opener (Smart home): A transistor drives the relay coil, with a flyback diode.
A relay module hides a small circuit: a transistor that switches the coil, and a diode across it. Here you build that circuit yourself from a bare relay, an NPN transistor (2N2222), a 1 kΩ resistor and a 1N4007 diode. This is how any load that needs more current than a pin gives is driven: relays, motors, solenoids, LED strips.
What you'll learn
- Using an NPN transistor as a low-side switch: the load between 5V and the collector, the emitter on GND
- Why the base needs a resistor
- What a flyback diode does, and which way round it goes
How it works
A pin gives about 20 mA; the relay coil needs about 70 mA. Pin 7 drives the transistor's base through R1 (1 kΩ), so only a few milliamps flow from the pin. That small base current lets the transistor conduct from C to E, which pulls the coil's low side (COIL2) to GND: the coil gets 5 V and the contacts move. Pin 7 LOW turns the transistor off and the coil lets go.
Without the resistor the pin would drive the base-emitter junction, a diode, like a short. Delete R1 and wire pin 7 straight to the base: the simulator warns you.
When the transistor turns off, the coil's current cannot stop at once: its voltage spikes far above 5 V and would destroy the transistor. D1 across the coil gives that current a path. Its striped end (C, the cathode) goes to the + side of the coil, so in normal running it does not conduct. Turn the diode round, or remove it, and the simulator warns you.
The relay's first pole (P1) is wired to 5V, so its NO1 contact lights the LED while the coil is energised.
Try this
- Remove D1 and run: read the warning.
- Turn D1 round (A to 5V, C to COIL2) and read the warning.
- Replace the relay with a DC motor (M+ to 5V, M− to the collector) and spin it with
analogWrite.
sketch.ino
// Pin 7 switches a relay through an NPN transistor; the relay's contacts light an LED.
const int COIL = 7;
void setup() {
pinMode(COIL, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(COIL, HIGH); // base current on: the transistor conducts, the coil pulls in
Serial.println("Relay on");
delay(1000);
digitalWrite(COIL, LOW); // the transistor turns off; the diode catches the coil's spike
Serial.println("Relay off");
delay(1000);
}