9 Relays and Solenoids
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.1 Relay Fundamentals
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.1.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.1.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.1.3 Relay Module Wiring
Most relay modules include the transistor driver and flyback diode:
ESP32 Relay Module High-Power Load
GPIO25 ------> IN (control)
GND ----------> GND
3.3V/5V -----> VCC
COM ----------------> Load common
NO (normally open) -> Load hot (when relay ON)
NC (normally closed)-> Load hot (when relay OFF)
9.2 Solenoid Control
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.3 Flyback Protection
9.4 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:
GPIO --> [Transistor/MOSFET] --+-- Relay Coil --+
| |
+-- [Diode] <----+
|
GND
Diode specs:
- Voltage rating > supply voltage
- Current rating >= coil current
- 1N4007 for relays, 1N5819 Schottky for motors
9.5 Solid-State Relays (SSR)
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.6 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.7 Real-World Case Study: Rachio Smart Sprinkler Controller
Rachio, a US-based smart irrigation company, designs Wi-Fi-connected sprinkler controllers that manage solenoid valves across 8 or 16 zones. Their design decisions illustrate relay and solenoid engineering tradeoffs in a mass-market product (over 1 million units sold as of 2023).
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 (solid-state) per zone, not mechanical relay | At 2 cycles/day x 365 days x 10 years = 7,300 cycles total – mechanical relays would survive, but triacs eliminate the audible click that bothers homeowners with controllers mounted near bedroom walls |
| 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: Rachio chose solid-state switching not for electrical superiority but for user experience (silent operation). The additional cost per zone ($0.30 for triac vs $0.15 for relay) was justified by eliminating the number-one customer complaint in their competitor’s product reviews: “clicking noise at 5 AM when the sprinklers turn on.”
Worked Example: Sizing a Relay for a 12V DC Motor with Inrush Current
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 Model | Continuous Rating | Inrush Rating | Mechanical Life | Cost |
|---|---|---|---|---|
| Omron G5LE-1 | 10A @ 12V DC | 30A for 100ms | 100,000 cycles | $1.20 |
| Songle SRD-05VDC | 10A @ 12V DC | Not specified (assume 1.5× continuous = 15A) | 100,000 cycles | $0.35 |
Step 3: Calculate safety margin
G5LE-1: 30A inrush rating / 28A measured = 1.07× margin (minimal but acceptable)
SRD-05VDC: 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 Omron G5LE-1 despite the $0.85 cost premium. The Songle relay will fail prematurely due to contact welding from inrush current exceeding its capacity.
Alternative approach: Soft-start circuit
To use the cheaper Songle relay 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!)
Cost comparison:
- Direct switching: 1× G5LE-1 = $1.20
- Soft-start: 1× SRD-05VDC ($0.35) + 1× bypass relay ($0.35) + 10Ω resistor ($0.15) = $0.85 (saves $0.35 per unit)
For a production run of 10,000 units, soft-start saves $3,500 – justifying the added circuit complexity.
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.
9.8 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) |
| Cost (10A @ 12V rated) | $0.50-2.00 | $3.00-8.00 | $0.20-1.00 |
| 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 → homeowners complain about 5 AM irrigation clicking → SSR preferred despite 4× cost
- Isolation → 24V AC is low-voltage but isolation still preferred for outdoor installation → SSR with optocoupler
Choice: Triac-based SSR with optocoupler input (e.g., Crydom D2425). Cost: $4.50/zone × 8 = $36 total vs $8 for mechanical relays, but eliminates noise complaints.
Common Mistake: Ignoring Relay Contact Arc Erosion in Inductive Loads
The mistake: An IoT smart plug design uses a standard 10A mechanical relay (Songle SRD-05VDC, rated 10A @ 250V AC resistive) to switch a vacuum cleaner (rated 8A). After 500 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× - Cost: $0.15 per relayAdd metal-oxide varistor (MOV) across load:
MOV clamps voltage spike to <200V - Part: Littelfuse V130LA2P (clamping at 200V) - Protects relay from high-voltage arcing - Cost: $0.25Use SSR (no contacts to erode):
- Solid-state relay handles inductive loads without degradation
- Cost: $4.00 vs $0.80 for mechanical relay, but eliminates failure mode
Real-world failure case: Belkin WeMo smart plugs (2014-2016 models) used 10A mechanical relays without snubbers or derating. Customer reports documented failures after 200-800 cycles when switching vacuum cleaners, space heaters with fans, and washing machines – all inductive loads. Belkin’s 2017 hardware revision switched to 16A relays with RC snubbers, reducing failure rate by 90%.
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.9 Safety Considerations
9.10 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 Sensor Squad!
“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.
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.11 Knowledge Check
9.12 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.13 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. Using NC Relay Contacts for Fail-Safe Without Checking 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.14 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 |