ESP8266 Communication With Server and ESP8266

I was working on this project for last 2-3 days. I tried to find resources on the Internet and got a lot of stuff but the complete description from scratch was not present anywhere. Therefore, I decided to start this by myself from scratch.

ESP8266 is a robust and cheap Wi-Fi module, which help you to communicate with the server as well as with other ESP8266. There are two types of communication channels, which one can construct and use in their project.

The first method is to create a LOCAL Server:

1. You can create a LOCAL Server using ESP8266. When it will connect to the internet, it will automatically create a local instance of WEB and will provide you the IP of that server. You can use that IP for communication by reading and writing on it. (You must have used this earlier while making basic Led Controller using WEB). After some days, IP will change because router IP changes in range [DHCP range]

2. You can create a LOCAL Server using ESP8266 with fixed IP. Open your Router settings and in Network Settings find the DHCP range. Choose any IP address outside this range and set it in ESP8266 code. Use Sub Mask and Gateway (Gateway will be the IP address of Router) with IP address and you will be able to communicate with a fixed IP.

However, using a LOCAL Server is not a great deal. We need something robust, which can be used by any Network over WEB from anywhere in the world.

The second method is to create a WWW Server. Now, this method is not easy because you need to buy server space and write the necessary backend files to work. However, there are many websites, which provide free Web Hosting facility to Host your Website and get server space (Limited) for a period free.

In this instructable, I will be using 000WebHost Website, which helps you to make this project efficiently and easily. You do not need any prior knowledge of HTML, CSS, JAVASCRIPT [Frontend languages] and PHP, RUBY ON RAILS [Backend Languages]. I will describe the whole procedure in detail. This instructable may go bit longer, but you must read it completely because you will find everything for ESP8266 Communication here whether you have plans to create a communication channel between several ESPs or between ESP8266 and Server.

Step 1: Requirements

  1. ESP8266 Development Board. [NodeMCU 12e Board] (If you are using ESP 01 board, then also it will work. Just use FTDI to upload code. )
  2. Wi-Fi Connection
  3. Data Cable
  4. Patience

Step 2: Creating Web Server

The first step is to create a WEB SERVER and we will use 000Webhost for this. Go to website https://in.000webhost.com/ and create an account. You will need to follow the instructions and create your website. The website provides you an easy interface where you can choose, drag and drop things to create your first website. Most importantly, create your domain name and remember it. You will get Password for your domain name, do remember that also.

Next step is to create a model on our desk which we will follow while communication to Web Server.

MODEL

There will be a text file with name “datastorage.txt”. We will communicate with this file only. I have two ESP8266 and both are needed to communicate with each other. Therefore, instead of communicating directly, Server will act as an intermediate and both ESPs will communicate with Server. ESP8266 can read the data from the file as well write the data into the file. Each ESP connected to the server will add its key while sending data to file. In addition, this key will be used to recognize the ESP, which wants to communicate.

We need PHP scripts to write data to the file. We do not need PHP script to read data from a file.

Read and Write

I thought it would be very easy for anyone if we can make a custom URL that can be used to write data in the file as well read from the file.

URLs:

Let say:

Your domain name is http://xyz.000webhostapp.com/

Filename is datastorage.txt

URL to access file contents http://xyz.000webhostapp.com/datastorage.txt

Custom URL to write data in the file will be http://xyz.000webhostapp.com/writefile.php?data=n...

[Here “name” in above URL is data, which will be added to file]

Step 3: PHP Script

Now PHP script to append data to file with name "writefile.php"

Open any text Editor and save it with name writefile.php

Paste the below code into the file and again save it.

<?php

$val = $_GET["data"];

$fileContent=$val."\n";

$fileStatus=file_put_contents("datastorage.txt",$fileContent,FILE_APPEND);

if($fileStatus != false)

{

echo "SUCCESS. Data written in file.";

}

else

{

echo "FAIL. Could not connect to file.";

}

?>

Code Explanation:

Code started with initialization (Basic PHP code syntax). Then GET request is added to get the text after the ‘=’ sign in the URL and that text will be saved in the variable named ‘val’. PHP variables start with ‘$’ character. Must not forget to put ‘;’ semicolon at end of every instruction. $fileContent is the variable, which appends ‘\n’ (next line) character at end of the text. Now file_put_contents () is a function used to push the contents in the file. Filename, data and flag (FILE_APPEND) are arguments of this function. This function returns a status flag i.e. True or False. IF flag is true, means Data is stored successfully. In case of False, there might be some error.

Now it is time to add these two files [datastrorage.txt and writefile.php] in File Manager of your Server.

Open-File Manager of your Website. You will see this link on your dashboard at the top. Click on Upload Files and it will redirect you to a new page where you will see all the files working in the backend of your website. Now click on Upload button, choose file “writefile.php” from the computer, and upload it. You need to upload the file in “public_html” folder. Now click on add New file and name this file as “datastorage.txt” and create. That is it.

?>

Step 4: Testing the Server

Now open another tab and type custom URL and replace “name” (written after ‘=’ character) with any other text (maybe your name) and press Enter. You will see message “SUCCESS. Data are written in the file." On the webpage. In case you do not get any message, make sure your PHP file does not have any error. Now open File URL in another tab and you will be able to see the contents of the file. You will be able to see your text, which you had written previously in the file. This is all.

Step 5: NODEMCU ESP8266 12e Board

Now it is time to program ESP such that it can send and receive messages from the server.

We will be using ESP8266HTTPClient library for our task. You can go through the documentation of this library. This library provides function to begin our HTTP connection with any website and send GET/POST requests. With this library, we will also use ESP8266WiFi library for connecting our Wi-Fi module with Internet. Setup function will be the trivial one containing the code to connect with Internet and display ‘Connected’. I had added one more thing to setup. It will send a message to server to save something on server file. One important thing, which I want to add, is that you should not add spaces in text while sending. Because spaces are replaced at server end with ‘%20’ and I had not added any such code to replace spaces with ‘%20’ in text before sending. You can add it and then your spaces, but for now, I had not used that, so do not do that, it will not work. After that, we will poll in Loop function by reading the received message in a continuous manner and will handle messages if necessary.

Because I was communicating with another ESP, I added a message validation method, which checks the received message, and notifies ESP whether the message needs to be replied or not. If not, it will continue to read messages and if yes, it will stop receiving messages and will send reply to server and again resumes the loop for receiving messages.

Methods:

1. Receive Message: will receive contents of file, extract the last line of the file, and return it.

2. Send Message: Will send message to server using custom URL and read the response. According to response, will send its own response whether message was sent successfully or not.

3. Message Validation: This method will read the received message and check whether the received message is needed to be replied or not. It returns its own response as 1/0.

4. Handle messages: This method send reply to server in case message is validated and needed to be replied. It will compare the message with pre-defined messages and reply them accordingly.

Now explaining the code to send and receive data from server using ESP8266

RECEIVE DATA

String receivelastmessage()

{

String lastmessage="";

if(WiFi.status()==WL_CONNECTED)

{

HTTPClient http;

String url="http://xyz.000webhostapp.com/datastorage.txt";

http.begin(url);

http.addHeader("Content-Type","text/plain");

int httpCode=http.GET();

String data=http.getString();

lastmessage=getlastline(data);

http.end();

}

else

{

lastmessage="";

}

return lastmessage;

}

Explanation:

‘http’ object is created of class ‘HTTPClient’. The connection I started with the URL. HTTP headers are added. Now simple GET request is sent to the server. This will return the HTTP code and at the end, collect the received message from http.getString () method of HTTPClient class. This will send you the contents of the File. Using getlastline () method to extract the last line of the data.

SEND DATA

int sendmessage(String d)

{

int sres;

int net;

if(WiFi.status()==WL_CONNECTED)

{

HTTPClient http;

String url="http://xyz.000webhostapp.com/writefile.php?data="+d;

http.begin(url);

http.addHeader("Content-Type","text/plain");

int httpCode=http.GET();

String payload=http.getString();

Serial.println("While sending I received this from server :"+payload);

if(payload=="SUCCESS. Data written in file.")

{

sres=1;

}

else

{

sres=0;

}

http.end();

net=1;

}

else

{

Serial.println("Internet Problem!");

net=0;

}

return (net&& sres);

}

Explanation: This code is similar to receive data code. In
this code, we added the custom URL to HTTP begin function and then read the response of this URL using GET function. We compared it with the text, which we had added in our PHP File ‘SUCCESS. Data written in the file.’ At last, the response is sent whether the message is sent successfully or not.

Other methods are self-explanatory and not have anything to discuss here. You can download the code from below, which contains all the methods.

Now, you can upload the code to your ESP8266 board and it will work fine. You can check Serial Monitor or open the file URL in the browser to check the status of file contents.

Share

    Recommendations

    • Make it Glow Contest 2018

      Make it Glow Contest 2018
    • Big and Small Contest

      Big and Small Contest
    • First Time Author

      First Time Author

    8 Discussions

    0
    None
    mhndr003

    Question 2 months ago on Step 5

    what if i want to erase that datastorage.txt file on my server using esp8266

    0
    None
    PandaB10

    Question 5 months ago

    I get this message during compiling the file is there any solution

    'getlastline' was not declared in this scope

    0
    None
    iamhollis84

    7 months ago

    Keep getting errors message on line 54. Error is Syntax error, unexpected T_VARIABLE

    Line 54 reads;
    \par $val = $_GET[“data”];
    What am I doing wrong?

    0
    None
    ShahL

    8 months ago

    I am getting this error. Kindly help me

    Arduino: 1.8.2 (Windows 8.1), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 4M (1M SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

    Build options changed, rebuilding all

    Archiving built core (caching) in: C:\Users\SMHAMZ~1\AppData\Local\Temp\arduino_cache_783740\core\core_esp8266_esp8266_nodemcuv2_CpuFrequency_80,FlashSize_4M1M,LwIPVariant_v2mss536,Debug_Disabled,DebugLevel_None____,FlashErase_none,UploadSpeed_115200_bcd5075b824f7e273757832e403668e5.a

    Sketch uses 268140 bytes (25%) of program storage space. Maximum is 1044464 bytes.

    Global variables use 33828 bytes (41%) of dynamic memory, leaving 48092 bytes for local variables. Maximum is 81920 bytes.

    warning: espcomm_sync failed

    error: espcomm_open failed

    error: espcomm_upload_mem failed

    error: espcomm_upload_mem failed

    This report would have more information with

    "Show verbose output during compilation"

    option enabled in File -> Preferences.

    4 replies
    0
    None
    LalitA9ShahL

    Reply 8 months ago

    @ShahL If you are using ESP8266 breakout , you have to ground pin 1 while loading code. I hope you remembered that. If you are using NodeMcu and still getting this error, reset the module or plug out and plug in again. This error states that the module is not able to connect with port. So, try it again after reseting the connection. This will work. Make sure all the other parameretes are set correctly.

    0
    None
    ShahLLalitA9

    Reply 8 months ago

    Arduino pin Rx/Tx will be used or not?

    0
    None
    ShahLShahL

    Reply 8 months ago

    I am following this connection diagram

    Connection.png
    0
    None
    LalitA9ShahL

    Reply 8 months ago

    There are two GPIOs in ESP8266 and one is to be grounded while programming the breakout. Rest of the connections are trivial. Yes Rx/Tx will be connected with those of Microcontroller or Microprocessor.