Communication between two esp8266 wifi modules programmed in arduino ide

Communication between two esp8266 wifi modules programmed in arduino ide


This tutorial is about inter communication between 2 esp8266 WiFi modules. I will explain the method and code of inter communication between two esp8266 modules. I was working on a cool embedded project in which a wireless communication is required between two motors placed a part on a small distance, also the status of the motors needs to monitored and transmitted over the internet. Their are several methods through which i can accomplish this simple task like Bluetooth, RF (radio frequency), GPRS etc. I was working on finding an optimum and best solution to it. Then the idea to inter esp8266 communication comes to mind. It has few advantages. One major is it required few components, only just two esp8266 modules. The inter communication between 2 esp8266 modules can be used for relaying data, as repeaters etc.  

Methods for Inter Esp8266 Communication

Their are two methods through which we can send data between 2 esp8266 modules or through which the esp8266 WiFi modules can talk with each other. In both cases one esp8266 module is in client mode and the other one in server mode.
  1. Send a HTTP request from client to server and the server upon receiving the particular request will perform the desired action, manipulate its Inputs Outputs etc. Consider this method as you are sending an HTTP request(From esp8266) containing data to a website(Server-Host esp8266) and the website than displays the data on a web page(Esp8266 Manipulate I/O Pins).
  2. Send a HTTP request from client to server. Up on receiving the request the server replies client with some useful information.  We read the information at client side and extract the meaningful data from the information forwarded by server. 

Both methods have their own advantages. First method is useful when we have a fixed process to be executed when ever we want and we don't need to pass a real time value or data string etc. For example we want to activate a relay, switch or some home appliance in this case we do not need any real time data string to be manipulated. We can hard code a single request for each peripheral.  Second method is useful when we need real time data like time, date etc. For example we have a RTC(Real Time Clock) at server side and we want to update our date and time(Client Side), for this we need a real time data string whose length will be fairly long. So here the second method fits in.

NodeMcu(Esp8266-12E) and Esp8266-01 talking with each other

I am going to toggle an led connected to Esp8266-01 from NodeMcu Lua Module(Esp8266-12E). For this single task no real time data needs to be manipulated so i am going with first method. Nodemcu will be in client mode and esp8266-01 will be in server mode. 
Communication between two esp8266 wifi modules, sending data and talking with each other.
Communication between two esp8266 wifi modules, sending data and talking with each other.

Esp8266 Client side Circuit Diagram

Communication between nodumcu lua and esp826 01
Communication between nodumcu lua and esp826 01
At client side nodemcu i connected a push button with Pin#D7. Pin#D7 is used as input pin.  A push button is connected in series with an led and a resistor. Resistor is grounded and led is at active high side with push button in series. Active high side is supplied +3.3 volt from the nodemcu lua module. Resistor is also grounded with the nodemcu module ground. Pin#D7 normally remains at low level. But when ever push button is pressed the led lights up and the D7 logic level changes to high.

What i want is when ever the push button(At client) is pressed the led connected at the server side(esp8266-01) toggles. So the circuit at the right side is made to achieve this logic. Nodemcu is powered through PC USB plug. You can remove the Led from the circuit is their are power issues but it worked for me and i have no issue with the same configuration. 

Esp8266 Server Side Circuit Diagram

At sever side led is connected to Pin#2 of esp8266-01 module. Esp8266-01 has only two GPIO's(General Purpose Input Output Pins) GPIO-0 amd GPIO-2. I choose GPIO-2 because GPIO-1 is used during uploading code. A 470 ohm resistor is connected in series to led. Circuit is powered through the same power that we apply to vcc of esp8266 module. Esp8266 is a 3.3 volt chip do not power it with more than 4 volts. The vcc of resistor is connected to vcc of esp8266.

I come across many problems in uploading the code to esp8266-01 from arduino ide and finally i succeeded. I made a tutorial on it after that so that other can take advantage of my learning. I suggest you to take the tutorial before proceeding any further. 
  
Esp8266 communication with nodemcu(esp8266 12E) lua
Esp8266 communication with nodemcu(esp8266 12E) lua

ESp8266 to Esp8266 communication code

I assume that you have previously worked with esp8266 wifi modules and know about its modes soft-AP(Access Point), Station etc other esp8266 configurations and how to send HTTP request with Esp8266 module to server. I also consider that you people are well aware of HTTP get, post requests and their formats.
server.on("/Led", handleRoot);
At sever side i have a page at address http://192.168.4.1/Led. The above statement is from the server code it initializes a function name handleRoot. So now when ever this page is requested by the client its corresponding function handleRoot activates. 192.168.4.1 is server (Esp8266-01) IP Address. The handle root function is below.
void handleRoot() {
  toggle=!toggle;                                                     //Toggling Led Variable
    digitalWrite(2,toggle);                                         //Toggle Led
    String s = "\r\n\r\n<!DOCTYPE HTML>\r\n<html><h1>Esp8266 Communication</h1> ";
    s += "<p>Success!!!</html>\r\n\r\n";
    server.send(200,"text/html",s);                           //Reply to the client
}
When ever the page  http://192.168.4.1/Led is requested by client the above handleRoot function is executed. What this function does is toggles the led, toggle variable is used for this purpose. Then as a reply it sends back a web page (success information) back to client.
Note: If we want to use the second method which was discussed above we can insert our data in this web page (confirmation text) and extract it at the client side. This is not a hard task it requires a fixed string format with know parameters etc. I will make tutorial on it in future.
  
              //Request to server to activate the led
              client.print(String("GET ") +"/Led"+" HTTP/1.1\r\n" +
              "Host: " + host + "\r\n" +
              "Connection: close\r\n\r\n");
At client side the request format is above the "/Led" is the webpage name and host (192.168.4.1) is address of the server. I hope you can understand the above statement.

Important note: Esp8266-01 is used in AP(access point) mode and nodemcu in station mode. Nodemcu is restricted in the client code to connect to the SSID of Esp8266-01 which is 
"ESP_D54736". Server Esp8266-01 is assigning IP to nodemcu client. Their is no password the Esp8266 network is open. Recall high school lectures both devices must be on same network to transfer data between each other. Also some esp8266-01 modules are naughty :D and they did not let change their SSID(Its a question why not roaming on internet?). So if your esp8266-01(server) did not originate with this name "ESP_D54736". Make sure to change the SSID also in the client code.

Project Code - Server Side(ESp8266-01)

Download the project code from the links given at the bottom of the Post.



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

const char* ssid = "ESP_D54736";  // SSID of esp8266
//const char* password = "123";   //
bool toggle=0;                  //Variable to switch on and off the solenoid
ESP8266WebServer server(80);    //Specify port for TCP connection

void handleRoot() {
  toggle=!toggle;               //Toggling Led Variable
    digitalWrite(2,toggle);     //Toggle Led
        String s = "\r\n\r\n  <!DOCTYPE HTML>\r\n<html><h1>Esp8266 Communication</h1> ";
        s += "<p>Success!!!</html>\r\n\r\n";  
        server.send(200,"text/html",s);      //Reply to the client
}

void setup() {
  delay(200);                           //Stable Wifi
  Serial.begin(115200);                 //Set Baud Rate
  pinMode(2, OUTPUT);                   //Led/Solenoid at pin 2
  WiFi.softAP(ssid);//, password);      //In Access Point Mode

  IPAddress myIP = WiFi.softAPIP();     //Check the IP assigned. Put this Ip in the client host.
  Serial.print("AP IP address: ");
  Serial.println(myIP);         //Print the esp8266-01 IP(Client must also be on the save IP series)
  server.on("/Led", handleRoot);           //Checking client connection
  server.begin();                       // Start the server
  Serial.println("Server started");
}

void loop() {
  // Check if a client has connected. On first connection switch on the Solenoid on next switch off.
  server.handleClient();
}
Arduino

Project Code - Client Side(NodeMcu Lua Esp-12E)

Download the project code from the links given at the bottom of the Post.


#include <ESP8266WiFi.h>
#include <WiFiClient.h> 
//Ip of the Host(Our Case esp8266-01 as server. Its the ip of the esp8266-01 as Access point)
const char* host = "192.168.4.1"; 

void setup() {
  Serial.begin(115200);          //Baud Rate for Communication
  delay(10);                     //Baud rate prper initialization
  pinMode(13,INPUT);             //Pin D7 on NodeMcu Lua. Button to switch on and off the solenoid.
  WiFi.mode(WIFI_STA);           //NodeMcu esp12E in station mode
  WiFi.begin("ESP_D54736");      //Connect to this SSID. In our case esp-01 SSID.  

  while (WiFi.status() != WL_CONNECTED) {      //Wait for getting IP assigned by Access Point/ DHCP. 
  //Our case  esp-01 as Access point will assign IP to nodemcu esp12E.
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());             //Check out the Ip assigned by the esp12E
}

void loop() {

         if(digitalRead(13)==1){    //Check out if Pin D7/13 is high. If high activate 
                                    //the led connected to esp-01. On next press deactivate it. 
              Serial.print("connecting to ");
              Serial.println(host);
              // Use WiFiClient class to create TCP connections
              WiFiClient client;
              const int httpPort = 80;
                if (!client.connect("192.168.4.1", httpPort)) {
                  Serial.println("connection failed");
                  return;
                   }    
              //Request to server to activate the led
              client.print(String("GET ") +"/Led"+" HTTP/1.1\r\n" + 
                           "Host: " + host + "\r\n" + 
                           "Connection: close\r\n\r\n");         
              delay(10);
              // Read all the lines of the reply from server and print them to Serial Monitor etc
              while(client.available()){
                String line = client.readStringUntil('\r');
                Serial.print(line);
              }
              //Close the Connection. Automatically
              Serial.println();
              Serial.println("closing connection");             
            }//End if

}//End Loop
Arduino
Download the Project Code writeen in arduino ide. Folder contains the client and server side code. Please give us your feed back on the project. In case you have any queries please write them below in the comments section.
SHARE

Oscar perez

Arquitecto especialista en gestion de proyectos si necesitas desarrollar algun proyecto en Bogota contactame en el 3006825874 o visita mi pagina en www.arquitectobogota.tk

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comentarios:

Publicar un comentario