Smart Home Automation with ESP32 and Relay Modules

November 18, 2026 · fareedahmed486

Smart Home Automation with ESP32 and Relay Modules

Smart Home Automation with ESP32 and Relay Modules: Complete Beginner’s Guide

Smart home automation is becoming increasingly popular in Pakistan as people look for convenient, affordable, and energy-efficient ways to control their home appliances. With an ESP32 development board and relay modules, you can build a smart home automation system that allows you to control lights, fans, and other electrical appliances using a smartphone or wireless network.

Whether you are an electronics beginner, Arduino enthusiast, IoT developer, or engineering student working on a final-year project (FYP), ESP32 is an excellent platform for developing smart home automation projects.

The ESP32 comes with built-in Wi-Fi and Bluetooth connectivity, making it suitable for Internet of Things (IoT) applications. By combining an ESP32 with a relay module, you can create a system that switches connected loads ON and OFF through a web interface or smartphone.

In this tutorial, we will explain how ESP32 smart home automation works, which components you need, how to connect relay modules, and how to write Arduino IDE code for controlling electrical loads. We will also cover safety precautions, common problems, and advanced IoT project ideas.

1. What Is Smart Home Automation?

Smart home automation is a technology that allows users to control and monitor household devices using electronic controllers, sensors, smartphones, and wireless communication.

Instead of manually switching appliances ON and OFF, a smart home system can automate these operations using a microcontroller such as ESP32.

For example, you can develop a system that allows you to:

  • Turn room lights ON and OFF using your smartphone.

  • Control an electric fan through Wi-Fi.

  • Switch multiple appliances using relay modules.

  • Automate lighting based on sensor readings.

  • Monitor temperature and humidity.

  • Create scheduled appliance-control functions.

  • Develop wireless home automation prototypes.

ESP32 makes these projects easier because it includes integrated Wi-Fi and Bluetooth connectivity without requiring an additional wireless module.

2. Why Use ESP32 for Home Automation?

The ESP32 is a powerful microcontroller family developed by Espressif Systems. It is widely used in IoT, robotics, wireless monitoring, and home automation applications.

Compared with traditional Arduino Uno boards, ESP32 offers built-in wireless connectivity and more processing capabilities for many IoT applications.

Important ESP32 Features

  • Built-in 2.4GHz Wi-Fi on common ESP32 variants.

  • Bluetooth or Bluetooth Low Energy support, depending on the model.

  • Multiple GPIO pins for controlling electronic modules.

  • PWM support for controlling compatible devices.

  • ADC inputs for reading analog sensors.

  • Compatibility with Arduino IDE.

  • Low-power operating modes on supported variants.

  • Support for web servers and IoT communication protocols.

Why Is ESP32 Better for Wi-Fi Home Automation?

With an Arduino Uno, you generally need an additional Wi-Fi module to create wireless home automation.

An ESP32 development board already includes Wi-Fi, making the circuit simpler and often more affordable.

You can use it to create a local Wi-Fi control panel that opens in your smartphone’s browser without installing a dedicated mobile application.

3. What Is a Relay Module and Why Is It Used?

A relay module is an electrically controlled switch that allows a low-voltage control circuit to switch another electrical circuit.

In an ESP32 smart home automation project, the ESP32 sends a control signal to the relay module. The relay then changes its contact position to switch the connected load ON or OFF.

A relay module typically contains:

Understanding Relay Terminals

Most electromechanical relay modules provide three main switching terminals:

Terminal Function
COM Common terminal
NO Normally Open
NC Normally Closed

COM (Common): The shared switching contact.

NO (Normally Open): The connection is open when the relay is not energized.

NC (Normally Closed): The connection is closed when the relay is not energized.

For a basic low-voltage demonstration, the NO and COM terminals can be used so that the load remains OFF until the relay is activated.

4. Components Required for ESP32 Smart Home Automation

Before building the project, collect the following components.

Component Quantity Purpose
ESP32 Development Board 1 Main IoT controller
4-Channel Relay Module 1 Controls four independent loads
USB Cable 1 Programming and power
Jumper Wires As required Circuit connections
Breadboard 1 Low-voltage prototyping
LED with Resistor Optional Safe switching demonstration
Temperature Sensor Optional Environmental monitoring
Power Supply As required Powers the circuit

You can also use a 1-channel or 2-channel relay module if your project only needs to control one or two devices.

For electronics students and IoT developers in Pakistan, the ESP32 development board, relay module, sensors, and other accessories are useful components for building practical home automation prototypes.

5. Understanding the ESP32 and Relay Module Connections

For this tutorial, we will use an ESP32 development board with a four-channel relay module.

The ESP32 will control each relay independently through its GPIO pins.

ESP32 to 4-Channel Relay Module Pinout

Relay Module Pin ESP32 Connection
IN1 GPIO 23
IN2 GPIO 22
IN3 GPIO 21
IN4 GPIO 19
GND GND
VCC According to module specification

Important electrical compatibility: ESP32 GPIO operates at 3.3V and is not 5V tolerant. Some 5V relay boards do not reliably recognize a 3.3V control signal. Use a relay module explicitly compatible with 3.3V logic or a suitable transistor/level-shifting interface. Do not assume that every 5V relay module will work directly.

Also, check the relay module’s coil supply requirements and provide a suitable regulated supply. Do not power multiple relay coils directly from an ESP32 GPIO pin.

Important Power Connections

  • Power the ESP32 through its USB connection or a suitable regulated supply.

  • Supply the relay board according to its rated voltage.

  • Connect the control ground appropriately when using a non-isolated logic interface.

  • Follow the relay module manufacturer’s wiring diagram.

  • Avoid drawing relay coil current from the ESP32 3.3V output unless the board’s power budget explicitly supports it.

For initial testing, use a low-voltage DC LED circuit rather than household mains appliances.

High-voltage safety warning: Household electricity in Pakistan is typically around 230V AC and can cause fatal electric shock or fire. Never connect exposed mains wiring to a breadboard or handle energized relay terminals. Mains appliance switching requires correctly rated enclosures, fuses, insulation, clearances, earthing, and protective devices. Have the mains-side installation designed and completed by a qualified electrician. A relay module alone does not make a circuit safe.

6. How ESP32 Smart Home Automation Works

The working principle of an ESP32 home automation system is straightforward.

  1. The user connects a smartphone to the ESP32 control interface over Wi-Fi.

  2. The user selects an appliance control button.

  3. The ESP32 receives the HTTP request.

  4. The ESP32 changes the selected GPIO output.

  5. The relay module switches its corresponding contact.

  6. The connected demonstration load turns ON or OFF.

For example, when you press the Light ON button on your smartphone, the ESP32 activates Relay 1. Pressing Light OFF deactivates it.

This process can be repeated independently for multiple relay channels.

7. ESP32 Smart Home Automation Arduino Code

Now let’s program the ESP32 using Arduino IDE.

This example creates a simple web server hosted directly on the ESP32. Your smartphone and ESP32 should be connected to the same Wi-Fi network.

The code controls four relay channels through a browser interface.


#include <WiFi.h>
#include <WebServer.h>

// WiFi Credentials
const char* ssid = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";

// Relay GPIO Pins
#define RELAY1 23
#define RELAY2 22
#define RELAY3 21
#define RELAY4 19

// Most relay modules are active LOW.
// Change these values if your module uses
// active HIGH control.
#define RELAY_ON LOW
#define RELAY_OFF HIGH

WebServer server(80);

// Relay states
bool relayState[4] = {
  false, false, false, false
};

int relayPins[4] = {
  RELAY1, RELAY2, RELAY3, RELAY4
};

// Update relay output
void setRelay(int channel, bool state) {

  relayState[channel] = state;

  digitalWrite(
    relayPins[channel],
    state ? RELAY_ON : RELAY_OFF
  );
}

// Create web control page
String webpage() {

  String page = R"rawliteral(
  <!DOCTYPE html>
  <html>
  <head>
    <meta name="viewport"
    content="width=device-width, initial-scale=1">

    <title>ESP32 Smart Home</title>

    <style>
      body {
        font-family: Arial;
        text-align: center;
        background: #eef2f7;
      }

      h1 {
        color: #172554;
      }

      .card {
        background: white;
        padding: 18px;
        margin: 15px auto;
        max-width: 350px;
        border-radius: 12px;
      }

      a {
        text-decoration: none;
      }

      button {
        padding: 12px 25px;
        margin: 8px;
        border: none;
        border-radius: 8px;
        color: white;
        font-size: 16px;
        cursor: pointer;
      }

      .on {
        background: #16a34a;
      }

      .off {
        background: #dc2626;
      }
    </style>
  </head>

  <body>

    <h1>ESP32 Smart Home</h1>
    <p>WiFi Appliance Control</p>
  )rawliteral";

  for (int i = 0; i < 4; i++) {

    page += "<div class='card'>";
    page += "<h3>Device ";
    page += String(i + 1);
    page += "</h3>";

    page += "<p>Status: ";
    page += relayState[i] ? "ON" : "OFF";
    page += "</p>";

    page += "<a href='/relay";
    page += String(i + 1);
    page += "/on'>";
    page += "<button class='on'>ON</button></a>";

    page += "<a href='/relay";
    page += String(i + 1);
    page += "/off'>";
    page += "<button class='off'>OFF</button></a>";

    page += "</div>";
  }

  page += "</body></html>";

  return page;
}

// Handle relay requests
void handleRelay(int channel, bool state) {

  setRelay(channel, state);

  server.send(200, "text/html", webpage());
}

void setup() {

  Serial.begin(115200);

  // Initialize relay pins to OFF
  for (int i = 0; i < 4; i++) {

    digitalWrite(relayPins[i], RELAY_OFF);
    pinMode(relayPins[i], OUTPUT);

  }

  // Connect WiFi
  WiFi.begin(ssid, password);

  Serial.print("Connecting to WiFi");

  while (WiFi.status() != WL_CONNECTED) {

    delay(500);
    Serial.print(".");

  }

  Serial.println();

  Serial.println("WiFi Connected");
  Serial.print("ESP32 IP Address: ");
  Serial.println(WiFi.localIP());

  // Main page
  server.on("/", []() {
    server.send(200, "text/html", webpage());
  });

  // Relay 1
  server.on("/relay1/on", []() {
    handleRelay(0, true);
  });

  server.on("/relay1/off", []() {
    handleRelay(0, false);
  });

  // Relay 2
  server.on("/relay2/on", []() {
    handleRelay(1, true);
  });

  server.on("/relay2/off", []() {
    handleRelay(1, false);
  });

  // Relay 3
  server.on("/relay3/on", []() {
    handleRelay(2, true);
  });

  server.on("/relay3/off", []() {
    handleRelay(2, false);
  });

  // Relay 4
  server.on("/relay4/on", []() {
    handleRelay(3, true);
  });

  server.on("/relay4/off", []() {
    handleRelay(3, false);
  });

  server.begin();

  Serial.println("Web Server Started");

}

void loop() {

  server.handleClient();

}

Before uploading:

  • Replace YOUR_WIFI_NAME with your Wi-Fi network name.

  • Replace YOUR_WIFI_PASSWORD with your Wi-Fi password.

  • Select the correct ESP32 board in Arduino IDE.

  • Confirm that your relay module supports the ESP32’s 3.3V control logic.

  • Verify whether the relay inputs are active LOW or active HIGH.

The code assumes active-LOW relay inputs. Test the relay board using a safe low-voltage load before connecting any real appliance.

8. How to Control Your Smart Home Using a Smartphone

After uploading the Arduino code, you can control your four relay channels using a smartphone or computer.

Follow these steps:

  1. Connect the ESP32 to your Wi-Fi network.

  2. Open Arduino IDE and launch the Serial Monitor.

  3. Set the Serial Monitor baud rate to 115200.

  4. Wait for the ESP32 to connect to Wi-Fi.

  5. Find the IP address printed in the Serial Monitor.

  6. Connect your smartphone to the same Wi-Fi network.

  7. Open Chrome or another browser.

  8. Enter the ESP32 IP address in the address bar.

You will see a smart home control page with four device sections.

You can now use the ON and OFF buttons to control each relay channel independently.

Example: If your ESP32 displays the IP address 192.168.1.105, enter that address into your smartphone browser.

The IP address shown here is only an example. Your ESP32 will display its own address.

Security note: This example is a basic local-network demonstration without login authentication or encrypted communication. Keep it on a trusted private network. Do not expose its web server directly to the public internet.

9. Different Types of Relay Modules for Home Automation

Relay modules are available in different configurations depending on the number of devices you want to control.

Relay Module Channels Typical Applications
1-Channel Relay 1 Single light or load
2-Channel Relay 2 Two independent loads
4-Channel Relay 4 Small smart home system
8-Channel Relay 8 Multiple-load automation

Which Relay Module Should You Choose?

  • 1-channel: Best for learning and basic switching experiments.

  • 2-channel: Suitable for controlling two independent devices.

  • 4-channel: A practical choice for a small smart home prototype.

  • 8-channel: Useful for larger automation systems with more switching outputs.

Always check the relay’s contact voltage and current ratings, load type, inrush current rating, and the module’s input voltage compatibility before choosing one.

10. Advanced ESP32 Smart Home Automation Features

Once your basic Wi-Fi relay control system is working, you can add more features to make your IoT project smarter.

A. Automatic Light Control Using a PIR Sensor

A PIR motion sensor detects movement and can send a signal to the ESP32.

You can program the ESP32 to switch a demonstration light ON when motion is detected and turn it OFF after a selected period.

B. Temperature-Based Fan Automation

Connect a suitable temperature sensor such as DHT11 or DHT22 to the ESP32.

The system can monitor room temperature and control a fan through an appropriately designed switching circuit.

C. Mobile App Integration

You can extend the project with an IoT platform or custom mobile application to control and monitor connected devices.

D. Voice-Controlled Home Automation

Voice assistants can be integrated through supported smart home platforms and automation services.

For example, you could create a system where a voice command triggers a light-control action.

E. Automatic Scheduling

You can program the ESP32 to perform scheduled actions, such as switching a low-voltage demonstration light ON at a specific time.

These features can transform a basic ESP32 relay project into a more advanced smart home automation system.

11. ESP32 vs Arduino Uno for Home Automation

Many beginners wonder whether they should use Arduino Uno or ESP32 for a smart home project.

Both boards are useful, but they have different capabilities.

Feature ESP32 Arduino Uno R3
Wi-Fi Built-in on common models Requires additional module
Bluetooth Available on supported models Not built-in
Operating Logic 3.3V 5V
GPIO More available pins on many variants 14 digital I/O
Processing More powerful More limited
IoT Applications Excellent Possible with extra hardware
Programming Arduino IDE supported Arduino IDE supported
Best Use Wireless automation Basic electronics projects

Our recommendation: If your main goal is to build Wi-Fi-based smart home automation, ESP32 is generally the better starting point. Arduino Uno remains a good option for learning basic microcontroller programming and electronics.

12. Common ESP32 Relay Module Problems and Solutions

Sometimes your relay module may not respond correctly after connecting it to an ESP32.

Here are some common problems and troubleshooting methods.

Problem Possible Cause Solution
Relay does not activate Incompatible 3.3V input Use a compatible relay module or interface
Relay activates automatically Active-LOW input logic Check relay trigger polarity
ESP32 keeps restarting Insufficient power supply Use a suitable regulated supply
Wi-Fi does not connect Incorrect credentials Verify Wi-Fi name and password
Relay clicks but load does not work Incorrect contact selection Check COM, NO and NC
Multiple relays behave unpredictably Supply limitations Check relay coil power requirements
Web page does not open Wrong IP address Check Serial Monitor
GPIO does not respond Incorrect pin configuration Verify pin numbers and wiring

Important Troubleshooting Tips

  • Always check the ESP32 power supply.

  • Use a relay board compatible with 3.3V logic.

  • Avoid using ESP32 boot-strapping pins for relay control unless you understand their startup behaviour.

  • Test each relay channel separately.

  • Check the Serial Monitor for Wi-Fi connection information.

  • Make sure your smartphone and ESP32 are on the same local network.

13. Safety Precautions for Smart Home Automation Projects

Safety is extremely important when developing an ESP32-based home automation system.

A relay module may use a low-voltage control signal, but its switching contacts can be connected to dangerous household electricity.

Follow these precautions:

  1. Begin your project with low-voltage DC loads.

  2. Never touch exposed electrical terminals.

  3. Never work on live household wiring.

  4. Use properly rated and enclosed switching equipment.

  5. Ensure suitable fusing and overcurrent protection.

  6. Keep the ESP32 and low-voltage electronics separated from hazardous mains connections.

  7. Use qualified electricians for household AC installation.

  8. Never assume that an optocoupler or a relay board automatically provides a safe mains installation.

  9. Test your code and relay logic before connecting any real appliance.

For a student project or electronics demonstration, a low-voltage LED or DC load is a safer way to demonstrate the complete switching process.

14. Applications of ESP32 Smart Home Automation

ESP32 home automation systems can be used in many IoT and electronics applications.

Some popular examples include:

  • Smart room lighting systems.

  • Wireless fan-control prototypes.

  • Automatic garden irrigation.

  • Smart energy monitoring.

  • Temperature-controlled ventilation.

  • Motion-based lighting demonstrations.

  • Remote monitoring systems.

  • IoT-based university projects.

  • Smart laboratory automation.

  • Wireless electrical control prototypes.

These applications make ESP32 a useful platform for learning embedded systems, wireless communication, and IoT development.

Frequently Asked Questions (FAQs)

1. Can ESP32 control home appliances using Wi-Fi?

Yes. ESP32 has built-in Wi-Fi on common development board models. It can communicate with a smartphone or web interface and control compatible relay modules.

2. Which relay module is best for ESP32?

A 1-channel, 2-channel, or 4-channel relay module with verified 3.3V logic compatibility is suitable, depending on how many loads you want to control.

3. Can I use a 5V relay module with ESP32?

Some 5V relay modules accept 3.3V logic signals, while others do not. Check the manufacturer’s specifications and use a suitable interface if required. Never apply 5V directly to an ESP32 GPIO.

4. How many relays can ESP32 control?

ESP32 can control multiple relay channels using its GPIO pins. The practical number depends on the particular ESP32 board, available pins, power requirements, and pin restrictions.

5. Can I control ESP32 home automation without the internet?

Yes. You can create a local Wi-Fi network using your router or ESP32 access-point mode. A smartphone can communicate with the ESP32 without an internet connection.

6. Can I control lights and fans using ESP32?

Yes. An appropriately designed and safely installed switching system can control compatible lights and fans. Household mains connections must be handled by a qualified electrician.

7. Is ESP32 suitable for a university final-year project?

Yes. ESP32 is suitable for IoT-based final-year projects involving smart home automation, wireless monitoring, sensor integration, and embedded control systems.

8. What programming software is used for ESP32?

Arduino IDE is a popular choice for beginners. ESP32 can also be programmed using ESP-IDF and other supported development environments.

9. What is the difference between a relay and a transistor?

A relay is an electrically controlled mechanical switch that provides contact-based switching. A transistor is a semiconductor device commonly used for electronic switching and amplification. The correct choice depends on the load and circuit requirements.

10. Where can I buy ESP32 boards and relay modules in Pakistan?

You can explore ESP32 development boards, relay modules, sensors, jumper wires, and other IoT components at Electroway.org.

Conclusion

Smart home automation with ESP32 and relay modules is an excellent electronics and IoT project for beginners, students, and developers.

By combining an ESP32 development board with a compatible relay module, you can create a wireless control system that operates through a smartphone or web browser.

Start with a simple one-channel relay project using a low-voltage DC load. Once you understand the GPIO connections, relay operation, and Wi-Fi communication, you can expand your system to multiple channels and add sensors, scheduling, and advanced automation features.

Remember that safe electrical design is essential, especially when working with household AC appliances.

If you are looking for ESP32 boards, relay modules, sensors, power supplies, and other electronics accessories in Pakistan, explore Electroway.org. You can also explore the Electroway app for your electronics component shopping needs.

Build your smart home, explore IoT technology, and turn your electronics ideas into reality with Electroway!