If you have ever wanted to turn on a light bulb, switch a fan, or control an irrigation pump using an Arduino or ESP32, you have encountered the fundamental problem of electronics: your microcontroller operates at 3.3V or 5V, but the appliance you want to control runs on 230V AC mains power. You cannot connect them directly. You need a relay.
This guide covers everything you need to know about relay modules — from the basic physics of how they work, to wiring them safely, to writing code that controls real appliances. We will pay special attention to safety, because when you work with mains voltage, mistakes can be fatal.
What Is a Relay?
A relay is an electrically operated switch. It uses a small current from your microcontroller to control a much larger current flowing through a completely separate circuit. Think of it as a bridge between two worlds: the low-voltage world of your Arduino (5V, milliamps) and the high-voltage world of your household appliances (230V AC, several amps).
The key property that makes relays valuable is galvanic isolation — the control circuit and the switched circuit are electrically separate. There is no direct electrical connection between your microcontroller and the mains power. The relay uses a magnetic field to mechanically move a switch contact, keeping the two circuits physically apart.
How a Relay Works Internally
Inside every relay, you will find four essential parts:
- Coil (Electromagnet): A wire wound around an iron core. When current flows through the coil, it creates a magnetic field.
- Armature: A movable metal piece that is attracted by the electromagnet. This is the mechanical part that actually moves.
- Spring: Holds the armature in its default (resting) position when the coil is not energized.
- Contacts: The electrical connection points that open or close when the armature moves.
The Three Contact Terminals
Every relay has three contact terminals that you need to understand:
| Terminal | Full Name | Description |
|---|---|---|
| COM | Common | The shared terminal — your input power wire connects here |
| NO | Normally Open | Disconnected from COM when the relay is off. Connected when the relay is energized. |
| NC | Normally Closed | Connected to COM when the relay is off. Disconnected when the relay is energized. |
How it works in practice: When you send a signal from your Arduino to the relay, the coil energizes, the armature moves, and the COM terminal switches from being connected to NC to being connected to NO. When you remove the signal, the spring pulls the armature back, and COM reconnects to NC.
For most home automation applications, you wire your load between COM and NO. This means the appliance is off by default and turns on when you activate the relay. This is the safer configuration — if your microcontroller crashes or loses power, the appliance turns off.
Types of Relays: SPST, SPDT, and DPDT
Relays are classified by the number of poles (independent circuits they can control) and throws (positions the switch can connect to):
| Type | Poles | Throws | Contacts | Best For |
|---|---|---|---|---|
| SPST | 1 | 1 | COM + NO only | Simple on/off switching. Lights, fans. |
| SPDT | 1 | 2 | COM + NO + NC | Switching between two circuits. Most relay modules use this type. |
| DPDT | 2 | 2 | Two sets of COM + NO + NC | Motor direction control (forward/reverse). Switching two lines simultaneously. |
Most relay modules you will buy for Arduino and ESP32 projects use SPDT relays. This gives you the flexibility to use either the NO or NC terminal depending on your application.
Understanding Relay Module Boards
A bare relay cannot be connected directly to an Arduino pin. The pin cannot supply enough current to drive the relay coil, and the back-EMF from the coil could damage your microcontroller. This is why we use relay module boards — they package everything you need onto a single PCB.
A typical relay module board includes:
- Relay: The electromechanical switch itself, usually rated for 10A at 250V AC.
- Transistor driver: An NPN transistor (or MOSFET) that amplifies the small signal from your microcontroller into enough current to drive the relay coil.
- Flyback diode: Connected across the relay coil to suppress the voltage spike (back-EMF) when the coil de-energizes. Without this, the spike could destroy your transistor or microcontroller.
- Optocoupler (on better modules): Provides optical isolation between your microcontroller and the relay driver circuit. This adds an extra layer of protection.
- Indicator LED: Lights up when the relay is activated, making debugging easy.
- Screw terminals: For connecting your high-voltage wires securely to the COM, NO, and NC contacts.
- Pin header: VCC, GND, and IN (signal) pins for connecting to your microcontroller.
The JD-VCC Jumper
Many relay modules have a jumper between VCC and JD-VCC. When this jumper is in place, the relay coil is powered from the same supply as the optocoupler. For proper isolation, remove this jumper and power JD-VCC from a separate 5V supply. This keeps your microcontroller completely isolated from the relay coil circuit.
Wiring a Relay Module to Arduino and ESP32
Basic Wiring (Arduino Uno)
| Relay Module Pin | Arduino Pin |
|---|---|
| VCC | 5V |
| GND | GND |
| IN1 | Digital Pin 7 |
Basic Wiring (ESP32)
| Relay Module Pin | ESP32 Pin |
|---|---|
| VCC | VIN (5V) or external 5V supply |
| GND | GND |
| IN1 | GPIO 26 |
Important for ESP32: The ESP32 operates at 3.3V logic. Most relay modules with optocouplers work fine with 3.3V signals, but some older modules designed for 5V Arduino logic may not trigger reliably. Check your module's specifications, or use a logic level shifter if needed.
Active-High vs Active-Low
This is a common source of confusion. Relay modules come in two flavors:
- Active-HIGH: The relay turns ON when you send a HIGH signal (5V or 3.3V) to the IN pin.
digitalWrite(pin, HIGH)activates the relay. - Active-LOW: The relay turns ON when you send a LOW signal (0V) to the IN pin.
digitalWrite(pin, LOW)activates the relay.
Most relay modules with optocouplers are active-LOW. The LED inside the optocoupler turns on when the IN pin is pulled LOW (connected to GND through the optocoupler LED). If your relay seems to be doing the opposite of what you expect, you probably have the logic inverted.
Code: Basic On/Off Control with Arduino
This sketch toggles a relay every 3 seconds. Connect a lamp or LED strip to the relay's COM and NO terminals to see it in action.
// Basic Relay Toggle - Arduino
// Relay module IN1 connected to pin 7
const int RELAY_PIN = 7;
void setup() {
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, HIGH); // Start with relay OFF (active-low module)
Serial.begin(9600);
Serial.println("Relay control initialized");
}
void loop() {
Serial.println("Relay ON");
digitalWrite(RELAY_PIN, LOW); // Activate relay (active-low)
delay(3000); // Stay on for 3 seconds
Serial.println("Relay OFF");
digitalWrite(RELAY_PIN, HIGH); // Deactivate relay (active-low)
delay(3000); // Stay off for 3 seconds
}
If your module is active-HIGH, simply swap the HIGH and LOW values.
Code: Timed Relay with ESP32
This example turns on a relay for a configurable number of seconds, then automatically turns it off. Useful for irrigation pumps, battery charging cutoffs, or timed ventilation.
// Timed Relay Control - ESP32
// Relay module IN1 connected to GPIO 26
const int RELAY_PIN = 26;
const unsigned long ON_DURATION_MS = 10000; // 10 seconds
bool relayActive = false;
unsigned long relayStartTime = 0;
void setup() {
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, HIGH); // Relay OFF (active-low)
Serial.begin(115200);
Serial.println("Timed relay control ready");
Serial.println("Send 'ON' via Serial Monitor to start the timer");
}
void loop() {
// Check for serial command
if (Serial.available()) {
String command = Serial.readStringUntil('\n');
command.trim();
if (command == "ON" && !relayActive) {
digitalWrite(RELAY_PIN, LOW); // Activate relay
relayActive = true;
relayStartTime = millis();
Serial.print("Relay ON for ");
Serial.print(ON_DURATION_MS / 1000);
Serial.println(" seconds");
}
}
// Auto-off after duration
if (relayActive && (millis() - relayStartTime >= ON_DURATION_MS)) {
digitalWrite(RELAY_PIN, HIGH); // Deactivate relay
relayActive = false;
Serial.println("Relay OFF (timer expired)");
}
}
Code: Web-Controlled Relay via ESP32 WiFi
This is where things get exciting. The ESP32's built-in WiFi lets you control a relay from any device on your local network — phone, laptop, or tablet.
// Web-Controlled Relay - ESP32
// Access the control page at the ESP32's IP address
#include <WiFi.h>
#include <WebServer.h>
const char* WIFI_SSID = "YourNetworkName";
const char* WIFI_PASS = "YourPassword";
const int RELAY_PIN = 26;
WebServer server(80);
bool relayState = false;
void handleRoot() {
String html = "<!DOCTYPE html><html><head>";
html += "<meta name='viewport' content='width=device-width, initial-scale=1'>";
html += "<style>";
html += "body { font-family: Arial, sans-serif; text-align: center; ";
html += "padding: 40px; background: #f0f0f0; }";
html += ".btn { display: inline-block; padding: 20px 40px; ";
html += "font-size: 20px; border: none; border-radius: 8px; ";
html += "cursor: pointer; margin: 10px; color: white; }";
html += ".on { background: #10B981; }";
html += ".off { background: #dc3545; }";
html += ".status { font-size: 24px; margin: 20px 0; }";
html += "</style></head><body>";
html += "<h1>ESP32 Relay Control</h1>";
html += "<div class='status'>Relay is: <strong>";
html += relayState ? "ON" : "OFF";
html += "</strong></div>";
html += "<a href='/on'><button class='btn on'>Turn ON</button></a>";
html += "<a href='/off'><button class='btn off'>Turn OFF</button></a>";
html += "</body></html>";
server.send(200, "text/html", html);
}
void handleOn() {
digitalWrite(RELAY_PIN, LOW); // Active-low
relayState = true;
server.sendHeader("Location", "/");
server.send(303);
}
void handleOff() {
digitalWrite(RELAY_PIN, HIGH); // Active-low
relayState = false;
server.sendHeader("Location", "/");
server.send(303);
}
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, HIGH); // Start OFF
WiFi.begin(WIFI_SSID, WIFI_PASS);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected! IP: ");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.on("/on", handleOn);
server.on("/off", handleOff);
server.begin();
}
void loop() {
server.handleClient();
}
Upload this sketch, open the Serial Monitor to find the IP address, then open that IP in any browser on the same network. You now have wireless relay control.
Safety: Working with Mains Voltage (230V AC)
This is the most important section in this entire article. Read it carefully.
When you connect a relay module to a mains-powered appliance, you are working with 230V AC — the same voltage that comes out of every wall socket in India. This voltage can kill you. It can start fires. It can destroy equipment. There is no margin for carelessness.
Mandatory Safety Rules
-
ALWAYS disconnect mains power before wiring. Turn off the MCB/circuit breaker for the circuit you are working on. Verify with a tester that the wires are dead before touching anything.
-
Never work on live circuits. Not even to "quickly check something." Not even if you are experienced. Disconnect first, wire everything, double-check every connection, then restore power.
-
Use an enclosure. All mains-voltage wiring must be inside a proper electrical enclosure (junction box). No exposed 230V terminals, no open breadboard connections, no dangling wires. Use a proper IP-rated plastic enclosure.
-
Use appropriate wire gauge. For loads up to 10A (2300W at 230V), use at minimum 1.0 sq mm copper wire. For higher loads, size up accordingly. Never use thin jumper wires or breadboard wires for mains connections.
-
Always fuse the circuit. Place an appropriately rated fuse or MCB between the mains supply and the relay. If the relay's contacts are rated for 10A, use a 6A or 10A fuse. The fuse protects against short circuits and relay contact failure.
-
Use proper connectors. Use screw terminals, wire ferrules, and crimped connectors. Never twist bare wires together and tape them. In India, loose connections are a leading cause of electrical fires.
-
Respect the relay's contact ratings. A relay rated for 10A at 250V AC does not mean you should run 10A through it continuously. Derate by at least 20-30% for continuous loads. For a 10A relay, limit continuous current to 7-8A.
-
Keep high-voltage and low-voltage sides separate. Route mains wires away from your microcontroller and signal wires. Inside your enclosure, keep a clear physical separation between the 230V side and the 5V/3.3V side.
-
Ground everything. If your enclosure is metal, it must be earthed. Use three-wire mains cables (live, neutral, earth) and connect earth to the enclosure.
-
Never bypass safety devices. Do not remove the earth wire. Do not use a larger fuse than specified. Do not disable the MCB.
A Note on Indian Electrical Standards
In India, the standard mains supply is 230V AC, 50Hz, single phase for residential use. The plug/socket system uses IS 1293 Type D (5A) and Type M (15A) sockets. When building home automation projects, ensure your enclosure and wiring comply with Indian electrical standards. If you are not confident in your electrical wiring skills, consult a licensed electrician for the mains-voltage portion of your project.
Common Applications
Relay modules are the backbone of countless practical projects:
- Home automation: Control lights, fans, geysers, and air coolers from your phone or voice assistant. A 4-channel relay module can control an entire room.
- Motor control: Use a DPDT relay to reverse the direction of a DC motor. Use a relay to start/stop a single-phase motor.
- Irrigation systems: Automate a water pump based on soil moisture sensor readings or a scheduled timer.
- Battery chargers: Cut off charging when the battery reaches full voltage using a relay and a voltage sensor.
- Aquarium/terrarium: Automate lighting schedules, heaters, and air pumps.
- Industrial control: Interlock circuits, sequential motor starting, and alarm systems.
Common Mistakes and How to Avoid Them
1. Not Handling Back-EMF
When a relay coil de-energizes, the collapsing magnetic field generates a voltage spike (back-EMF) that can be 10-50 times the coil voltage. Relay module boards include a flyback diode to suppress this. If you are driving a bare relay without a module board, you must add a flyback diode (such as 1N4007) across the coil, cathode to positive.
2. Powering the Relay from the Arduino 5V Pin
The Arduino Uno's 5V pin can supply about 200mA when powered via USB. A single relay coil draws 70-80mA. Two relays and you are at 150mA, leaving almost nothing for the rest of your circuit. Use an external 5V power supply for the relay module, especially with multi-channel modules. Share a common GND between the external supply and your Arduino.
3. Relay Chattering
If your relay clicks on and off rapidly, the cause is usually:
- Insufficient coil voltage: The supply voltage is too low to fully energize the coil. Ensure stable 5V to the module.
- Noisy signal line: Long wires between the microcontroller and relay can pick up interference. Keep signal wires short, or use shielded cable.
- Software bouncing: Your code is toggling the relay pin too rapidly. Add appropriate debounce logic.
4. Exceeding Contact Ratings
Just because the relay says "10A 250VAC" does not mean you should switch 10A inductive loads. Inductive loads (motors, solenoids, transformers) generate arcing across the relay contacts when switching, which degrades them rapidly. For inductive loads, derate the relay to 30-50% of its resistive load rating, or use an appropriate snubber circuit (RC network) across the contacts.
5. Not Using Active-Low Logic Correctly
Many beginners write digitalWrite(pin, HIGH) expecting the relay to turn on. With an active-low module, this keeps the relay off. Always test with a simple blink sketch first and observe the LED on the relay module to confirm the logic level.
Solid-State Relays (SSR) vs Mechanical Relays
| Feature | Mechanical Relay | Solid-State Relay (SSR) |
|---|---|---|
| Switching element | Physical contacts | Semiconductor (TRIAC/MOSFET) |
| Switching speed | 5-15 ms | < 1 ms |
| Lifespan | ~100,000 cycles | Millions of cycles |
| Audible click | Yes | No (silent) |
| Voltage drop | Near zero when closed | 1-2V drop (generates heat) |
| Leakage current | Zero when open | Small leakage (~mA) |
| Cost | Lower | Higher |
| Heat | Minimal | Needs heatsink at high loads |
| Best for | Low-frequency switching, cost-sensitive projects | High-frequency switching, dimming, silent operation |
Use a mechanical relay when you need clean on/off switching at low cost and do not switch more than a few times per minute. Use an SSR when you need fast switching, silent operation, PWM-based dimming, or long operational life. For most hobby home automation projects, mechanical relay modules are the practical and economical choice.
Multi-Channel Relay Modules
Relay modules come in 1, 2, 4, 8, and even 16-channel configurations. Each channel is an independent relay with its own input pin.
| Channels | Typical Use | Power Note |
|---|---|---|
| 1-channel | Single appliance control, learning projects | Can be powered from Arduino 5V |
| 2-channel | Light + fan, motor forward/reverse | External 5V recommended |
| 4-channel | Full room automation (light, fan, geyser, socket) | External 5V supply required |
| 8-channel | Multi-room automation, industrial control panels | External 5V supply mandatory; draws ~600mA+ |
For 4-channel modules and above, always use a dedicated external 5V power supply. An 8-channel module with all relays active can draw over 640mA — far more than any microcontroller can provide.
When using many channels, consider whether you actually need all relays active simultaneously. If not, you can reduce peak current draw by staggering relay activation in your code.
Relay Specifications Explained
When buying a relay module, you will encounter these specifications. Here is what they mean and why they matter:
| Specification | Meaning | What to Check |
|---|---|---|
| Coil voltage | Voltage needed to energize the coil (typically 5V or 12V) | Must match your supply. 5V modules work directly with Arduino/ESP32 setups. |
| Contact rating (resistive) | Maximum current and voltage the contacts can switch with a resistive load | Common: 10A @ 250VAC, 10A @ 30VDC. Do not exceed these values. |
| Contact rating (inductive) | Maximum for inductive loads (motors, solenoids) | Usually 3-7A. If not listed, derate resistive rating by 50%. |
| Switching time | Time for contacts to change state after coil is energized/de-energized | Typically 5-15ms. Not critical for most applications. |
| Coil resistance | Resistance of the coil winding | Determines coil current draw. ~70 ohms for a 5V relay means ~71mA draw. |
| Dielectric strength | Voltage isolation between coil and contacts | Should be 1500-4000VAC for safety. Higher is better. |
| Mechanical life | Number of switching cycles before mechanical failure | Typically 10 million cycles without load. |
| Electrical life | Number of switching cycles at rated load before contact degradation | Typically 100,000 cycles at full rated load. |
Choosing the Right Relay Module
For most hobbyist and home automation projects in India, a 5V, single or 4-channel SPDT relay module with optocoupler isolation is the best starting point. Look for modules that:
- Use SRD-05VDC-SL-C relays (or equivalent) rated for 10A @ 250VAC
- Have optocoupler isolation (look for a JD-VCC jumper)
- Have clearly labeled screw terminals (COM, NO, NC)
- Include onboard indicator LEDs
- Support both 3.3V and 5V logic input (important for ESP32)
Wrapping Up
Relay modules are one of the most satisfying components in electronics because they let you bridge the gap between your small microcontroller projects and the real world of mains-powered appliances. With a few lines of code and a relay module, you can automate your home, build an irrigation controller, or create a remotely operated power switch.
But this power comes with real responsibility. Every time you work with mains voltage, you are working with something that can kill. Follow the safety rules, use proper enclosures and wiring, fuse your circuits, and never take shortcuts. If the mains-voltage wiring is beyond your comfort level, there is no shame in asking a qualified electrician to handle that part while you focus on the microcontroller and software side.
Start with a simple single-channel module and an LED or low-voltage load. Get comfortable with the wiring and the code. Then, with proper safety measures in place, graduate to controlling real appliances. That first time you turn on a light from your phone using an ESP32 and a relay — it is a genuinely magical moment.
Build safely. Build smart.



