The use of the ESP8266 in the world of IoT

User avatar
By Majik
#75792 Hi there, I'm new to Arduino and programming so please bear with me. I found a great example how to employ my D1 Mini to toggle a relay via a webpage on my local network. This is the code that works for me:

Code: Select all//This example will use a static IP to control the switching of a relay. Over LAN using a web browser.
//A lot of this code have been resued from the example on the ESP8266 Learning Webpage below.
//http://www.esp8266learning.com/wemos-webserver-example.php

//CODE START
//1
#include <ESP8266WiFi.h>

// Below you will need to use your own WIFI informaiton.
//2
const char* ssid = "myssid"; //WIFI Name, WeMo will only connect to a 2.4GHz network.
const char* password = "mypassword"; //WIFI Password

//defining the pin and setting up the "server"
//3
int relayPin = D1; // The Shield uses pin 1 for the relay
WiFiServer server(80);
IPAddress ip(192, 168, 178, 77); // where xx is the desired IP Address
IPAddress gateway(192, 168, 178, 1); // set gateway to match your network
IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your network


// void setup is where we initialize variables, pin modes, start using libraries, etc.
//The setup function will only run once, after each powerup or reset of the wemos board.
//4
void setup() {
  Serial.begin(115200);
  delay(10);
 

  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW);
 
  Serial.print(F("Setting static ip to : "));
  Serial.println(ip);
 
  // Connect to WiFi network
  //5
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.config(ip, gateway, subnet);
  WiFi.begin(ssid, password);
  //Trying to connect it will display dots
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
 
  // Start the server
  server.begin();
  Serial.println("Server started");
 
  // Print the IP address
  Serial.print("Use this URL : ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}

//void loop is where you put all your code. it is a function that returns nothing and will repeat over and over again
//6
void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
 
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
 
  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
 
  //Match the request, checking to see what the currect state is
  int value = LOW;
  if (request.indexOf("/relay=ON") != -1) {
    digitalWrite(relayPin, HIGH);
    value = HIGH;
  }
  if (request.indexOf("/relay=OFF") != -1){
    digitalWrite(relayPin, LOW);
    value = LOW;
  }
  // Return the response, build the html page
  //7
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
 
  client.print("Relay is now: ");
 
  if(value == HIGH) {
    client.print("Engaged (ON)"); 
  } else {
    client.print("Disengaged (OFF)");
  }
  client.println("<br><br><br>");
  client.println("<a href=\"/relay=ON\">Click here to engage (Turn ON) the relay.</a> <br><br><br>");
  client.println("<a href=\"/relay=OFF\">Click here to disengage (Turn OFF) the relay.</a><br>");
  client.println("</html>");
 
  delay(1);
  Serial.println("Client disconnected");
  Serial.println("");
 
}//END


I used this in conjunction with 1 relay and it works fine. I now want to use it with multiple relays so I made some changes in the code to add a second one, however, I must have missed something as the link to switch the second relay on or off still switches the first relay, see code:

Code: Select all//This example will use a static IP to control the switching of a relay. Over LAN using a web browser.
//A lot of this code have been resued from the example on the ESP8266 Learning Webpage below.
//http://www.esp8266learning.com/wemos-webserver-example.php

//CODE START
//1
#include <ESP8266WiFi.h>

// Below you will need to use your own WIFI informaiton.
//2
const char* ssid = "myssid"; //WIFI Name, WeMo will only connect to a 2.4GHz network.
const char* password = "mypassword"; //WIFI Password

//defining the pin and setting up the "server"
//3
int relayPin1 = D1; // The Shield uses pin 1 for relay 1
int relayPin2 = D2; // The Shield uses pin 2 for relay 2

WiFiServer server(80);
IPAddress ip(192, 168, 178, 77); // where xx is the desired IP Address
IPAddress gateway(192, 168, 178, 1); // set gateway to match your network
IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your network


// void setup is where we initialize variables, pin modes, start using libraries, etc.
//The setup function will only run once, after each powerup or reset of the wemos board.
//4
void setup() {
  Serial.begin(115200);
  delay(10);
 

  pinMode(relayPin1, OUTPUT);
  digitalWrite(relayPin1, LOW);

  pinMode(relayPin2, OUTPUT);
  digitalWrite(relayPin2, LOW);

  Serial.print(F("Setting static ip to : "));
  Serial.println(ip);
 
  // Connect to WiFi network
  //5
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.config(ip, gateway, subnet);
  WiFi.begin(ssid, password);
  //Trying to connect it will display dots
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
 
  // Start the server
  server.begin();
  Serial.println("Server started");
 
  // Print the IP address
  Serial.print("Use this URL : ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}

//void loop is where you put all your code. it is a function that returns nothing and will repeat over and over again
//6
void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
 
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
 
  // Read the first line of the 1st request
  String request1 = client.readStringUntil('\r');
  Serial.println(request1);
  client.flush();
 
  //Match the 1st request, checking to see what the currect state is
  int value1 = LOW;
  if (request1.indexOf("/relay=ON") != -1) {
    digitalWrite(relayPin1, HIGH);
    value1 = HIGH;
  }
  if (request1.indexOf("/relay=OFF") != -1){
    digitalWrite(relayPin1, LOW);
    value1 = LOW;
  }

    // Read the first line of the 2nd request
  String request2 = client.readStringUntil('\r');
  Serial.println(request2);
  client.flush();
 
  //Match the 1st request, checking to see what the currect state is
  int value2 = LOW;
  if (request2.indexOf("/relay=ON") != -1) {
    digitalWrite(relayPin2, HIGH);
    value2 = HIGH;
  }
  if (request2.indexOf("/relay=OFF") != -1){
    digitalWrite(relayPin2, LOW);
    value2 = LOW;
  }
  // Return the response, build the html page
  //7
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
 
  client.print("Relay 1 is now: ");
 
  if(value1 == HIGH) {
    client.print("Engaged (ON)"); 
  } else {
    client.print("Disengaged (OFF)");
  }
  client.println("<br><br><br>");
  client.println("<a href=\"/relay=ON\">Click here to engage (Turn ON) relay 1.</a> <br><br><br>");
  client.println("<a href=\"/relay=OFF\">Click here to disengage (Turn OFF) relay 1.</a><br>");
  client.println("<br><br><br>");

   client.print("Relay 2 is now: ");
 
  if(value2 == HIGH) {
    client.print("Engaged (ON)"); 
  } else {
    client.print("Disengaged (OFF)");
  }
  client.println("<br><br><br>");
  client.println("<a href=\"/relay=ON\">Click here to engage (Turn ON) relay 2.</a> <br><br><br>");
  client.println("<a href=\"/relay=OFF\">Click here to disengage (Turn OFF) relay 2.</a><br>");
  client.println("<br><br><br>");
  client.println("</html>");
 
  delay(1);
  Serial.println("Client disconnected");
  Serial.println("");
 
}//END


I'd appreciate it if someone could point out to me what I need to add or change to make this work.

Thanks in advance!
User avatar
By MigaJohn
#86418 Hello, try this, for me works good, but only problem I'm looking to put a password and login, have you got any idea?
static const uint8_t D0 = 16;
static const uint8_t D1 = 5;
static const uint8_t D2 = 4;
static const uint8_t D3 = 0;
static const uint8_t D4 = 2;
static const uint8_t D5 = 14;
static const uint8_t D6 = 12;
static const uint8_t D7 = 13;
static const uint8_t D8 = 15;
static const uint8_t D9 = 3;
static const uint8_t D10 = 1;

int relay1Pin = D3;//define a pin for relay
int relay2Pin = D5;//define a pin for relay

int relay1State = 1;//initial state . 1 ON, 0 OFF
int relay2State = 1;//initial state . 1 ON, 0 OFF

String button1Title1 ="Light ON";
String button1Title2 ="Light OFF";

String button2Title1 ="Buzzer ON";
String button2Title2 ="Buzzer OFF";



#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>



#ifndef STASSID
#define STASSID "your WiFi SSID" // your WiFi SSID
#define STAPSK "your WiFi password" //your WiFi password
#endif

const char *ssid = STASSID;
const char *password = STAPSK;

ESP8266WebServer server(80);

void handleRoot() {
String HTML ="<!DOCTYPE html>\
<html>\
<head>\
<title>Robojax ESP8266 Relay Control</title>\
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
<style>\
html,body{width:100%\;height:100%\;margin:0}*{box-sizing:border-box}.colorAll{background-color:#90ee90}.colorBtn{background-color:#add8e6}.angleButtdon,a{font-size:30px\;border:1px solid #ccc\;display:table-caption\;padding:7px 10px\;text-decoration:none\;cursor:pointer\;padding:5px 6px 7px 10px}a{display:block}.btn{margin:5px\;border:none\;display:inline-block\;vertical-align:middle\;text-align:center\;white-space:nowrap}";

HTML +="</style></head><body><h1>Robojax ESP8266 2 ch Relay Control </h1>";

if(relay1State){
HTML +="<div class=\"btn\"><a class=\"angleButton\" style=\"background-color:#f56464\" href=\"/control?r1=off\">";
HTML +=button1Title2;
}else{
HTML +="<div class=\"btn\"><a class=\"angleButton \" style=\"background-color:#90ee90\" href=\"/control?r1=on\">";
HTML +=button1Title1;
}
HTML +="</a></div>";

if(relay2State){
HTML +="<div class=\"btn\"><a class=\"angleButton\" style=\"background-color:#f56464\" href=\"/control?r2=off\">";
HTML +=button2Title2;
}else{
HTML +="<div class=\"btn\"><a class=\"angleButton \" style=\"background-color:#90ee90\" href=\"/control?r2=on\">";
HTML +=button2Title1;
}
HTML +="</a></div></body></html>";
server.send(200, "text/html", HTML);
}//handleRoot()

void handleNotFound() {

String message = "File Not Found ";
message += "URI: ";
message += server.uri();
message += "Method: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "Arguments: ";
message += server.args();
message += " ";

for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + " ";
}

server.send(404, "text/plain", message);

}//end of handleNotFound()

void setup(void) {
pinMode(relay1Pin, OUTPUT);// define a pin as output for relay
digitalWrite(relay1Pin, relay1State);//initial state either ON or OFF

pinMode(relay2Pin, OUTPUT);// define a pin as output for relay
digitalWrite(relay2Pin, relay2State);//initial state either ON or OFF

Serial.begin(115200);//initialize the serial monitor

//Relay control ON OFF by Robojax.com


WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");

// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: http://");
Serial.println(WiFi.localIP());

if (MDNS.begin("robojaxESP8266")) {
Serial.println("MDNS responder started");
Serial.println("access it via http://robojaxESP8266");
}

server.on("/", handleRoot);
server.on("/control", HTTP_GET, relayControl);
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");

}//end of setup

void loop(void) {

server.handleClient();
MDNS.update();

if(relay1State ==1)
{
digitalWrite(relay1Pin, LOW);
}else
{
digitalWrite(relay1Pin, HIGH);
}

if(relay2State ==1)
{
digitalWrite(relay2Pin, LOW);
}else{
digitalWrite(relay2Pin, HIGH);
}

delay(100);
//Serial.print("Relay1:");Serial.print (relay1State);
//Serial.print(" Relay2:");Serial.println(relay2State);
}//end of loop

/*
* relayControl()
* updates the value of "relayState" varible to 1 or zero
* returns nothing
* written by Ahmad Shamshiri
* on Wednesday Feb 22, 2020 at 16:20 in Ajax, Ontario, Canada
* http://www.robojax.com
*/
void relayControl() {
if(server.arg("r1") == "on")
{
relay1State = 1;// set state of relay1 to ON
}else if(server.arg("r1") == "off"){
relay1State = 0; // set state of relay1 to OFF
}

if(server.arg("r2") == "on") {
relay2State =1; // set state of relay2 to ON
}else if(server.arg("r2") == "off"){
relay2State =0; // set state of relay2 to OFF
}

handleRoot();
}//relayControl() end


Have a great day