Introduction: 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.
Step 1: Requirements
- ESP8266 Development Board. [NodeMCU 12e Board] (If you are using ESP 01 board, then also it will work. Just use FTDI to upload code. )
- Wi-Fi Connection
- Data Cable
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.
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.
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.
$val = $_GET["data"];
if($fileStatus != false)
echo "SUCCESS. Data written in file.";
echo "FAIL. Could not connect to file.";
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.
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
‘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.
int sendmessage(String d)
Serial.println("While sending I received this from server :"+payload);
if(payload=="SUCCESS. Data written in file.")
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.
We have a be nice policy.
Please be positive and constructive.