loader
How to Create ESP8266 Web Server to Make Your Own Smart Home

Transform your home into a smart home with our step-by-step guide on How to Create ESP8266 Web Server to Make Your Own Smart Home. The ESP8266 microcontroller, known for its affordability and versatility, allows you to design a personalized smart home solution tailored to your unique preferences. Learn how to control and monitor devices remotely, customize your web interface, and embrace the flexibility of home automation.

Required Hardware Components

Before diving into How to Create ESP8266 Web Server to Make Your Own Smart Home, ensure you have the following hardware components ready:

  • 1 x ESP8266 Node MCU board
  • 1 x USB-to-Micro USB cable
  • 1 x Breadboard
  • 4 x Male to Female Jumper Wire
  • 1 x 2 Channel Relay
  • 2 x Electric Bulb

Getting Started With ESP8266

Getting started with the ESP8266 Node MCU, from setting up the hardware to installing drivers on your PC and running your first sketch into ESP8266. I have explained each and everything into detail here: Getting Started With ESP8266 Node MCU: A Comprehensive Guide.

Prototyping: How to Create ESP8266 Web Server

  • Relay VCC => ESP8266 VIN
  • Relay GND => ESP8266 GND
  • Relay IN2 => ESP8266 D1
  • Relay IN3 => ESP8266 D2
  • On the input side using IN2 & IN3 same as switch

How to Create ESP8266 Web Server to Make Your Own Smart Home - Prototyping

ESP 8266 Sketch for Smart Home

This Arduino code is for creating a simple web server using the ESP8266 microcontroller. The web server allows you to control two GPIO pins, corresponding to two home automation devices (in this case, lights), through a web interface.

#include <ESP8266WiFi.h>

const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

WiFiServer server(80);

String header;

String output5State = "off";
String output4State = "off";

const int output5 = 5; //D1
const int output4 = 4; //D2


unsigned long currentTime = millis();

unsigned long previousTime = 0;

const long timeoutTime = 2000;

IPAddress local_IP(192, 168, 1, 111);
IPAddress gateway(192, 168, 1, 156);
IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8);
IPAddress secondaryDNS(8, 8, 4, 4);

void setup() {
  Serial.begin(115200);

  pinMode(output5, OUTPUT);
  pinMode(output4, OUTPUT);

  digitalWrite(output5, HIGH);
  digitalWrite(output4, HIGH);

 if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
    Serial.println("Failed to configure");
  }

  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  //WiFi.hostname("iotboys");
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop() {
  WiFiClient client = server.available();

  if (client) {
    Serial.println();
    //Serial.print("ESP Board MAC Address:  ");
    //Serial.println(WiFi.macAddress());
    Serial.println("New Client.");
    String currentLine = "";
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) {
      currentTime = millis();
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        header += c;
        if (c == '\n') {
          if (currentLine.length() == 0) {

            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            if (header.indexOf("GET /5/on") >= 0) {
              Serial.println("GPIO 5 on");
              output5State = "on";
              digitalWrite(output5, LOW);
            } else if (header.indexOf("GET /5/off") >= 0) {
              Serial.println("GPIO 5 off");
              output5State = "off";
              digitalWrite(output5, HIGH);
            } else if (header.indexOf("GET /4/on") >= 0) {
              Serial.println("GPIO 4 on");
              output4State = "on";
              digitalWrite(output4, LOW);
            } else if (header.indexOf("GET /4/off") >= 0) {
              Serial.println("GPIO 4 off");
              output4State = "off";
              digitalWrite(output4, HIGH);
            }

            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");

            client.println("<style>html { font-family: Helvetica; display: inline-block;  text-align: center;}");
            client.println("body{ background-color: #111a23; color: #ecf0f1; margin: 0px !important;}");
            client.println("header { background-color: #0c151e; display: flex; align-items: center; justify-content: center; } footer { background-color: #0c151e; position: fixed;bottom: 0;width: 100%; }");
            client.println(".button { background-color: green; border: none; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer; width:35%;}");
            client.println(".logo {max-width: 100px; height: auto;  } .container{ padding:10px; margin-top:25%;} ");
            client.println(".button2 {background-color: red; border: none; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer; width:35%;}</style></head>");
            client.println("<body><header><img class='logo' src='https://iotboys.com/wp-content/uploads/2023/09/cropped-IoTBoys-512x512-1.png' alt='IoTBoys' /><h1>My Smart Home</h1></header>");
            
            
           
            client.println("<div class='container'>");
           
            client.println("<h3>Outdoor Light </h3>");
            if (output4State == "off") {
              client.println("<p><a href=\"/4/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/4/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
           client.println("<h3>Kitchen Light </h3>");
         
            if (output5State == "off") {
              client.println("<p><a href=\"/5/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/5/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</div>");
            client.println("<footer><p>Powered by &copy; IoTBoys</p></footer></body></html>");


            client.println();

            break;
          } else {
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;
        }
      }
    }

    header = "";

    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

Let’s understand the code for ESP8266 Web Server

Libraries and Constants:

#include <ESP8266WiFi.h>

const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

WiFiServer server(80);

String header;

String output5State = "off";
String output4State = "off";

const int output5 = 5; // GPIO 5, mapped to D1 on the NodeMCU board
const int output4 = 4; // GPIO 4, mapped to D2 on the NodeMCU board

unsigned long currentTime = millis();
unsigned long previousTime = 0;
const long timeoutTime = 2000;

IPAddress local_IP(192, 168, 1, 111);
IPAddress gateway(192, 168, 1, 156);
IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8);
IPAddress secondaryDNS(8, 8, 4, 4);

WiFi Configuration: The code sets up the Wi-Fi credentials (SSID and password), establishes a server on port 80, and defines two GPIO pins for controlling devices.

Setup Function:

void setup() {
  Serial.begin(115200);

  pinMode(output5, OUTPUT);
  pinMode(output4, OUTPUT);

  digitalWrite(output5, HIGH);
  digitalWrite(output4, HIGH);

  if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
    Serial.println("Failed to configure");
  }

  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}
  • Serial Communication Setup: Initializes serial communication for debugging.
  • Pin Configuration: Sets the GPIO pins as outputs and initializes them to a HIGH state.
  • Wi-Fi Connection: Connects to the specified Wi-Fi network and prints the assigned IP address.
  • Server Initialization: Begins the web server

Loop Function:

void loop() {
  WiFiClient client = server.available();

  if (client) {
    Serial.println();
    Serial.println("New Client.");
    String currentLine = "";
    currentTime = millis();
    previousTime = currentTime;

    while (client.connected() && currentTime - previousTime <= timeoutTime) {
      currentTime = millis();

      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        header += c;

        if (c == '\n') {
          if (currentLine.length() == 0) {
            // Handling HTTP requests

            // ... (HTTP response handling logic)

            break;
          } else {
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;
        }
      }
    }

    header = "";
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}
  • Server Availability Check: Checks if there’s a client attempting to connect to the server.
  • HTTP Request Handling: Parses incoming HTTP requests and responds accordingly.

HTTP Request Handling:

The code processes HTTP requests to control the state of two GPIO pins based on the specified routes (“/5/on”, “/5/off”, “/4/on”, “/4/off”). It updates the state of the corresponding devices (lights) and generates an HTML response for the web interface.

Web Interface:

The HTML response includes a simple web page with buttons to control the devices. The state of each device is displayed, and the buttons trigger HTTP requests to turn the devices on or off.

Read also: Getting Started with ESP8266 Node MCU: A Comprehensive Guide

Conclusion:

Congratulations! You’ve successfully navigated the intricacies of creating an How to Create ESP8266 Web Server to make your own smart home. This comprehensive guide empowers you to embark on a journey where your imagination sets the limits. Embrace the power of technology and make your smart home vision a reality. Whether you’re a novice or an experienced DIY enthusiast, the ESP8266 is your key to unlocking the full potential of home automation.

Leave a Reply

Your email address will not be published. Required fields are marked *