Connecting a relay straight to a microcontroller IO pin burns the pin, because the coil draws tens of milliamps while the IO can only source a few. This page covers the transistor switch, the base resistor and the essential freewheel diode.
A relay coil is inductive and its pull-in current is often 30 to 70mA, far above the 4 to 20mA a microcontroller IO can drive. The transistor acts as a switch: the base takes a few milliamps from the IO and the collector handles the coil current, so a small current controls a large one. An NPN with collector to coil low side and emitter to ground turns on with a high IO.
Size the base resistor for hard saturation. For a 12V 40mA coil and a conservative beta of 20, I_B must be at least 2mA. From a 5V IO minus 0.7V U_BE, R_B is about 2kohm. The collector saturation drop is then near 0.2V, so the coil sees about 11.8V and pulls in firmly. Too small a resistor overdrives the IO, too large leaves the transistor linear.
The freewheel diode is mandatory. When the coil de-energises it kicks a reverse spike of tens of volts that destroys the transistor. Place a 1N4007 inverse-parallel across the coil, cathode to supply, so the inductive current has a path. Without it the transistor fails after a few operations. Solder the diode close to the coil.
| Parameter | Value | Note |
|---|---|---|
| Coil voltage | 12 V | match supply |
| Pull-in current | 40 mA | from rating |
| I_B | at least 2 mA | beta 20 margin |
| R_B | 2 kohm | 5 V IO |
| Freewheel | 1N4007 | across coil |
| U_CE sat | about 0.2 V | deep saturation |
This fits 5V, 12V and 24V low-power relays, PLC output expansion and appliance controllers. Measure the coil resistance and rated current first, then compute R_B, and never omit the freewheel diode. Check its direction with a diode test before powering.
The quantities and component characteristics discussed here follow current national standards and the corresponding IEC documents: Low-voltage control design per GB/T 4728; equipment safety IEC 60204-1. Always check the device datasheet and the product design file for ratings and derating.
Locate the issue with the approach above, then confirm with measurements; safety-related circuits must follow the standards and manufacturer requirements.