Relay Module (Switching Mains Power)

How to safely switch mains-powered devices using a relay module and ESP32

A relay is an electrically operated switch. It lets your ESP32's tiny $3.3\,\text{V}$ GPIO signal control much larger loads -- think lamps, fans, heaters, pumps, or any device that runs on a separate power supply. The relay provides electrical isolation between the ESP32 and the load, meaning the high-power circuit and the low-power control circuit have no direct electrical connection. This is essential for safety and for protecting your microcontroller.

This guide uses the ESP32-WROOM-32 DevKit. Pin labels and GPIO numbers may differ on your board -- always check your board's pinout diagram.

SAFETY WARNING: Relay modules are commonly used to switch mains voltage (110V/220V AC) appliances. Working with mains voltage is extremely dangerous and can cause electrocution, fire, or death. This guide only demonstrates switching low-voltage DC loads (such as a 12V LED strip or a 5V fan). Only work with mains voltage if you are qualified and understand the risks. If you do work with mains, use a properly rated relay, enclose all exposed terminals, and never touch the circuit while it is energized.

🔗Key Specs

ParameterValue (typical module)
Relay typeSPDT (Single Pole, Double Throw)
Coil voltage$5\,\text{V}$
TriggerActive LOW (most modules)
Max switching voltage$250\,\text{V}$ AC / $30\,\text{V}$ DC
Max switching current$10\,\text{A}$
IsolationOptocoupler (on most modules)
IndicatorOnboard LED shows relay state

Active LOW vs. Active HIGH: Most relay modules with optocoupler isolation are active LOW -- the relay turns ON when the input signal is LOW and turns OFF when HIGH. This can be counterintuitive. Check your specific module's behavior by testing with a simple sketch before connecting a load.

Alternatives: For DC loads that need PWM dimming or speed control, a MOSFET is a better fit — it switches silently and supports high-frequency PWM. See our relay vs. MOSFET comparison for help choosing.

🔗Relay Terminal Basics

The high-voltage side of the relay module has three screw terminals:

TerminalNameDescription
COMCommonConnect one wire of your load here
NONormally OpenDisconnected from COM when relay is off, connected when relay is on
NCNormally ClosedConnected to COM when relay is off, disconnected when relay is on

For most applications, you will use COM and NO. When the relay is activated, COM and NO connect, completing the circuit and powering your load.

🔗What You'll Need

ComponentQtyNotesBuy
ESP32 dev board1AliExpress | Amazon.de .co.uk .com
Relay module (5V)1AliExpress | Amazon.de .co.uk .com
Breadboard1AliExpress | Amazon.de .co.uk .com
Jumper wires3AliExpress | Amazon.de .co.uk .com

Links marked Amazon/AliExpress are affiliate links. We may earn a small commission at no extra cost to you.

🔗Wiring

🔗Low-Voltage Side (ESP32 to Relay Module)

Relay Module PinESP32 PinNotes
VCC5V (VIN)Relay coil needs 5V
GNDGND
IN (Signal)GPIO 25Control signal (active LOW on most modules)

🔗High-Voltage Side (Relay to Load)

For this example, we will switch a 12V DC LED strip:

Relay TerminalConnection
COM12V power supply positive (+)
NOLED strip positive (+) input

The LED strip's negative (-) wire connects directly to the 12V supply's GND. When the relay activates, COM connects to NO, completing the circuit and turning on the LED strip.

Note about flyback protection: When a relay coil de-energizes, it can produce a voltage spike (back-EMF). Most relay modules have a flyback diode built into the circuit to suppress this. If you are using a bare relay without a module board, you should add a diode (such as 1N4007) across the relay coil, with the cathode on the positive coil terminal.

🔗Code Example: Basic On/Off Control

This sketch turns the relay on and off every 3 seconds. Remember, most modules are active LOW.

#define RELAY_PIN 25

void setup() {
    Serial.begin(115200);
    pinMode(RELAY_PIN, OUTPUT);
    digitalWrite(RELAY_PIN, HIGH);  // Start with relay OFF (active LOW)
    Serial.println("Relay module ready.");
}

void loop() {
    Serial.println("Relay ON (load powered)");
    digitalWrite(RELAY_PIN, LOW);   // Active LOW: LOW turns relay ON
    delay(3000);

    Serial.println("Relay OFF (load unpowered)");
    digitalWrite(RELAY_PIN, HIGH);  // HIGH turns relay OFF
    delay(3000);
}

Tip: If your relay turns on when you expect it to be off (and vice versa), your module is active HIGH instead of active LOW. Simply swap the HIGH and LOW values in the code.

🔗Code Example: Timed Relay with Serial Control

This sketch lets you turn the relay on and off by sending commands through the Serial Monitor.

#define RELAY_PIN 25

bool relayState = false;

void setRelay(bool on) {
    relayState = on;
    // Active LOW: LOW = on, HIGH = off
    digitalWrite(RELAY_PIN, on ? LOW : HIGH);
    Serial.print("Relay is now ");
    Serial.println(on ? "ON" : "OFF");
}

void setup() {
    Serial.begin(115200);
    pinMode(RELAY_PIN, OUTPUT);
    setRelay(false);  // Start off
    Serial.println("Send '1' to turn ON, '0' to turn OFF");
}

void loop() {
    if (Serial.available()) {
        char cmd = Serial.read();
        if (cmd == '1') {
            setRelay(true);
        } else if (cmd == '0') {
            setRelay(false);
        }
    }
}

🔗How It Works

A relay is fundamentally an electromagnetic switch. Inside the relay housing:

  1. An electromagnet (the coil) is wrapped around an iron core
  2. When current flows through the coil, it creates a magnetic field
  3. The magnetic field pulls a spring-loaded metal contact (the armature) from one position to another
  4. This either connects or disconnects the high-voltage circuit

You can hear the relay click when it switches -- that is the physical contact moving. The audible click is a useful debugging tool to confirm the relay is actually toggling.

🔗Optocoupler Isolation

Most relay modules include an optocoupler between the input signal and the relay coil driver. The optocoupler uses an LED and a phototransistor to transfer the signal optically, providing additional electrical isolation between the ESP32 and the relay coil. This protects the ESP32 from voltage spikes that can occur when the relay switches.

🔗Troubleshooting

ProblemPossible CauseSolution
Relay does not clickVCC not connected to 5VRelay coil needs 5V -- connect VCC to VIN, not 3.3V
Relay clicks but load does not turn onWrong terminal (using NC instead of NO)Move the load wire from NC to NO (or vice versa)
Relay turns on at startupGPIO default state is LOW (active LOW trigger)Add digitalWrite(RELAY_PIN, HIGH) in setup() before pinMode(), or use a GPIO with a known startup state
ESP32 resets when relay switchesBack-EMF or insufficient powerUse a module with built-in flyback diode; power relay from external 5V
Relay state is invertedActive LOW module with active HIGH codeSwap HIGH/LOW in your code
Relay chatters (rapid clicking)Signal noise or bouncingAdd a small delay after state changes; verify solid wiring

🔗Next Steps

  • Control the relay over WiFi to build a smart switch
  • Add a physical button for manual override alongside remote control
  • Use a temperature sensor to trigger the relay automatically (for example, turning on a fan when temperature exceeds a threshold)
  • Explore solid-state relays (SSRs) for silent, faster switching with no mechanical wear