Multiple esp8266 communicating through Wi-Fi to turn on the internal led on the board

Hello, I am fairly new to coding so i was wondering if anyone could help me with an issue. i'm trying to write a piece of code so for example I am writing arduino code by using two esp8266' currently communicating just text to each other over the same wi-fi connection. But I want to expand this so if the client esp says to the server esp "turn on red led" it would turn on the internal led the same as turning off etc.

Show us what you've done so far, which type of ESP8266's are you using ?

Well there are many ways to get there. Before i get 1 unit to tell the other what to do, i tend to get them to respond to my human orders first.

i am using a feather huzzah ESP8266
This is the code for the server

/*  Server 
 *  Connects to the home WiFi network
 *  Asks some network parameters
 *  Starts WiFi server with fix IP and listens
 *  Receives and sends messages to the client
 *  Communicates: wifi_client_01.ino
 */
#include <SPI.h>
#include <ESP8266WiFi.h>

byte ledPin = 0;
char ssid[] = "******";               // SSID of your home WiFi
char pass[] = "******";               // password of your home WiFi
WiFiServer server(80);                    

IPAddress ip(192, 168, *,*);            // IP address of the server
IPAddress gateway(192,168,1,);           // gateway of your network
IPAddress subnet(255,255,255,0);          // subnet mask of your network

void setup() {
  Serial.begin(115200);                   // only for debug
  WiFi.config(ip, gateway, subnet);       // forces to use the fix IP
  WiFi.begin(ssid, pass);                 // connects to the WiFi router
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  server.begin();                         // starts the server
/*  Serial.println("Connected to wifi");
  Serial.print("Status: "); Serial.println(WiFi.status());  // some parameters from the network
  Serial.print("IP: ");     Serial.println(WiFi.localIP());
  Serial.print("Subnet: "); Serial.println(WiFi.subnetMask());
  Serial.print("Gateway: "); Serial.println(WiFi.gatewayIP());
  Serial.print("SSID: "); Serial.println(WiFi.SSID());
  Serial.print("Signal: "); Serial.println(WiFi.RSSI());
  Serial.print("Networks: "); Serial.println(WiFi.scanNetworks());*/
  pinMode(ledPin, OUTPUT);
}

void loop () {
  WiFiClient client = server.available();
  if (client) {
    if (client.connected()) {
      digitalWrite(ledPin, LOW);  // to show the communication only (inverted logic)
      Serial.println(".");
      String request = client.readStringUntil('\r');    // receives the message from the client
      Serial.print("From client: "); Serial.println(request);
      client.flush();
      client.println("Hi client! No, I am listening.\r"); // sends the answer to the client
      digitalWrite(ledPin, HIGH);
    }
    client.stop();                // tarminates the connection with the client
  }
}

This is the code for the client

#include <SPI.h>
#include <ESP8266WiFi.h>

byte ledPin = 0;
char ssid[] = "*****";           // SSID of your home WiFi
char pass[] = "******";            // password of your home WiFi

unsigned long askTimer = 0;

IPAddress server(192,168,*,*);       // the fix IP address of the server
WiFiClient client;

void setup() {
  Serial.begin(115200);               // only for debug
  WiFi.begin(ssid, pass);             // connects to the WiFi router
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
/*  Serial.println("Connected to wifi");
  Serial.print("Status: "); Serial.println(WiFi.status());    // Network parameters
  Serial.print("IP: ");     Serial.println(WiFi.localIP());
  Serial.print("Subnet: "); Serial.println(WiFi.subnetMask());
  Serial.print("Gateway: "); Serial.println(WiFi.gatewayIP());
  Serial.print("SSID: "); Serial.println(WiFi.SSID());
  Serial.print("Signal: "); Serial.println(WiFi.RSSI());*/
  pinMode(ledPin, OUTPUT);
}

void loop () {
  client.connect(server, 80);   // Connection to the server
  digitalWrite(ledPin, LOW);    // to show the communication only (inverted logic)
  Serial.println(".");
  client.println("Hello server! Are you sleeping?\r");  // sends the message to the server
  String answer = client.readStringUntil('\r');   // receives the answer from the sever
  Serial.println("from server: " + answer);
  client.flush();
  digitalWrite(ledPin, HIGH);
  delay(2000);                  // client will trigger the communication after two seconds
}

And how would I do that? thank you.

Well first of all, your ESP's aren't connected to each other but they are connected to the same network, not that it matters much

There are a few way to communicate between ESP's and what i do is start out with something that is usable for a human.
I create a webpage on a webserver with a few forms on there that result in different actions.

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

const char *ssid = "xxxxx";
const char *password = "xxxxxxxx;
const char *apname = "esp8266";
const char *appass = "password"; // minimum length 8 characters

ESP8266WebServer server(80);

const int ledpin = 2;  // I'm running this on an ESP-01
// i have a led connected to this active LOW
// i can't use the internal (pin 1) for the use of Serial
// on most other ESP8266's there is an internal led on GPOI 2

uint8_t ledstatus = 0; // this is keeping track of the state (of our statemachine)

const char   // like this these lines are statically declared and const, so we can't change them at all
*pageheader = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">",
 *htmlhead = "<html><head><title>ESPwebserver</title><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ></head>",
  *bodystyle = "<body style=\"color: wheat; background-color: teal; font-size: 12pt; font-family: sans-serif;\">",
   *accessIP = "http://192.168.4.1",
    *htmlclose = "</body></html>";

String webIP;

void setup() {
  webIP.reserve(30);  // prevent fragments
  digitalWrite(ledpin, HIGH);
  pinMode(ledpin, OUTPUT);

  Serial.begin(115200);

  WiFi.softAP(apname, appass); // start AP mode
  webIP = accessIP;
  Serial.print("Started Access Point \"");
  Serial.print(apname);
  Serial.println("\"");
  Serial.print("With password \"");
  Serial.print(appass);
  Serial.println("\"");
  WiFi.begin(ssid, password);  // attempt starting STA mode
  Serial.println("Attempting to start Station mode");

  uint32_t moment = millis();
  while ((WiFi.status() != WL_CONNECTED) && (millis() < moment + 8000)) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

    if (MDNS.begin("esp8266")) {  // type esp8266.local/ in your browser
      Serial.println("MDNS responder started, type esp8266.local/ in your browser");
    }
    webIP = StationIP();
  }
  else if (WiFi.status() == WL_CONNECT_FAILED) {
    Serial.print("Connecting to ");
    Serial.print(ssid);
    Serial.println(" Unsuccessful.");
  }
  else if (WiFi.status() == WL_NO_SSID_AVAIL) {
    Serial.print("Network ");
    Serial.print(ssid);
    Serial.println(" not available.");
  }
  WiFi.reconnect();   // reconnect AP after attempting to connect STA

  server.on("/", handleRoot);
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
  checkLedStatus();
}

void checkLedStatus() {  // our statemachine
  switch (ledstatus) {
    case 0: {
        digitalWrite(ledpin, HIGH);
        return;
      }
    case 1: {
        digitalWrite(ledpin, LOW);
        return;
      }
    case 2: {
        if (ledBlink(500)) ; // here the return value (of ledBlink() ) gets discarded
        return;
      }
    case 3: {
        modulateLed();
        return;
      }
  }
}

void modulateLed() {
  static uint16_t ms = 100;
  static bool increase = true;

  if (!ledBlink(ms)) return;
  if (ms > 250) increase = false;
  if (ms < 20) increase = true;
  if (increase) ms = (ms * 10) / 9;
  else ms = (ms * 9) / 10;
}

bool ledBlink(uint32_t wait) {
  static bool pinstate = false;
  static uint32_t moment = millis();
  if (millis() > moment + wait) {
    pinstate = !pinstate;
    moment = millis();
    if (pinstate) digitalWrite(ledpin, LOW);
    else digitalWrite(ledpin, HIGH);
    return pinstate;  // if pinstate is true and the pinstate has changed, the modulator will change speed
  }
  return false;
}

void handleRoot() {
  String ledstatusupdate;
  if (server.hasArg("led")) {
    if (server.arg("led") == "off") {
      ledstatus = 0;
      ledstatusupdate = "The LED has been turned Off<br>";
    }
    else if (server.arg("led") == "on") {
      ledstatus = 1;
      ledstatusupdate = "The LED has been turned On<br>";
    }
    else if (server.arg("led") == "blink") {
      ledstatus = 2;
      ledstatusupdate = "The LED has been set to Blink<br>";
    }
    else if (server.arg("led") == "modulate") {
      ledstatus = 3;
      ledstatusupdate = "The LED has been set to Modulate<br>";
    }
  }

  String s = "";
  s += pageheader;
  s += htmlhead;
  s += bodystyle;

  s += "<h1>Welcome to ESP webserver</h1><p>From here you can control your LED making it blink or just turn on or off. ";
  s += "</p>";

  s += ledstatusupdate;
  s += "<br>";

  s += "<form action=\"";
  s += webIP;
  s += "\" method=\"get\" name=\"button\">";
  s += "<input type=\"hidden\" name=\"led\" value=\"on\">"; // the hidden parameter gets included
  s += "<input type=\"submit\" value=\" LED ON \"></form><br>"; // the button simply submits the form

  s += "<form action=\"";
  s += webIP;
  s += "\" method=\"get\" name=\"button\">";
  s += "<input type=\"hidden\" name=\"led\" value=\"off\">";
  s += "<input type=\"submit\" value=\" LED OFF\"></form><br>";

  s += "<form action=\"";
  s += webIP;
  s += "\" method=\"get\" name=\"button\">";
  s += "<input type=\"hidden\" name=\"led\" value=\"blink\">";
  s += "<input type=\"submit\" value=\"  BLINK  \"></form><br>";

  s += "<form action=\"";
  s += webIP;
  s += "\" method=\"get\" name=\"button\">";
  s += "<input type=\"hidden\" name=\"led\" value=\"modulate\">";
  s += "<input type=\"submit\" value=\"MODULATE\"></form><br>";

  s += htmlclose;
  yield();  // not stricktly neccesary, though the String class can be slow
  server.send(200, "text/html", s); //Send web page
}


String StationIP() {
  String stationIP = "http://";
  stationIP += WiFi.localIP().toString();
  return stationIP;
}

once i have that working, i can create a node that can send a POST or a GET request to perform the same the submission of those forms.

Thank you very much for your help, i was on holidays so only back now, i've gotten more complex in it, I would like to eventually have 1 server and 3 clients, so 4 ESPs, so i want the server to say "client 1 turn on led" and it turn on the light for client 1 etc. But i'm not sure to do this, I would need the ESPs to be connected to each other wirelessly or connected to the same network. firstly i'm trying to get 1 client to respond to one server, but i'm just stuck i don't know where to start from your code.

Firstly you should start with getting the ESP to respond to human commands.

So once you have got this going, you can try and get your 'client' to connect to this 'server' and send the 'get' request that is now executed by the form in the browser from that. Have a look at the Examples -> ESP8266WiFi -> WiFiClient Example

/*
    This sketch sends data via HTTP GET requests to data.sparkfun.com service.

    You need to get streamId and privateKey at data.sparkfun.com and paste them
    below. Or just customize this script to talk to other HTTP servers.

*/

#include <ESP8266WiFi.h>

const char* ssid     = "your-ssid";
const char* password = "your-password";

const char* host = "data.sparkfun.com";
const char* streamId   = "....................";
const char* privateKey = "....................";

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

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  /* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
     would try to act as both a client and an access-point and could cause
     network-issues with your other WiFi-devices on your WiFi-network. */
  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());
}

int value = 0;

void loop() {
  delay(5000);
  ++value;

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;         // create the client
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {   // connect the client
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request   // For our purpose we would be sending a different URL of course
  String url = "/input/";           // ours would be the same as the 'get' request that is normally made by the browser
  url += streamId;
  url += "?private_key=";
  url += privateKey;
  url += "&value=";
  url += value;

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

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }

  // Read all the lines of the reply from server and print them to Serial
  while (client.available()) {
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");
}

Actually i think what you want is the opposite, 3 servers and 1 client connecting to each of them. Of course this client will also act as a server for human commands.

But let's take this step by step, make sure you can control the LED from the first code from your browser, and copy the URL that is send by the html-form to do so.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.