9 Relays and Solenoids
actuators
relays
solenoids
9.1 Start With the Story
Think of a water valve that opens only when the controller energizes a coil, then snaps shut when power is removed. The software command is small, but the coil current, contact rating, flyback path, and default state decide whether the physical action is safe.
Relays and solenoids are useful because they make clean on/off actions. Treat them as inductive loads with stored energy, not as logic pins, and design the driver and protection before trusting the switch or plunger.
Chapter Roadmap
This chapter moves from safe switching decisions to physical actuator behavior:
- First you separate relay coils, contacts, NO/NC defaults, and GPIO driver limits.
- Then you drive solenoids and flyback-protected coils without asking a GPIO pin to source 50-100 mA.
- Next you compare mechanical relays, SSRs, MOSFETs, valve loads, and contact-wear examples.
- Finally you turn those tradeoffs into safety rules, quizzes, and wiring checks.
Checkpoints recap the design decisions as you go, and deeper coil/contact calculations are optional on a first pass.
Key Concepts
- Relay: An electromechanical switch where a small control current through a coil creates a magnetic field that physically moves contacts to open or close a separate high-power circuit; provides complete electrical isolation between control and load circuits
- Normally Open (NO) Contact: Relay contact that is open (circuit broken) when the relay coil is de-energized; closes when the coil is energized; default state is off — the load is unpowered unless the relay is actively activated
- Normally Closed (NC) Contact: Relay contact that is closed (circuit connected) when the relay coil is de-energized; opens when the coil is energized; default state is on — the load is powered unless the relay is actively activated
- Solid State Relay (SSR): A relay using semiconductor switches (triacs, SCRs, MOSFETs) instead of mechanical contacts; no moving parts, faster switching, longer life, silent operation; optically isolated input; suitable for AC load control
- Solenoid: An electromechanical device where current through a coil creates a magnetic field pulling a ferromagnetic plunger; converts electrical energy to linear mechanical motion; used in door locks, valves, vending machines, and pneumatic systems
- Flyback Diode: A diode placed across a relay coil or solenoid in reverse bias; suppresses the voltage spike generated when coil current is switched off (inductive kickback); prevents transistor or MOSFET drain-source breakdown
- Relay Coil Voltage and Current: The control-side voltage and current required to energize the relay; common values: 5 V at 70-90 mA or 12 V at 50-70 mA; exceeds typical GPIO limits so transistor driver circuits are always required
- Relay Contact Ratings: The maximum voltage and current the relay’s output contacts can safely switch; expressed as AC amperes at 250 V or DC amperes at 30 V; always derate by 50% for reliability — a 10 A relay should be used for loads up to 5 A continuous
Learning Objectives
After completing this chapter, you will be able to:
- Explain relay operation principles and interpret relay specifications
- Interface relays safely with microcontrollers using transistor drivers
- Drive solenoids for linear actuation in locks, valves, and latches
- Implement flyback diode protection for inductive loads
- Design safe high-voltage switching circuits with proper isolation
- Select solid-state relays (SSR) for silent, high-speed switching applications
For Beginners: Relays and Solenoids
A relay is like having a small child flip a giant light switch – a tiny signal from your microcontroller controls a much bigger electrical load. This lets a low-power chip safely turn on things like heaters, pumps, or lights that need far more electricity. A solenoid works similarly but produces a pushing or pulling motion, like an electronic door latch that locks or unlocks when powered.
9.2 Relay Fundamentals
First separate the two sides of the relay: the coil your controller energizes, and the contacts that switch the real load.
Relays are electrically-operated switches that allow low-power circuits (microcontrollers) to control high-power loads (motors, heaters, lights).
Key Benefits:
- Electrical isolation: Complete separation between control and load circuits
- High current switching: 10A, 20A, or more
- AC and DC loads: Can switch both types
- Low control current: Typically 20-100mA coil current
9.2.1 Relay Specifications
| Parameter | Typical Values | What It Means |
|---|---|---|
| Coil voltage | 3.3V, 5V, 12V, 24V | Voltage needed to activate relay |
| Coil current | 50-100mA | Current drawn by coil (needs driver!) |
| Contact rating | 10A @ 250VAC | Maximum load current and voltage |
| Contact type | SPST, SPDT, DPDT | Number of poles and throws |
Interactive: Can Your GPIO Drive This Relay?
9.2.2 Relay Control Circuit
Never Connect Relay Coil Directly to GPIO!
Most relay coils draw 50-100mA, far exceeding the 20-40mA GPIO limit. Always use a transistor driver!
// Relay control with transistor driver
#define RELAY_PIN 25
void setup() {
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW); // Relay OFF (normally open)
}
void loop() {
// Turn relay ON (closes normally-open contact)
digitalWrite(RELAY_PIN, HIGH);
Serial.println("Relay ON - Load powered");
delay(3000);
// Turn relay OFF
digitalWrite(RELAY_PIN, LOW);
Serial.println("Relay OFF - Load unpowered");
delay(3000);
}9.2.3 Relay Module Wiring
Most relay modules include the transistor driver and flyback diode:
| ESP32 / Power | Relay module | Load connection | Purpose |
|---|---|---|---|
| GPIO25 | IN | - | Low-current control signal |
| ESP32 GND | GND | - | Common reference for the module |
| 3.3 V or 5 V | VCC | - | Relay module logic/coil supply |
| - | COM | Load common | Switch input terminal |
| - | NO | Load hot when relay is ON | Normally open output |
| - | NC | Load hot when relay is OFF | Normally closed output |
Checkpoint: Relay Interfaces
You now know:
- A relay coil that needs 50-100 mA exceeds a typical GPIO limit, so the GPIO should command a transistor or MOSFET driver.
- NO contacts default off, while NC contacts default on; the safest default depends on what failure state the load can tolerate.
- Relay contacts and relay coils are separate ratings: a 5 V or 12 V coil can switch a much higher-voltage load only when the contact rating allows it.
9.3 Solenoid Control
Once the relay pattern is clear, a solenoid is the same electrical problem with motion instead of contacts.
Solenoids provide linear push/pull motion for locks, valves, and latches.
Characteristics:
- Fast response (5-50ms)
- Binary operation (on/off only)
- High inrush current
- Requires flyback protection
#define SOLENOID_PIN 26
void setup() {
pinMode(SOLENOID_PIN, OUTPUT);
}
void loop() {
// Activate solenoid (pull/push)
Serial.println("Activating solenoid lock...");
digitalWrite(SOLENOID_PIN, HIGH);
delay(1000);
// Release solenoid
Serial.println("Releasing solenoid lock...");
digitalWrite(SOLENOID_PIN, LOW);
delay(3000);
}
// Smart lock example
void unlockDoor() {
digitalWrite(SOLENOID_PIN, HIGH);
Serial.println("Door unlocked");
// Auto-lock after 5 seconds
delay(5000);
digitalWrite(SOLENOID_PIN, LOW);
Serial.println("Door locked");
}9.4 Flyback Protection
9.5 Critical: Inductive Kickback Protection
Relay coils and solenoids are inductors. When power is cut, the collapsing magnetic field generates a high voltage spike (potentially 100V+ from a 12V supply) that can destroy transistors and microcontrollers!
Putting Numbers to It
A relay coil with inductance \(L = 100\) mH carrying 80mA is switched off in 1 μs. The induced voltage is \(V = -L \frac{dI}{dt} = -0.1 \times \frac{0.08}{0.000001} = -8000\) V (negative indicates reverse polarity). This spike punches through the transistor’s 60V breakdown rating instantly. A flyback diode clamps this to \(V_{diode} \approx 0.7\) V, dissipating the energy safely as \(E = \frac{1}{2}LI^2 = \frac{1}{2} \times 0.1 \times 0.08^2 = 0.32\) mJ over \(\sim\) 10 ms, well within the diode’s rating.
Interactive: Inductive Kickback Voltage Calculator
Required Protection Circuit:
| Connection | Component | Why it matters |
|---|---|---|
| GPIO to transistor/MOSFET gate/base | Driver stage | GPIO commands the load without supplying coil current directly |
| Supply through relay coil to driver | Relay coil | The coil receives current from the actuator supply |
| Reverse-biased across the coil | Flyback diode | Provides a safe path for stored magnetic energy when the driver turns off |
| Driver source/emitter to ground | Common ground | Completes the control and load current paths |
Diode specs: voltage rating above the supply voltage, current rating at least equal to coil current; use 1N4007 for many relay coils and 1N5819 Schottky diodes for faster motor freewheel paths.
Checkpoint: Coil Energy
You now know:
- Relays and solenoids are inductive loads, so turn-off energy needs a deliberate path.
- The chapter’s 100 mH, 80 mA coil stores 0.32 mJ, but an ideal 1 us turn-off can imply an 8000 V spike.
- A flyback diode protects the driver, while snubbers, MOVs, or TVS parts handle different contact or AC-load spike paths.
9.6 Solid-State Relays (SSR)
With coil protection handled, the next choice is which switching technology best matches the load and cycle pattern.
For silent, high-speed, and maintenance-free switching, use solid-state relays.
Advantages over mechanical relays:
- No mechanical wear
- Silent operation
- Faster switching (microseconds vs milliseconds)
- No contact bounce
- Works with PWM for heater control
Disadvantages:
- Voltage drop across output (1-2V)
- Requires heatsink for high loads
- More expensive
- No electrical isolation (optocoupler-type has some isolation)
// SSR for heater PWM control
#define SSR_PIN 27
void setup() {
// SSR can handle PWM for proportional heating
ledcSetup(0, 1, 8); // 1 Hz (1 cycle/second), 8-bit resolution (0-255)
ledcAttachPin(SSR_PIN, 0);
}
void setHeaterPower(int percent) {
// 0-100% maps to 0-255
int duty = map(percent, 0, 100, 0, 255);
ledcWrite(0, duty);
}9.7 Valve Control
Solenoid valves control fluid flow in irrigation, HVAC, and industrial systems.
#define VALVE_PIN 25
#define FLOW_SENSOR_PIN 34
void setup() {
pinMode(VALVE_PIN, OUTPUT);
pinMode(FLOW_SENSOR_PIN, INPUT);
digitalWrite(VALVE_PIN, LOW); // Valve closed
}
// Water for specified duration
void water(int seconds) {
Serial.print("Watering for ");
Serial.print(seconds);
Serial.println(" seconds");
digitalWrite(VALVE_PIN, HIGH); // Open valve
delay(seconds * 1000);
digitalWrite(VALVE_PIN, LOW); // Close valve
Serial.println("Watering complete");
}
// Water until flow sensor detects specified volume
void waterVolume(float liters) {
float flowRate; // Liters per minute
float totalVolume = 0;
digitalWrite(VALVE_PIN, HIGH);
while (totalVolume < liters) {
// Read flow sensor (pulse counting)
// This is simplified - real implementation needs interrupt
flowRate = readFlowSensor();
totalVolume += flowRate / 60.0; // Convert to liters/second
delay(1000);
Serial.print("Volume: ");
Serial.print(totalVolume);
Serial.print(" / ");
Serial.print(liters);
Serial.println(" L");
}
digitalWrite(VALVE_PIN, LOW);
}9.8 Design Example: Smart Sprinkler Controller
A Wi-Fi-connected irrigation controller is a useful relay and solenoid design example because it must switch many outdoor valve coils, survive wiring faults, and avoid nuisance noise in a home installation. The exact component choices vary by product, but the engineering tradeoffs are stable.
The engineering challenge: Each irrigation zone uses a 24V AC solenoid valve drawing 250-500 mA inrush current. The controller must switch up to 16 zones, survive outdoor temperature extremes (-20C to +50C), and last 10+ years with daily cycling.
Key design decisions:
| Decision | Choice | Rationale |
|---|---|---|
| Switching element | Triac or other solid-state output per zone | At 2 cycles/day x 365 days x 10 years = 7,300 cycles total, mechanical relays may meet cycle life, but solid-state switching removes audible clicks and contact wear |
| Flyback protection | TVS diode + varistor per channel | Solenoid inductive kick at 24V AC can reach 80-100V. Standard diodes are too slow for AC loads; TVS diodes clamp spikes in nanoseconds |
| Zone current sensing | 0.1-ohm shunt resistor per channel | Detects stuck-open valves (current drops to zero) and short circuits (current exceeds 1A), enabling the app to alert homeowners to broken sprinkler heads |
| Power supply | 24V AC transformer (user-supplied, standard irrigation) | Avoids UL/CE certification complexity of including a mains power supply in the product enclosure |
Lesson for IoT designers: solid-state switching is not always chosen for raw electrical superiority. It can be chosen because silent operation, sealed enclosures, and reduced contact wear matter more than the lowest component count.
12V Motor Relay Sizing
Scenario: You are designing an IoT greenhouse controller that switches a 12V DC ventilation fan on and off based on temperature readings. The fan motor is rated for 5A continuous operation. How do you select the appropriate relay?
Step 1: Measure actual inrush current
DC motors draw 5-8× their rated current for 50-200ms during startup as the rotor accelerates from standstill. Using a current clamp meter on the fan:
- Steady-state current: 5.2A (matches datasheet)
- Inrush current (first 100ms): 28A peak
Step 2: Check relay contact ratings
You are evaluating two relay options:
| Relay Option | Continuous Rating | Inrush Rating | Mechanical Life | Design Note |
|---|---|---|---|---|
| Relay A | 10A @ 12V DC | 30A for 100ms | 100,000 cycles | Inrush rating is stated |
| Relay B | 10A @ 12V DC | Not specified (assume only 1.5× continuous = 15A for screening) | 100,000 cycles | Inrush rating is missing |
Step 3: Calculate safety margin
Relay A: 30A inrush rating / 28A measured = 1.07× margin (minimal but acceptable)
Relay B: 15A assumed inrush / 28A measured = 0.54× margin (undersized – contacts will arc and weld!)
Step 4: Verify mechanical life against application
The greenhouse controller switches the fan 4 times per day (heating cycles):
- Cycles per year: 4 × 365 = 1,460
- Years to 100,000 cycles: 100,000 / 1,460 = 68.5 years
Both relays exceed the required lifespan, but contact degradation from inrush current will shorten this significantly if undersized.
Step 5: Decision
Select Relay A despite its higher part cost and similar continuous-current headline. Relay B will fail prematurely if its real inrush capability is below the measured startup current.
Alternative approach: Soft-start circuit
To use a relay with weaker inrush capability safely, add a soft-start circuit using a power resistor and bypass relay:
+12V ---[10Ω 10W Resistor]---[Bypass Relay]--- Motor+
|
GND
Control sequence:
1. Close main relay (current limited by resistor to 12V/10Ω = 1.2A)
2. Wait 200ms (motor reaches 80% speed)
3. Close bypass relay (shorts resistor, full current flows)
4. Total inrush current seen by main relay: 1.2A (within rating!)
Tradeoff comparison:
- Direct switching: fewer parts, but the relay must tolerate the measured inrush current directly.
- Soft-start: more parts and firmware sequencing, but the main relay sees only the current-limited startup path before the bypass closes.
In a product design review, this becomes a reliability and manufacturing tradeoff rather than a simple “cheaper relay” decision.
Key takeaway: Always measure real inrush current with a scope or current clamp. Relay datasheets often omit inrush ratings, leading to premature contact failure in motor-switching applications.
Checkpoint: Switching Choices
You now know:
- SSRs switch silently and avoid mechanical wear, but their 1-2 V output drop can become heat at high current.
- A 5 A fan with a 28 A, 100 ms inrush needs contact ratings that cover startup, not just steady-state current.
- The sprinkler example chooses solid-state outputs because 7,300 cycles, outdoor wiring, and quiet operation matter as much as raw part count.
9.9 Relay Selection: Decision Framework
Complete Decision Framework: Relay vs SSR vs MOSFET
| Selection Criteria | Mechanical Relay | Solid-State Relay (SSR) | MOSFET Switch |
|---|---|---|---|
| Switching speed | 5-15 ms (mechanical delay) | 1-100 µs (zero-cross: half-cycle delay) | 10-100 ns (instant) |
| On-state voltage drop | <100 mV (contact resistance ~50 mΩ) | 1.0-1.6 V (SCR/TRIAC forward drop) | 10-200 mV (Rds(on) dependent) |
| Off-state leakage | Zero (galvanic isolation) | 0.1-1 mA (semiconductor leakage) | <1 µA (negligible) |
| Electrical isolation | Full galvanic (>1 kV typical) | Optocoupler (2.5-4 kV) | None (requires isolated gate drive for high-side) |
| Switching frequency max | 1-5 Hz (contact bounce, mechanical wear) | 60 Hz (AC zero-cross) to 1 kHz (DC) | 100 kHz+ (limited by gate drive and switching loss) |
| Power dissipation (10A load) | 0.5 W (I²R in coil + contacts) | 10-16 W (1.6V drop × 10A) – requires heatsink | 0.2-1 W (depends on Rds(on)) |
| Audible noise | Loud click on every operation | Silent | Silent |
| Mechanical lifespan | 10⁵-10⁷ cycles (contact wear) | Unlimited (no moving parts) | Unlimited (no moving parts) |
| Failure mode | Contacts weld closed OR burn open | Usually fails short (conducting) | Usually fails short (Drain-Source) |
| Relative cost | Low to moderate | Moderate to high | Low for DC switching |
| PWM suitability | No (arcing at contacts) | Limited (zero-cross SSR: max 60 Hz; DC SSR: yes) | Excellent (high-frequency PWM) |
| Typical IoT application | HVAC control, irrigation valves, lights (infrequent switching) | Heater control (PWM or proportional), high-cycle lighting | Motor speed control, LED dimming, DC load switching |
Decision tree for IoT actuator control:
- Switching AC mains (120V/240V)?
- Yes → Mechanical relay OR SSR (MOSFET requires complex bridge circuit for AC)
- No (DC only) → Proceed to step 2
- Switching frequency >10 times per minute?
- Yes → SSR (if AC) OR MOSFET (if DC). Mechanical relay wears out too quickly.
- No → Proceed to step 3
Interactive: Relay Lifespan Calculator
- Need PWM control (heater, motor speed, LED dimming)?
- Yes → MOSFET (for DC) OR zero-cross SSR (for AC resistive heating only)
- No → Proceed to step 4
- Load current <2A AND DC voltage <50V?
- Yes → MOSFET (cheapest, lowest power loss)
- No → Proceed to step 5
- Need electrical isolation (safety-critical or outdoor installation)?
- Yes → Mechanical relay OR SSR with optocoupler
- No → MOSFET acceptable
- Is audible click acceptable?
- No (bedroom, library, quiet environment) → SSR or MOSFET
- Yes → Mechanical relay (cheapest for high current)
Worked example: Smart irrigation controller switching 8 zones of 24V AC solenoid valves (0.4A each), 2 cycles per day.
- AC load → eliminates MOSFET
- Low frequency (2 cycles/day) → both relay and SSR acceptable
- Click noise → silent switching may be preferred for controllers installed near living spaces
- Isolation → 24V AC is low-voltage but isolation still preferred for outdoor installation → SSR with optocoupler
Choice: Triac-based SSR or triac output stage with optocoupler input. It may cost more than mechanical relays, but it can remove audible clicks and contact-maintenance concerns.
Relay Arc Erosion in Inductive Loads
The mistake: An IoT smart plug design uses a standard 10A mechanical relay, rated for resistive loads, to switch a vacuum cleaner drawing 8A in normal operation. After repeated switching cycles, the relay contacts weld shut, leaving the vacuum permanently on and creating a fire hazard.
Why it happened: The 10A relay rating assumes resistive loads (heaters, incandescent lights). Inductive loads (motors, transformers, solenoid valves) create voltage spikes and arcing during switching that erode contacts far faster than resistive loads.
Physics of contact arcing:
When switching off an inductive load (motor winding = inductor), the collapsing magnetic field generates a voltage spike following V = -L × (di/dt). A vacuum motor with 50 mH inductance switched off in 5 ms produces:
V_spike = -(50×10⁻³ H) × (8A / 5×10⁻³ s) = -80V spike
With a 120V AC supply, the instantaneous voltage across the relay contacts can reach 120V + 80V = 200V just as the contacts separate. At 200V and 8A, the arc power is 1,600W concentrated in a microscopic contact area, vaporizing metal from the contact surfaces.
Measured contact degradation:
| Switching Cycles | Contact Surface Condition | Contact Resistance | Risk |
|---|---|---|---|
| 0 (new relay) | Smooth silver surface | 50 mΩ | None |
| 100 cycles | Light pitting visible | 75 mΩ | Low |
| 300 cycles | Deep pits, material transfer between contacts | 150 mΩ | Medium (heating during operation) |
| 500 cycles | Contacts welded together (metal vapor re-solidified) | N/A (stuck closed) | Fire hazard |
Relay derating for inductive loads:
Relay manufacturers specify derating factors but often bury them in footnotes:
| Load Type | Derating Factor | Effective Current Rating for 10A Relay |
|---|---|---|
| Resistive (heater, incandescent) | 1.0× | 10A |
| Inductive (motor, L/R > 5ms) | 0.3-0.5× | 3-5A |
| Lamp (inrush 10-15× steady state) | 0.1× | 1A |
For the 8A vacuum motor, the relay should be rated for 8A / 0.4 = 20A minimum.
Interactive: Relay Derating Calculator for Inductive Loads
Solutions:
Properly size relay: Use 20A relay for 8A inductive load (derate by 2.5×)
Add RC snubber across contacts:
Relay contacts in parallel with: - 100Ω resistor in series with 0.1µF 250V capacitor - Absorbs inductive spike energy, extends relay life 5-10× - Adds a small passive network per relayAdd metal-oxide varistor (MOV) across load:
MOV clamps voltage spike to <200V - Choose a voltage rating and energy rating for the load and supply - Protects relay from high-voltage arcing - Must be rated for the expected surge energyUse SSR (no contacts to erode):
- Solid-state relay handles inductive loads without degradation
- Usually higher part cost than a mechanical relay, but eliminates contact-wear failure
Real-world failure pattern: smart plugs and appliance controllers that switch motors, transformers, or fan heaters can fail with welded relay contacts when the contact rating is chosen from steady-state current alone. The durable fix is not a larger-looking headline rating by itself; it is proper derating, contact suppression, thermal protection, and a fail-safe load state.
Key takeaway: ALWAYS derate mechanical relays by 2-3× for inductive loads. Add snubber circuits to extend relay life. For high-cycle applications or motor loads, use SSRs despite higher cost.
9.10 Safety Considerations
The design examples end in the same place: what happens when the switch fails, arcs, overheats, or is wired into mains equipment.
9.11 High Voltage Safety
When working with mains voltage (120V/240V AC):
- Use properly rated relay contacts (check current AND voltage rating)
- Ensure electrical isolation between low-voltage and mains circuits
- Use enclosed, insulated enclosures for all high-voltage connections
- Install fuses or circuit breakers on the mains side
- Follow local electrical codes (NEC, IEC, etc.)
- Consider hiring a licensed electrician for permanent installations
For Kids: Meet the Actuator Crew!
“Click!” went Relay Ray, snapping his switch. “I just turned on a whole house heater – and Max didn’t even break a sweat!”
“How does that work?” asked Lila the LED. “Max can barely power me, and I only need a tiny bit of electricity!”
“That’s my magic trick!” said Relay Ray proudly. “Max sends me a teeny-tiny signal – like whispering in my ear. When I hear it, I CLICK my big switch closed, and the heater gets its power from the wall outlet. Max never touches the dangerous electricity at all!”
“It’s like a light switch,” explained Max the Microcontroller. “Your finger uses very little energy to flip the switch, but it controls a bright ceiling light. I’m the finger, and Ray is the switch!”
Solenoid Sally pushed forward with a “THUNK!” “And I do the pushing! Need to lock a door? THUNK – I push the bolt closed! Need to open a water valve? THUNK – I pull it open!”
“But be careful!” warned Bella the Battery. “When Ray or Sally turn off, their coils create a nasty electric zap – like a static shock but WAY bigger! That’s why we always put a special diode next to them. The diode is like a safety net that catches the zap before it hurts Max.”
“Safety first!” everyone agreed.
Checkpoint: Failure Modes
You now know:
- Welded contacts can leave a heater or motor permanently powered, so fuses, breakers, enclosures, and fail-safe defaults are part of the actuator design.
- An 8 A inductive load may require about a 20 A relay after derating by 0.4 and adding margin.
- A 2 A, 200 ms lock solenoid pulse can support about 22,500 theoretical battery cycles before practical derating and standby load.
9.12 Deep Dive: Coil Drivers, Contact Stress, and Kickback Paths
Relays and solenoids let a tiny control signal command a larger electrical or mechanical action. A relay coil moves contacts that switch a separate load circuit. A solenoid coil pulls a plunger to move a latch, valve, or striker. Both are inductive coils, so switching them off releases stored magnetic energy; the driver survives only if that energy has a deliberate path.
The first sizing check is current. Suppose a 5 V relay coil is marked 80 mA. The coil resistance is approximately 5 V / 0.08 A = 62.5 ohm, and the coil consumes 5 V x 0.08 A = 0.4 W while energized. An ESP32 GPIO pin is a logic signal, not a coil supply. The safe pattern is GPIO to transistor or logic-level MOSFET, relay coil to its own supply, and a diode across the coil. The GPIO then supplies only base current or gate charge while the actuator supply provides coil power.
With a low-side NPN transistor driving that 5 V, 80 mA coil, choose the transistor for more than 80 mA collector current, then drive it into saturation with a conservative forced gain. If you assume forced gain of 10, base current is about 80 mA / 10 = 8 mA. From a 3.3 V GPIO and a 0.7 V base-emitter drop, a base resistor near (3.3 - 0.7) / 0.008 = 325 ohm is implied; a nearby standard value such as 330 ohm is the right order. A logic MOSFET often wastes less GPIO current, but the same flyback diode is still needed because the coil energy has not disappeared.
Contact ratings are a separate problem from coil ratings. The same 5 V, 80 mA coil might switch a 12 V pump at 2 A, a 24 V valve at 0.4 A, or a mains lamp. If a contact says 10 A resistive, that does not automatically mean 10 A motor or transformer load. A motor that runs at 4 A may draw 5 x 4 = 20 A for a short startup interval, and an inductive load can arc as the contacts open. For design margin, a 4 A inductive load is often treated as needing a 10 A to 15 A contact class, plus a snubber, MOV, or other suppression matched to the load.
Solenoids add a pulse-energy budget. A 12 V latch solenoid drawing 1.2 A for 200 ms uses 12 x 1.2 x 0.2 = 2.88 J per actuation. Ten actuations per day consume only 28.8 J/day in the coil, but the 1.2 A pulse can still sag a small battery or reset a controller if wiring resistance and bulk capacitance are ignored. Relays and solenoids look binary in software, but their current, stored energy, contact stress, and fail-safe state are analog design constraints.
Switching technology changes the loss and failure tradeoff. A mechanical relay with 50 milliohm contact resistance at 5 A dissipates I^2R = 25 x 0.05 = 1.25 W at the contacts. A triac-output AC SSR may drop about 1.6 V, so at the same 5 A it dissipates 1.6 x 5 = 8 W and needs a thermal path. The SSR wins when silence, high cycle life, or zero-cross AC switching matters; the mechanical relay wins when true open-circuit isolation, low leakage, and low on-state loss matter. For DC loads that need fast PWM, a MOSFET switch is usually the better actuator driver than either relay type.
Finally separate coil suppression from contact suppression. A diode across a DC relay coil protects the transistor. An RC snubber or MOV across relay contacts protects the contacts when the load itself is inductive. Putting the diode in the contact path or across the wrong terminals can leave the real fault untouched, so trace the current path during both on-time and turn-off before approving the wiring.
9.12.1 Under the Hood: Inductive Kickback
An inductor opposes changes in its current, and its voltage is V = L x (di/dt). When a transistor switches a relay or solenoid coil off, the current tries to stop almost instantly, so di/dt is enormous and the coil generates a large reverse voltage spike. That spike punches through the switching transistor or microcontroller pin unless a clamp gives the current a safer path.
The stored energy is easy to estimate. A relay coil with L = 100 mH and I = 80 mA stores 0.5 x 0.1 x 0.08^2 = 0.00032 J, or 0.32 mJ. That energy is small, but if current is forced from 80 mA to zero in 1 microsecond, the ideal inductor voltage is 0.1 x 0.08 / 1e-6 = 8000 V. Real parasitic capacitance, arcing, and transistor avalanche limit the voltage before that ideal value, but without a clamp the circuit chooses a destructive voltage high enough to keep current flowing.
A diode clamp changes the time scale. With the same 5 V, 80 mA coil, coil resistance is about 62.5 ohm. When a diode conducts, current circulates through the coil and diode while the magnetic field collapses. The clamp voltage is only about 0.7 V plus winding resistance effects, so the driver sees a safe voltage, but the relay releases more slowly because current decays gently. If a solenoid lock must release quickly, designers sometimes clamp at a higher voltage using a diode plus Zener or a TVS diode; the higher clamp dissipates the same stored energy faster while staying below the transistor’s safe rating.
9.13 Summary
Relays and solenoids are simple to command but unforgiving to drive incorrectly. Both require a driver stage between GPIO and coil, both need flyback protection, and relay contact choice must be checked against the load type, voltage, current, and desired fail-safe state.
Key Takeaway
Relays provide essential electrical isolation between low-power microcontrollers and high-power loads, while solenoids enable fast linear actuation for locks and valves. Both are inductive loads that absolutely require flyback diode protection. For high-voltage AC switching, always use properly rated components, enclosed wiring, fuses, and consult a licensed electrician for permanent installations.
9.14 Knowledge Check
9.15 Concept Relationships
| Concept | Relates To | Connection Type |
|---|---|---|
| Flyback Protection | Actuator Safety | Diodes clamp inductive voltage spikes |
| Electrical Isolation | High-Voltage Safety | Relays separate low-voltage control from AC mains |
| Inductive Loads | DC Motors | Motors require same flyback protection as relays |
| SSR vs Mechanical | Actuator Classifications | Decision tree for switching technology |
9.16 See Also
- Actuator Safety - Flyback diodes and fail-safe design
- Solenoid Valves - Linear actuation for locks and valves
- SSR Applications - When to use solid-state relays
- High-Voltage Wiring - Electrical codes and safety
- DC Motors - Inductive kickback protection
Common Pitfalls
1. Driving Relay Coil Directly from GPIO
Relay coils typically require 50-100 mA to energize, far exceeding the 20-40 mA GPIO limit. Connecting a relay coil directly to GPIO causes excessive current draw that permanently degrades or destroys the GPIO output driver. Always use a NPN transistor (2N2222, BC337) or MOSFET with a base/gate resistor to drive relay coils from a separate power source.
2. Omitting Flyback Diode on Relay or Solenoid Driver
When the transistor cuts coil current, the relay/solenoid’s inductance generates a voltage spike of 10-100 V above the supply rail. Without a flyback diode (placed reverse-biased across the coil, cathode to positive supply), this spike destroys the driver transistor. This is the most common relay wiring mistake and a non-negotiable requirement.
3. Connecting SSR Output to DC Load Without Checking SSR Type
AC solid state relays switch using triac or SCR devices that only work correctly with AC loads. Connecting an AC SSR to a DC load causes it to never turn off (or never turn on) due to the zero-crossing detection circuitry. Use a DC-rated SSR (using MOSFET output) for DC loads such as 12 V motors, heaters, and LED strips.
4. Check NC Relay Default State
NC relay contacts are connected (load powered) when the relay is de-energized, making them appear safe for fail-safe applications. However, if the coil burns out or the driver fails, the relay remains de-energized and NC contacts remain closed — potentially leaving a load permanently powered. Design fail-safe systems carefully, considering which failure mode is safer for your specific application.
9.17 What’s Next
| If you want to… | Read this |
|---|---|
| Understand PWM control fundamentals for motor and dimmer control | PWM Control |
| Learn about DC motor control for higher-power motor applications | DC Motors |
| Explore actuator safety circuits and protection design | Actuator Safety |
| Practice relay and solenoid control in hands-on labs | Actuator Labs |
