ADIY

IoT Projects & Protocolsintermediateproject build

DIY Home Automation with ESP8266 & Relay Module: Control Appliances via WiFi

Build a Wi-Fi home automation system with an ESP8266 NodeMCU and a relay module, with wiring, code and essential mains safety precautions.

By ADIY10 min read

Illustration: DIY Home Automation with ESP8266 & Relay Module: Control Appliances via WiFi

Technical review pending. Figures marked “verify” or “check your part” have not been confirmed against your exact hardware revision. Check the manufacturer datasheet before relying on them in a design.

Home automation doesn't have to be expensive or reliant on proprietary systems. With the power of IoT microcontrollers like the ESP8266 and simple mechanical relay modules, building a smart home setup on a budget in India is easier than ever. Whether you want to turn on your AC before reaching home or automate your garden lights, learning home automation with ESP8266 is a fundamental step for any DIY electronics enthusiast.

In this comprehensive guide, we will walk you through controlling AC mains appliances using an ESP8266 NodeMCU and an ADIY 4-Channel Relay Module. We will cover the local Web Server approach (no cloud needed) and the Blynk IoT approach (control from anywhere).

1. Safety Warning: Working with AC Mains#

2. How Relay Modules Work#

A relay is an electrically operated switch. It allows a low-voltage microcontroller (like the 3.3V ESP8266) to safely turn on and off high-voltage, high-current appliances (like a 230V fan or bulb).

Key concepts you need to know:

  • Coil: When current passes through the relay coil, it creates a magnetic field that pulls the mechanical switch contacts together or apart.
  • Contacts: Most relays have Common (COM), Normally Open (NO), and Normally Closed (NC) terminals.
  • NO (Normally Open): The circuit is broken (OFF) when the relay is inactive. It connects when activated. (Recommended for home automation).
  • NC (Normally Closed): The circuit is connected (ON) when inactive, and breaks when activated.
  • Optocoupler Isolation: Quality relay boards use optocouplers to provide electrical isolation between the high-voltage side and the sensitive microcontroller, protecting your ESP8266 from voltage spikes.

3. ADIY 4-Channel Relay Module Overview#

For this project, we are using an ADIY 4-Channel Relay Module. It is robust, easily available in India, and features optocoupler isolation.

  • Operating Voltage: 5V DC
  • Control Signal: TTL level (compatible with 3.3V signals from ESP8266)
  • Trigger Type: Active-Low (A LOW signal turns the relay ON, a HIGH signal turns it OFF).
  • Max Load: 10A at 250V AC / 10A at 30V DC

4. Components Needed#

Here is what you need to build this project. You can find these genuine Make in India components on the ADIY store.

ComponentDescription / Link
ESP8266 NodeMCU BoardThe brains of the project with built-in WiFi. / View Wireless Modules
4-Channel 5V Relay ModuleTo switch the AC appliances. / View Relay Boards
5V 2A Power SupplyTo power the ESP8266 and relays. Ensure adequate current.
Jumper Wires (Female-Female)For connecting the ESP to the Relay board.
AC Load & WiresBulbs, holders, and thick insulated electrical wire.

5. ESP8266 NodeMCU + 4-Channel Relay Wiring#

Powering relays from the ESP8266's 3.3V pin is a common mistake and can lead to instability. The ESP8266 Vin pin can output 5V if the board is powered via USB, but for a 4-channel relay, an external 5V power supply is highly recommended.

ESP8266 NodeMCU PinRelay Module PinNotes
Vin (or Ext 5V supply)VCCProvides 5V to relay coils
GND (or Ext GND)GNDCommon Ground
D1 (GPIO 5)IN1Relay 1 Control
D2 (GPIO 4)IN2Relay 2 Control
D5 (GPIO 14)IN3Relay 3 Control
D6 (GPIO 12)IN4Relay 4 Control

Appliance Wiring: Cut the LIVE (Phase) wire of your appliance. Connect one end to the COM terminal of the relay, and the other end to the NO terminal. The NEUTRAL wire goes directly to the appliance.

6. Approach 1: Local Web Server (No Internet Required)#

This method hosts a simple HTML webpage directly on the ESP8266. Any device (phone, laptop) connected to the same WiFi network can access the page via the ESP's IP address to control the relays. This is fast, private, and doesn't rely on third-party cloud servers.

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
// Replace with your network credentials
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
ESP8266WebServer server(80);
// Assign relay pins
const int relay1 = 5;  // D1
const int relay2 = 4;  // D2
const int relay3 = 14; // D5
const int relay4 = 12; // D6
// HTML Page Generation
String getHTML() {
  String html = "<!DOCTYPE html><html><head><title>ADIY Smart Home</title>";
  html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">";
  html += "<style>body{font-family: Arial; text-align: center; margin:0px auto; padding-top: 30px;}";
  html += ".button {background-color: #2F6A41; color: white; padding: 15px 32px; text-decoration: none; font-size: 20px; margin: 10px; border-radius: 8px; cursor: pointer;}";
  html += ".button-off {background-color: #dc3545;}</style></head><body>";
  html += "<h1>ADIY Home Automation</h1>";
  
  // Note Active-Low logic: LOW state means Relay is ON
  html += "<p>Relay 1: <a href=\"/relay1/on\"><button class=\"button\">ON</button></a> <a href=\"/relay1/off\"><button class=\"button button-off\">OFF</button></a></p>";
  html += "<p>Relay 2: <a href=\"/relay2/on\"><button class=\"button\">ON</button></a> <a href=\"/relay2/off\"><button class=\"button button-off\">OFF</button></a></p>";
  
  html += "</body></html>";
  return html;
}
void setup() {
  Serial.begin(115200);
  
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  
  // Set relays to HIGH (OFF) initially to prevent switching on boot
  digitalWrite(relay1, HIGH);
  digitalWrite(relay2, HIGH);
  
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  Serial.println("Connected!");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
  // Define Server Routes
  server.on("/", []() { server.send(200, "text/html", getHTML()); });
  
  server.on("/relay1/on", []() { 
    digitalWrite(relay1, LOW); // Turn ON (Active-Low)
    server.send(200, "text/html", getHTML()); 
  });
  
  server.on("/relay1/off", []() { 
    digitalWrite(relay1, HIGH); // Turn OFF
    server.send(200, "text/html", getHTML()); 
  });
  
  // Add similar routes for other relays...
  server.begin();
}
void loop() {
  server.handleClient();
}

How to use: Upload the code to your ESP8266. Open the Serial Monitor at 115200 baud, press the EN/RST button on the ESP, and copy the IP address printed (e.g., 192.168.1.45). Type this IP into your phone's mobile browser while connected to the same WiFi.

7. Approach 2: Cloud Control with Blynk IoT#

If you want to control your appliances from outside your house using mobile data, you need an IoT cloud platform. Blynk IoT is perfect for this. It provides a drag-and-drop app interface.

  1. Sign up at Blynk.cloud and create a New Template (Hardware: ESP8266, Connection: WiFi).
  2. Go to Datastreams and create Virtual Pins (V1 for Relay 1, V2 for Relay 2) as Integer datatypes (Min 0, Max 1).
  3. Create a Device from the Template and copy the BLYNK_TEMPLATE_ID, BLYNK_DEVICE_NAME, and BLYNK_AUTH_TOKEN.
  4. Download the Blynk app on your phone, log in, open your device, and add "Button" widgets linked to Datastreams V1 and V2.
// Include these at the very top of your sketch!
#define BLYNK_TEMPLATE_ID "TMPLxxxxxx"
#define BLYNK_DEVICE_NAME "Home Automation"
#define BLYNK_AUTH_TOKEN "YourAuthTokenHere"
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "YOUR_WIFI_SSID";
char pass[] = "YOUR_WIFI_PASSWORD";
const int relay1 = 5; // D1
void setup() {
  pinMode(relay1, OUTPUT);
  digitalWrite(relay1, HIGH); // Default OFF
  
  Blynk.begin(auth, ssid, pass);
}
// This function runs every time the V1 button state changes in the App
BLYNK_WRITE(V1) {
  int pinValue = param.asInt(); // Get value (0 or 1)
  
  if (pinValue == 1) {
    digitalWrite(relay1, LOW); // Turn Relay ON (Active Low)
  } else {
    digitalWrite(relay1, HIGH); // Turn Relay OFF
  }
}
void loop() {
  Blynk.run();
}

8. Voice Control: Google Assistant & IFTTT (Optional)#

To take it a step further, you can integrate your Blynk setup with Google Assistant using Webhooks via IFTTT (If This Then That). You can create an applet where the trigger is a Google Assistant command ("Turn on the fan"), and the action is a Webhook HTTP request that hits the Blynk API to update the Virtual Pin state.

9. Adding Physical Override Buttons#

A true smart home shouldn't break when the WiFi goes down. It is highly recommended to add physical push buttons alongside the relays so you can manually toggle lights just like traditional switches.

You can wire momentary push buttons from the ESP8266 input pins to GND. Use attachInterrupt() in your code to detect button presses and toggle the relay states while simultaneously syncing the state back to the Blynk cloud.

10. Enclosure and Placement Tips#

Never leave raw PCBs exposed where people can touch them. Buy a good quality PVC junction box or a 3D-printed enclosure.

  • Keep the ESP8266 module slightly away from the relays if possible to avoid EMI (Electromagnetic Interference) causing random reboots.
  • Use thick gauge wires for the AC load paths. Ensure connections in the terminal block are screwed down tightly. Loose connections cause arcing and fires.

11. Troubleshooting Common Issues#

12. Frequently Asked Questions#

Can I use an ESP32 instead of an ESP8266?

Absolutely! The ESP32 is more powerful and has Bluetooth built-in. The wiring concept remains identical, though you will need to adjust the GPIO pin numbers in the code and use the ESP32 specific WiFi libraries.

Does it matter if my relay module is Active-Low or Active-High?

Yes, it changes how you write your code. Most 5V relay modules with optocouplers are Active-Low, meaning a LOW signal (0V) turns them on, and a HIGH signal (3.3V/5V) turns them off. You must initialize them to HIGH in the setup() loop to prevent appliances from turning on during boot.

How many appliances can I control with one ESP8266?

A standard ESP8266 NodeMCU has about 9 usable GPIO pins for outputs. So technically, you could control an 8-channel relay board. For more, you would need an ESP32 or a GPIO expander IC like the MCP23017.

Is Blynk free to use?

Blynk offers a free tier (Blynk Maker plan) which is sufficient for small DIY home automation projects involving a couple of devices and basic data tracking.

Share