ESP8266 - Control Relay via Web

This tutorial instructs you how to control an relay through a web interface using a browser on a PC or smartphone, utilizing the ESP8266. In detail, , the ESP8266 will be programmed to work as a web server. Let's assume that the IP address of the ESP8266 is 192.168.0.3. Here are the details of how it works:

ESP8266 NodeMCU relay web browser

We will learn through two example codes:

The tutorial offers the fundamentals that you can readily and innovatively customize to achieve the following:

Hardware Preparation

1×ESP8266 NodeMCU
1×USB Cable Type-C
1×Relay
1×Jumper Wires
1×Breadboard
1×(Optional) Solenoid Lock
1×(Optional) 12V Power Adapter
1×(Optional) DC Power Jack
1×(Recommended) Screw Terminal Expansion Board for ESP8266
1×(Recommended) Power Splitter For ESP8266 Type-C

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of relay and ESP8266

If you do not know about relay and ESP8266 (pinout, how it works, how to program ...), learn about them in the following tutorials:

Wiring Diagram

The wiring diagram between ESP8266 NodeMCU and relay

This image is created using Fritzing. Click to enlarge image

See more in ESP8266's pinout and how to supply power to the ESP8266 and other components.

ESP8266 Code - HTML content is embedded into ESP8266 code

/* * This ESP8266 NodeMCU code was developed by newbiely.com * * This ESP8266 NodeMCU code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp8266/esp8266-controls-relay-via-web */ #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #define RELAY_PIN D8 // The ESP8266 pin connected to Relay const char *ssid = "YOUR_WIFI_SSID"; // CHANGE IT const char *password = "YOUR_WIFI_PASSWORD"; // CHANGE IT ESP8266WebServer server(80); // Web server on port 80 int relay_state = LOW; String getHTML() { String html = "<!DOCTYPE HTML>"; html += "<html>"; html += "<head>"; html += "<link rel='icon' href='data:,'>"; html += "</head>"; html += "<p>Relay state: <span style='color: red;'>"; if (relay_state == LOW) html += "OFF"; else html += "ON"; html += "</span></p>"; html += "<a href='/relay1/on'>Turn ON</a>"; html += "<br><br>"; html += "<a href='/relay1/off'>Turn OFF</a>"; html += "</html>"; return html; } void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); digitalWrite(RELAY_PIN, relay_state); // Connect to Wi-Fi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.println("Connected to WiFi"); // Print the ESP8266's IP address Serial.print("ESP8266 Web Server's IP address: "); Serial.println(WiFi.localIP()); // home page server.on("/", HTTP_GET, []() { Serial.println("ESP8266 Web Server: New request received:"); Serial.println("GET /"); server.send(200, "text/html", getHTML()); }); // Route to control the Relay server.on("/relay1/on", HTTP_GET, []() { Serial.println("ESP8266 Web Server: New request received:"); Serial.println("GET /relay1/on"); relay_state = HIGH; digitalWrite(RELAY_PIN, relay_state); server.send(200, "text/html", getHTML()); }); server.on("/relay1/off", HTTP_GET, []() { Serial.println("ESP8266 Web Server: New request received:"); Serial.println("GET /relay1/off"); relay_state = LOW; digitalWrite(RELAY_PIN, relay_state); server.send(200, "text/html", getHTML()); }); // Start the server server.begin(); } void loop() { // Handle client requests server.handleClient(); // Your code here }

Detailed Instructions

To get started with ESP8266 on Arduino IDE, follow these steps:

  • Check out the how to setup environment for ESP8266 on Arduino IDE tutorial if this is your first time using ESP8266.
  • Wire the components as shown in the diagram.
  • Connect the ESP8266 board to your computer using a USB cable.
  • Open Arduino IDE on your computer.
  • Choose the correct ESP8266 board, such as (e.g. NodeMCU 1.0 (ESP-12E Module)), and its respective COM port.
  • Copy the above code and open with Arduino IDE
  • Change the wifi information (SSID and password) in the code to yours
  • Click Upload button on Arduino IDE to upload code to ESP8266
  • Open the Serial Monitor
  • Check out the result on the Serial Monitor.
COM6
Send
Connecting to WiFi... Connected to WiFi ESP8266 Web Server's IP address: 192.168.0.3
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • You will see an IP address, for example: 192.168.0.3. This is the IP address of the ESP8266 Web Server
  • Open a web browser and enter one of the three formats below into the address bar:
192.168.0.3
192.168.0.3/relay1/on
192.168.0.3/relay1/off
  • Kindly be aware that the IP address might vary. Please verify the current value on the Serial Monitor.
  • You will also see the below output on Serial Monitor
COM6
Send
Connecting to WiFi... Connected to WiFi ESP8266 Web Server's IP address: 192.168.0.3 ESP8266 Web Server: New request recieved: GET / ESP8266 Web Server: New request recieved: GET /relay1/on ESP8266 Web Server: New request recieved: GET /relay1/off
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • Check relay state
  • You will see the web page of ESP8266 board on the web browser as below
ESP8266 NodeMCU relay web browser
  • You are now able to control the relay on/off via the web interface

ESP8266 Code - HTML content is separated from ESP8266 code

As a graphic web page contains a large amount of HTML content, embedding it into the ESP8266 code as before becomes inconvenient. To address this, we need to separate the ESP8266 code and the HTML code into different files:

  • The ESP8266 code will be placed in a .ino file.
  • The HTML code (including HTML, CSS, and Javascript) will be placed in a .h file.

Detailed Instructions

  • Open Arduino IDE and create new sketch, Give it a name, for example, newbiely.com.ino
  • Copy the below code and open with Arduino IDE
/* * This ESP8266 NodeMCU code was developed by newbiely.com * * This ESP8266 NodeMCU code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp8266/esp8266-controls-relay-via-web */ #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include "index.h" // Include the index.h file #define RELAY_PIN D8 // The ESP8266 pin connected to relay const char *ssid = "YOUR_WIFI_SSID"; // CHANGE IT const char *password = "YOUR_WIFI_PASSWORD"; // CHANGE IT ESP8266WebServer server(80); // Web server on port 80 int relay_state = LOW; String getHTML() { String html = webpage; // Use the HTML content from the index.h file html.replace("%RELAY_STATE%", relay_state ? "ON" : "OFF"); // update the relay state return html; } void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); digitalWrite(RELAY_PIN, relay_state); // Connect to Wi-Fi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.println("Connected to WiFi"); // Print the ESP8266's IP address Serial.print("ESP8266 Web Server's IP address: "); Serial.println(WiFi.localIP()); // home page server.on("/", HTTP_GET, []() { Serial.println("ESP8266 Web Server: New request received:"); Serial.println("GET /"); server.send(200, "text/html", getHTML()); }); // Route to control the relay server.on("/relay1/on", HTTP_GET, []() { Serial.println("ESP8266 Web Server: New request received:"); Serial.println("GET /relay1/on"); relay_state = HIGH; digitalWrite(RELAY_PIN, relay_state); server.send(200, "text/html", getHTML()); }); server.on("/relay1/off", HTTP_GET, []() { Serial.println("ESP8266 Web Server: New request received:"); Serial.println("GET /relay1/off"); relay_state = LOW; digitalWrite(RELAY_PIN, relay_state); server.send(200, "text/html", getHTML()); }); // Start the server server.begin(); } void loop() { // Handle client requests server.handleClient(); // Your code here }
  • Change the WiFi information (SSID and password) in the code to yours
  • Create the index.h file On Arduino IDE by:
    • Either click on the button just below the serial monitor icon and choose New Tab, or use Ctrl+Shift+N keys.
    Arduino IDE 2 adds file
    • Give the file's name index.h and click OK button
    Arduino IDE 2 adds file index.h
    • Copy the below code and paste it to the index.h.
    /* * This ESP8266 NodeMCU code was developed by newbiely.com * * This ESP8266 NodeMCU code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp8266/esp8266-controls-relay-via-web */ #ifndef WEBPAGE_H #define WEBPAGE_H const char* webpage = R"=====( <!DOCTYPE HTML> <html> <head> <link rel='icon' href='data:,'> </head> <p>Relay state: <span style='color: red;'>%RELAY_STATE%</span></p> <a href='/relay1/on'>Turn ON</a> <br><br> <a href='/relay1/off'>Turn OFF</a> </html> )====="; #endif
    • Now you have the code in two files: newbiely.com.ino and index.h
    • Click Upload button on Arduino IDE to upload code to ESP8266
    • Access the web page of ESP8266 board via web browser on your PC or smartphone as before. You will see it similar to the previous code as below:
    ESP8266 NodeMCU relay web browser

    ※ NOTE THAT:

    • If you modify the HTML content in the index.h and does not touch anything in newbiely.com.ino file, when you compile and upload code to ESP8266, Arduino IDE will not update the HTML content.
    • To make Arduino IDE update the HTML content in this case, make a change in the newbiely.com.ino file (e.g. adding empty line, add a comment....)

    You can readily and innovatively customize the above ocde to achieve the following:

    • Controlling multiple relays through the web
    • Redesigning the web user interface (UI)

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!