0

I have a project to connecting dual esp8266 using client server method, my expectation the server can get command from user from web request, and the request will be forward to client from server to turn on led. But the connection from server always failed

I'm using ESP-12F and programming using Arduino IDE

the code of server :

//--------------------------------------------------------------------------
  #include <ESP8266WiFi.h>
//--------------------------------------------------------------------------
// Membuat Variabel Autentikasi 
//--------------------------------------------------------------------------
  const char* ssid = "master-sport";
  const char* password = "1234567890";
//--------------------------------------------------------------------------
// Mengatur IP Address
//--------------------------------------------------------------------------
  IPAddress CLIENTA(192,168,4,100);
//--------------------------------------------------------------------------
// Create an instance of the server
// specify the port to listen on as an argument
//--------------------------------------------------------------------------
  WiFiServer server(80);
  WiFiClient client;
//===========================================================================
  void setup() {
   Serial.begin(115200);
   delay(10);

  // Mengatur WiFi ----------------------------------------------------------
   Serial.println();
   Serial.print("Configuring access point...");

   WiFi.mode(WIFI_AP);
   WiFi.softAP(ssid, password);

  // Start the server -------------------------------------------------------
   server.begin();
   Serial.println("Server dijalankan");

  // Print the IP address ---------------------------------------------------
   Serial.println(WiFi.localIP());
 }

//===========================================================================

  void loop() {
  // Check if a client has connected ----------------------------------------
    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 req = client.readStringUntil('\r');
   Serial.println(req);
   client.flush();

  // Match the request ------------------------------------------------------
   const char* host;
   int val;
   if (req.indexOf("/sr/0") != -1){
      host = "sa";
      val = 0;
    }
   else if (req.indexOf("/sr/1") != -1){
      host = "sa";
      val = 1;
    }
   else {
     Serial.println("invalid request");
     client.stop();
     return;
    }

   client.flush();
   Serial.println("Client disonnected");


  // Pengiriman data ke client -----------------------------------------------
   int value  = 0; 
   delay(5000);
   ++value;

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

  // Memebuat TCP Connection Menggunakan WiFiClient --------------------------
   const int httpPort = 80;
   if (!client.connect(CLIENTA, httpPort)) {
     Serial.println("connection failed");
     return;
   }

  // Membuat URL untuk dikirimkan -------------------------------------------
   String url = host;
   url += "/";
   url += val;

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

  // Mengirimkan Request ke Client ------------------------------------------
   client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + CLIENTA + "\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;
    }
  }

  // Melihat semua line balasan dari server dan menampilkan di Serial -------
   while(client.available()){
     String line = client.readStringUntil('\r');
     Serial.print(line);
   }

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

Client code :

//--------------------------------------------------------------------------
  #include <ESP8266WiFi.h>
  #include <Adafruit_NeoPixel.h>
  #ifdef __AVR__
  #include <avr/power.h>
  #endif
  #define PIN 13
//--------------------------------------------------------------------------
// Membuat Variabel Autentikasi 
//--------------------------------------------------------------------------
  const char* ssid = "master-sport";
  const char* password = "1234567890";
//--------------------------------------------------------------------------
// Mengatur IP Address
//--------------------------------------------------------------------------
  IPAddress IP(192,168,4,100);
  IPAddress NETMASK(255,255,255,0);
  IPAddress NETWORK(192,168,4,1);
//--------------------------------------------------------------------------
// Create an instance of the server
// specify the port to listen on as an argument
//--------------------------------------------------------------------------
  WiFiServer server(80);
//--------------------------------------------------------------------------
// Menasukan LED RGB
//--------------------------------------------------------------------------
  Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800);
//===========================================================================
  void setup() {
   Serial.begin(115200);
   delay(10);

  // Connect to WiFi network ------------------------------------------------
   Serial.println();
   Serial.println();
   Serial.print("Connecting to ");
   Serial.println(ssid);

  // Mengatur WiFi ----------------------------------------------------------
   WiFi.mode(WIFI_STA);
   WiFi.begin(ssid, password);
   WiFi.config(IP, NETMASK, NETWORK);

   while (WiFi.status() != WL_CONNECTED) {
     delay(500);
     Serial.print(".");
   }
   Serial.println("");
   Serial.println("WiFi connected");

  // Start the server -------------------------------------------------------
   server.begin();
   Serial.println("Server dijalankan");

  // Menjalankan LED RGB ----------------------------------------------------
   strip.begin();
   strip.show();

  // Print the IP address ---------------------------------------------------
   Serial.println(WiFi.localIP());
 }

//===========================================================================

  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 req = client.readStringUntil('\r');
   Serial.println(req);
   client.flush();

  // Match the request ------------------------------------------------------
   int val;
   if (req.indexOf("/sa/0") != -1){
      strip.setPixelColor(4,0x000000); //LED menjadi mati -------------------
      strip.show();
    }
   else if (req.indexOf("/sa/1") != -1){
      strip.setPixelColor(4, 0xFF0000); //LED menjadi merah -----------------
      strip.show();
    }
   else {
     Serial.println("invalid request");
     client.stop();
     return;
    }

   client.flush();
   Serial.println("Client disonnected");
}

//============================================================================

whats wrong that code ?

5
  • Could you describe exactly how it fails, please? Does the client (station) connect to the server (access point)? Do you get the "new client" log? And so on...
    – Mark Smith
    Commented Nov 23, 2016 at 22:46
  • the client connect to server but if my computer connect to and i try to scanning that network, client address can't detected. i want to sending data to server from my computer, when data be received to server, data will be continued send to client. but communication failed when the server sending data to client Commented Nov 24, 2016 at 3:14
  • I don't understand, sorry, but here's my advice: solve one problem at a time. Write enough code to do the first little part of the problem. Test it. If that doesn't work, ask for help with a clear description of ONLY the problem, and only the code required to see the problem.
    – Mark Smith
    Commented Nov 24, 2016 at 7:07
  • Your question is a bit difficult to understand but if I'm right, you want to connect an ESP to another ESP (which acts as a server) and then connect with your computer to get addresses? Well, the ESP is a very capable device, but not thát capable. I've worked with ESPs in a previous project and I decided to buy a portable wifi router (à €25) to which all the devices could connect. Furthermore, when you do get the ESPs to work as client and server, you can only connect 4 devices to an ESP. That's its limit.
    – Len
    Commented Nov 24, 2016 at 8:54
  • Your server appears to be a client, sending a GET request. Commented Apr 4, 2017 at 11:31

1 Answer 1

1

You do not need 2 ESPs, one is enough. Here you are the code so you can turn on the NeoPixel using web interface:

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

IPAddress ip(192,168,1,81);         // choose IP address
IPAddress subnet(255,255,255,0);

ESP8266WebServer server(80);

void handleRoot() {
  String page = "<!DOCTYPE html>\n";

  page += "<html>\n<body>\n<h1>Some heading</h1><br>Generated by ESP8266\n</body>\n</html>";
  server.send(200, "text/html", page);
}

// what to do when accessed through http://ip_address/something_undefined
void handleNotFound(){
  String message = "File not found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

void setup(void){
  Serial.begin(74880);                      // so you can see debug messages automatically sent by ESP8266
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(ip, ip, subnet);        // declared as: bool softAPConfig (IPAddress local_ip, IPAddress gateway, IPAddress subnet)
  WiFi.softAP("SOME_NAME", "password", 7);  // network name, network password, wifi channel

  IPAddress myIP = WiFi.softAPIP();
  Serial.println();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  server.on("/", handleRoot);               // what to do when accessed through browser using http://IP_address

  // what to do when accessed through http://ip_address/test
  server.on("/test", [](){
    server.send(200, "text/plain", "This is another page");
  });

  server.on("/sa/1", [](){
    // ... <-- put here the code for NeoPixel = on
    server.send(200, "text/html", "NeoPixel is now on");
  });

  server.on("/sa/0", [](){
    // ... <-- put here the code for NeoPixel = off
    server.send(200, "text/html", "NeoPixel is now off");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started...");
}

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

Now you can use xx.xx.xx.xx/sa/1 and xx.xx.xx.xx/sa/0 (where xx.xx.xx.xx is an IP address you've chosen) to turn on/off the NeoPixel.

Just add the Adafruit library for controlling NeoPixel and copy the NeoPixel setup and the code to turn it on/off from your code #2 to the appropriate places (I marked the place where to put the code to turn the NeoPixel on/off with the comments).

If you really want to add another ESP8266 then you have to set it up as a server using the same code - just change the network name, password & IP address and add sending GET request from your first ESP to the second.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.