Chapters

14 Relays and Solenoids: Drivers and Protection

actuators
relays
solenoids

14.1 Start With the Decision

A coil stores energy and sends it back when switched off. A driver and clamp must keep that pulse away from the GPIO.

14.2 Route Overview

This is part 1 of 2. Continue with Relays and Solenoids: Switching Choice and Safety.

14.3 Part Objectives

  • Size a relay or solenoid driver from coil current.
  • Choose flyback protection from release speed and voltage.

14.4 Start With the Story

Switch One Coil and Prove the Safe State

Picture a water valve that opens from a tiny control signal but damages its controller when switched off. The coil stored energy that had nowhere safe to go.

An actuator means a part that turns an electrical command into physical action. GPIO means general purpose input/output. A GPIO pin is a small digital connection on a controller; it must not power a heavy coil directly.

Command one on and off cycle, interrupt power, jam the load, and repeat. Record control voltage, coil current, driver state, protection path, temperature, motion, and safe resting state.

This runway does not prove that every relay or solenoid suits the load. The deeper sections explain ratings, drivers, isolation, flyback protection, heating, switching life, and mechanical limits.

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.

In 60 Seconds

Relays are electrically-operated switches that allow low-power microcontrollers to control high-power loads (up to 10A or more) with complete electrical isolation. Solenoids provide fast linear push/pull motion for locks and valves. Both are inductive loads that require flyback diode protection to prevent voltage spikes from damaging electronics.

The mathematical gist. This chapter’s 5 V, 80 mA coil has R=62.5 ΩR=62.5\ \Omega; with 100 mH, τ=L/R=1.60\tau=L/R=1.60 ms and a five-time-constant plain-diode estimate is 8.00 ms. Holding about 30 V across the coil gives the ideal constant-clamp estimate t=LI/V=0.267t=LI/V=0.267 ms — roughly 30 times faster, while the switch sees about 35 V before additional transient margin.

Math Bridge · guided foundationsWhy can a higher clamp release a solenoid faster?Let Max connect the coil's L/R decay to a controlled voltage-and-speed trade.
Chapter Roadmap
  • Start With the Story
  • In 60 Seconds
  • Phoebe’s Field Notes: Why A Plain Flyback Diode Makes The Valve Close Slowly
  • Key Concepts
  • Quick Check: Relay Driver Safety
  • For Beginners: Relays and Solenoids
  • Relay Fundamentals
  • Never Connect Relay Coil Directly to GPIO!
  • Checkpoint: Relay Interfaces
  • Solenoid Control
  • Flyback Protection
  • Critical: Inductive Kickback Protection
  • Putting Numbers to It
  • Checkpoint: Coil Energy
  • Solid-State Relays (SSR)
  • Valve Control
  • Design Example: Smart Sprinkler Controller
  • 12V Motor Relay Sizing
  • Checkpoint: Switching Choices
  • Relay Selection: Decision Framework
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
Quick Check: Relay Driver Safety

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

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.

14.5 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

14.5.1 Relay Specifications

ParameterTypical ValuesWhat It Means
Coil voltage3.3V, 5V, 12V, 24VVoltage needed to activate relay
Coil current50-100mACurrent drawn by coil (needs driver!)
Contact rating10A @ 250VACMaximum load current and voltage
Contact typeSPST, SPDT, DPDTNumber of poles and throws

Interactive: Can Your GPIO Drive This Relay?

14.5.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);
}

14.5.3 Relay Module Wiring

Different bodies can provide the same electrically controlled switching capability, but the isolation technology, current path, terminals, protection parts, and mounting method determine where each relay form belongs.

One-channel electromechanical relay breakout with logic header, indicator, relay can, and screw terminals
A one-channel electromechanical breakout packages a logic header, driver parts, indicator, moving-contact relay, and load terminals. The GPIO commands the board rather than carrying coil current, while COM, NO, and NC still require load-rated wiring and a safe default. Photo: Suyash Dwivedi, CC BY-SA 4.0
Panel-mount 40 amp solid-state relay with low-voltage control terminals and high-current load terminals
A panel-mount solid-state relay removes moving contacts and exposes separate control and high-current screw terminals. Silent, high-cycle switching is possible, but on-state voltage drop, leakage, load type, and heat sinking replace contact wear as selection constraints. Photo: SparkFun Electronics, CC BY 2.0
Relay controller kit with circuit board, relay, terminals, driver components, and protection parts laid out for assembly
A buildable controller shield lays the relay, terminals, driver, and protection parts out as a system rather than hiding them in a module. It teaches the same switching capability by making the control path and load path available for inspection and assembly. Photo: SparkFun Electronics, CC BY 2.0

Read across the three forms before following the terminal map. The electromechanical board, solid-state package, and buildable controller can all switch a load from a small command, yet their isolation, thermal, wear, protection, and service evidence are not interchangeable.

ESP32 / PowerRelay moduleLoad connectionPurpose
GPIO25IN-Low-current control signal
ESP32 GNDGND-Common reference for the module
3.3 V or 5 VVCC-Relay module logic/coil supply
-COMLoad commonSwitch input terminal
-NOLoad hot when relay is ONNormally open output
-NCLoad hot when relay is OFFNormally closed output
Motor MaxCheckpoint: 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.

14.6 Solenoid Control

Before applying the specification, inspect the real solenoid (valve/lock actuator) below: its package, terminals, scale, and installation context are part of the engineering evidence.

Real photograph of solenoid (valve/lock actuator)
This real example (Solenoid lock setup) shows a physical form of solenoid (valve/lock actuator). Use the visible package, interfaces, scale, mounting, and surrounding context as evidence; a catalogue label alone does not establish deployment fit. Photo: Gharris; CC BY-SA 3.0

Carry those visible constraints into the surrounding analysis; the abstract symbol or capability name does not capture mounting, wiring, protection, or service access.

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. Inspect Figure to distinguish the small electrical command from the larger fluid-powered motion it enables.

An industrial butterfly valve with a pneumatic actuator and electrically controlled solenoid valve mounted on top
This industrial assembly uses an electrical solenoid valve to route air into a larger pneumatic actuator: the controller energizes a small coil, and fluid power moves the butterfly valve. Photo: Sarah Adrita, CC BY-SA 4.0

In Figure, trace the energised coil into the pilot valve, then follow the routed air to the pneumatic actuator and butterfly valve. The visible valve motion is evidence from a chain of energy conversions, not proof that coil current alone guarantees movement.

A solenoid pulls because current through its coil creates a magnetic field that draws a ferromagnetic plunger or armature into the coil — the same principle as a relay coil, aimed at motion instead of a switch contact. A classic mechanical demonstration is the electric bell: energizing the coil pulls an armature that swings a hammer into the bell, but that same swing breaks a contact that was feeding the coil. The coil de-energizes, a spring returns the armature, the contact re-makes, and the coil pulls again — so the bell rings by interrupting its own circuit many times a second. That self-interrupting cycle is also a reminder for firmware-driven solenoids: a solenoid cycled on and off repeatedly creates a fresh inductive kickback on every break, not just a single switch-off, so flyback protection has to survive the full duty cycle, not one event.

Characteristics:

  • Fast response (5-50 ms)
  • 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");
}

14.7 Flyback Protection

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!

A relay coil with inductance L=100L = 100 mH carrying 80mA is switched off in 1 μs. The induced voltage is V=LdIdt=0.1×0.080.000001=8000V = -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 Vdiode0.7V_{diode} \approx 0.7 V, dissipating the energy safely as E=12LI2=12×0.1×0.082=0.32E = \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:

ConnectionComponentWhy it matters
GPIO to transistor/MOSFET gate/baseDriver stageGPIO commands the load without supplying coil current directly
Supply through relay coil to driverRelay coilThe coil receives current from the actuator supply
Reverse-biased across the coilFlyback diodeProvides a safe path for stored magnetic energy when the driver turns off
Driver source/emitter to groundCommon groundCompletes 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.

Motor MaxCheckpoint: 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.

14.8 Solid-State Relays (SSR)

The photographs below make solid-state relay (ssr) a physical comparison: look for changes in package, exposed interfaces, mounting, scale, and service access before treating the forms as interchangeable.

Real photograph of solid-state relay (ssr)
This real example (Solid state relay) shows a physical form of solid-state relay (ssr). Use the visible package, interfaces, scale, mounting, and surrounding context as evidence; a catalogue label alone does not establish deployment fit. Photo: en:User:Mike1024; Public domain
Real photograph of solid-state relay (ssr)
This real example (Solid-state-contactor) shows a physical form of solid-state relay (ssr). Use the visible package, interfaces, scale, mounting, and surrounding context as evidence; a catalogue label alone does not establish deployment fit. Photo: User:W2000; Public domain
Real photograph of solid-state relay (ssr)
This real example (DCR AND SOLID STATE RELAYS - NARA - 17471745) shows a physical form of solid-state relay (ssr). Use the visible package, interfaces, scale, mounting, and surrounding context as evidence; a catalogue label alone does not establish deployment fit. Photo: Martin Brown; Public domain

Read across the forms as engineering evidence. They share a capability name, but packaging and installation change the electrical, mechanical, environmental, and maintenance constraints.

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. Inspect Figure to locate the low-voltage control side, load terminals, case, and thermal path before comparing it with mechanical contacts.

A black solid-state relay module with screw terminals, control markings, and status LED
This enclosed SSR exposes low-voltage control terminals separately from its load terminals; unlike a mechanical relay it has no moving contact, but its current and heatsink ratings still matter. Photo: W2000, CC BY-SA 4.0

In Figure, read the control markings separately from the load markings, then notice the enclosed power device and mounting surface. No moving contact means quiet, fast cycling, but leakage, on-state voltage drop, load type, and heatsinking remain part of the switching decision.

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);
}

14.9 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);
}

14.10 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:

DecisionChoiceRationale
Switching elementTriac or other solid-state output per zoneAt 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 protectionTVS diode + varistor per channelSolenoid 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 sensing0.1-ohm shunt resistor per channelDetects stuck-open valves (current drops to zero) and short circuits (current exceeds 1A), enabling the app to alert homeowners to broken sprinkler heads
Power supply24V 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.

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-200 ms 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 100 ms): 28A peak

Step 2: Check relay contact ratings

You are evaluating two relay options:

Relay OptionContinuous RatingInrush RatingMechanical LifeDesign Note
Relay A10A @ 12V DC30A for 100 ms100,000 cyclesInrush rating is stated
Relay B10A @ 12V DCNot specified (assume only 1.5× continuous = 15A for screening)100,000 cyclesInrush 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.

Motor MaxCheckpoint: 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.

14.11 Relay Selection: Decision Framework

14.12 Continue to the Next Part

Carry this evidence into Relays and Solenoids: Switching Choice and Safety, which begins with Complete Decision Framework: Relay vs SSR vs MOSFET.