ESP8266 Relay Website

Greetings,

I have been working on the ESP8266 microcontroller for a while now, but still have a long way to go. For my studies, I have to create a website with buttons to control 4-pin-relay and it must send the data to phpMyAdmin, but for now, I'm only focusing on working with 1 relay pin.

So for example, let's say I want to turn on relay 1 on GPIO 5 with a button, but I want to send the data to a database and add a current time stamp and display the table on my website, so it will be obvious when the relay was turned on or off (if I wanted to check when was the last time my lamp got turned on, for example), but I'm really struggling and am asking for help.

I am currently using 000webhost where I have successfully created an insert.php file. With the php file I can insert the data via url:

So i want to combine two codes:

  • the first code is for relay website buttons and turning them on/off
#include <ESP8266WiFi.h>

const char* ssid = "name";
const char* password = "password";

WiFiServer server(80);
String header;

String relay1State = "off";
const int relay1 = 5; // GPIO5 D1

void setup() {
  Serial.begin(115200);
  pinMode(relay1, OUTPUT);
  digitalWrite(relay1, HIGH);

  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();
}

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

  if (client) { 
    Serial.println("New Client.");
    String currentLine = "";
    while (client.connected()) {
      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");
              relay1State = "on";
              digitalWrite(relay1, LOW);
            }
            else if (header.indexOf("GET /5/off") >= 0)
            {
              Serial.println("GPIO 5 off");
              relay1State = "off";
              digitalWrite(relay1, HIGH);
            }

            // Display the HTML web page
            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:,\">");
            // CSS to style the on/off buttons
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #195B6A; border: none; color: white; padding: 12px 24px;");
            client.println("text-decoration: none; font-size: 20px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #77878A;}</style></head>");

            // Web Page Heading
            client.println("<body><h1>NodeMCU Web Server</h1>");

            // Display current state, and ON/OFF buttons for GPIO 5
            client.println("<p>Relay 1 - State " + relay1State + "</p>");
            // If the relay1State is off, it displays the ON button
            if (relay1State == "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("</body></html>");
            client.println();
            
            break;

          } else {
            currentLine = "";
          }
        } else if (c != '\r') { 
          currentLine += c;      
        }
      }
    }
    
    header = "";
    
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}
  • and the second one is for a GET request:
const char* ssid = "your-ssid";
const char* password = "your-password"; 
const char* host = "example.000webhostapp.com";

void setup() { 
Serial.begin(115200); delay(10); 
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.mode(WIFI_STA);
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()); } 

void loop() { 
Serial.print("connecting to ");
Serial.println(host);

WiFiClient client;
const int httpPort = 80;

if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}

String url = "/relay/insert.php/relay1Status=";

Serial.print("Requesting URL: ");
Serial.println(url);

client.print(String("GET ") + url + " HTTP/1.1\r\n" + 
"Host: " + host + "\r\n" + 
"Connection: close\r\n\r\n");

client.stop(); return; } //

while (client.available())
{ 
String line = client.readStringUntil('\r'); Serial.print(line);
}
Serial.println();
}

and I really don't know how to combine them. I've been trying for over 6 months now, and I sincerely hope for advice.

Also, this is my insert.php code:

<?php

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$response = array();
 
if (isset($_GET['relay1Status'])) {
 
    $relay = $_GET['relay1Status'];

    $filepath = realpath (dirname(__FILE__));
	require_once($filepath."/db_connect.php");

    $db = new DB_CONNECT();
 
    $result = mysql_query("INSERT INTO relay(relay1Status) VALUES('$relay')");
 
    if ($result) {
        // successfully inserted 
        $response["success"] = 1;
        $response["message"] = "Data inserted successfully.";
 
        echo json_encode($response);
    } else {
        $response["success"] = 0;
        $response["message"] = "Error.";
        echo json_encode($response);
    }
} else {
    $response["success"] = 0;
    $response["message"] = "Parameters are missing.";
    echo json_encode($response);
}
?>

I already have an atribute for timestamp and autoincrementing id, so I only have to insert one parameter.