Correct Connection Needed to Upload From Client to Server
Larn how to establish a Wi-Fi communication (HTTP) between 2 ESP8266 NodeMCU boards to exchange data without the demand to connect to the internet (you don't need a router).
You're going to set one ESP8266 every bit an Access Point (Server) and another ESP8266 as a Station (Client). So, the server and the client will commutation data (sensor readings) via HTTP requests. We'll programme the ESP8266 boards using Arduino IDE.
In this example, we'll send BME280 sensor readings from ane board to the other. The receiver will brandish the readings on an OLED display.
If yous have an ESP32 lath, you can read this dedicated guide: ESP32 Customer-Server Wi-Fi Communication.
Sentry the Video Demonstration
To run into how the project works, you can watch the following video demonstration:
Project Overview
To better empathise how everything works, take a look at the post-obit diagram.
- The ESP8266 server creates its own wireless network (ESP8266 Soft-Access Betoken). Then, other Wi-Fi devices tin can connect to that network (SSID: ESP8266-Admission-Point, Countersign: 123456789).
- The ESP8266 client is set as a station. Then, information technology tin can connect to the ESP8266 server wireless network.
- The client tin make HTTP GET requests to the server to request sensor information or whatsoever other information. It just needs to use the IP address of the server to brand a request on a certain route: /temperature, /humidity or /pressure.
- The server listens for incoming requests and sends an appropriate response with the readings.
- The client receives the readings and displays them on the OLED brandish.
Equally an case, the ESP8266 client requests temperature, humidity and force per unit area to the server by making requests on the server IP address followed by /temperature, /humidity and /pressure, respectively (HTTP Get).
The ESP8266 server is listening on those routes and when a request is made, it sends the respective sensor readings via HTTP response.
Parts Required
For this tutorial, you lot need the following parts:
- 2x ESP8266 Development boards – read Best ESP8266 Boards Comparing
- BME280 sensor
- I2C SSD1306 OLED display
- Jumper Wires
- Breaboard
You tin employ the preceding links or become direct to MakerAdvisor.com/tools to detect all the parts for your projects at the best cost!
Installing Libraries
For this tutorial you need to install the following libraries:
Asynchronous Web Server Libraries
We'll use the post-obit libraries to handle HTTP request:
- ESPAsyncWebServer library (download ESPAsyncWebServer library)
- ESPAsync TCP library (download ESPAsyncTCP library)
These libraries are not available to install through the Library Managing director. So, yous demand to unzip the libraries and move them to the Arduino IDE installation libraries folder.
Alternatively, y'all can go toSketch>Include Library >Add .Nothing library… and select the libraries you've simply downloaded.
You may besides like: DHT11/DHT22 Asynchronous Web Server with the ESP8266
BME280 Libraries
The post-obit libraries can be installed through the Arduino Library Manager. Go toSketch>Include Library>Manage Libraries and search for the library proper name.
- Adafruit_BME280 library
- Adafruit unified sensor library
You may also like: Guide for BME280 with ESP8266
I2C SSD1306 OLED Libraries
To interface with the OLED display you need the following libraries. These can exist installed through the Arduino Library Manager. Go to Sketch > Include Library> Manage Libraries and search for the library proper name.
- Adafruit SSD1306
- Adafruit GFX Library
Yous may also like: Complete Guide for SSD1306 OLED Display with ESP8266
#1 ESP8266 Server (Access Point)
The ESP8266 server is an Access Indicate (AP), that listens for requests on the /temperature, /humidity and /pressure level URLs. When information technology gets requests on those URLs, information technology sends the latest BME280 sensor readings.
For testing, we're using a BME280 sensor, but you can utilize any other sensor by modifying a few lines of lawmaking (for instance: DHT11/DHT22 or DS18B20).
Schematic Diagram
Wire the ESP8266 to the BME280 sensor as shown in the post-obit schematic diagram.
BME280 | ESP8266 |
VIN/VCC | 3.3V |
GND | GND |
SCL | GPIO 5 (D1) |
SDA | GPIO iv (D2) |
Arduino Sketch for #1 ESP8266 Server
Upload the following code to your board.
/* Rui Santos Complete projection details at https://RandomNerdTutorials.com/esp8266-nodemcu-customer-server-wi-fi/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files. The above copyright detect and this permission notice shall be included in all copies or substantial portions of the Software. */ // Import required libraries #include <ESP8266WiFi.h> #include "ESPAsyncWebServer.h" #include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_BME280.h> // Set up your access point network credentials const char* ssid = "ESP8266-Access-Bespeak"; const char* password = "123456789"; /*#include <SPI.h> #define BME_SCK 18 #define BME_MISO 19 #ascertain BME_MOSI 23 #define BME_CS v*/ Adafruit_BME280 bme; // I2C //Adafruit_BME280 bme(BME_CS); // hardware SPI //Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI // Create AsyncWebServer object on port fourscore AsyncWebServer server(80); Cord readTemp() { render String(bme.readTemperature()); //render String(1.8 * bme.readTemperature() + 32); } Cord readHumi() { return String(bme.readHumidity()); } String readPres() { return Cord(bme.readPressure() / 100.0F); } void setup(){ // Serial port for debugging purposes Serial.begin(115200); Series.println(); // Setting the ESP as an admission bespeak Serial.impress("Setting AP (Access Point)…"); // Remove the countersign parameter, if y'all want the AP (Admission Signal) to exist open WiFi.softAP(ssid, password); IPAddress IP = WiFi.softAPIP(); Series.print("AP IP address: "); Serial.println(IP); server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *asking){ request->send_P(200, "text/evidently", readTemp().c_str()); }); server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/manifestly", readHumi().c_str()); }); server.on("/pressure level", HTTP_GET, [](AsyncWebServerRequest *asking){ request->send_P(200, "text/obviously", readPres().c_str()); }); bool status; // default settings // (you lot tin can as well pass in a Wire library object like &Wire2) status = bme.begin(0x76); if (!status) { Serial.println("Could not observe a valid BME280 sensor, check wiring!"); while (1); } // Start server server.begin(); } void loop(){ }
View raw lawmaking
How the code works
Beginning past including the necessary libraries. Include the ESP8266WiFi.h library and the ESPAsyncWebServer.h library to handle incoming HTTP requests.
#include <ESP8266WiFi.h> #include "ESPAsyncWebServer.h"
Include the post-obit libraries to interface with the BME280 sensor.
#include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_BME280.h>
In the following variables, define your access signal network credentials:
const char* ssid = "ESP8266-Access-Point"; const char* password = "123456789";
We're setting the SSID to ESP8266-Admission-Betoken, but you tin can requite it any other name. You tin can also change the password. By default, its gear up to 123456789.
Create an instance for the BME280 sensor called bme.
Adafruit_BME280 bme;
Create an asynchronous spider web server on port 80.
AsyncWebServer server(80);
Then, create three functions that render the temperature, humidity, and pressure as String variables.
Cord readTemp() { render Cord(bme.readTemperature()); //return String(one.8 * bme.readTemperature() + 32); } String readHumi() { render String(bme.readHumidity()); } String readPres() { return Cord(bme.readPressure() / 100.0F); }
In the setup(), initialize the Serial Monitor for demonstration purposes.
Serial.begin(115200);
Set your ESP8266 as an access indicate with the SSID name and password defined earlier.
WiFi.softAP(ssid, password);
So, handle the routes where the ESP8266 will be listening for incoming requests.
For example, when the ESP8266 server receives a request on the /temperature URL, information technology sends the temperature returned by the readTemp() function as a char (that'southward why we use the c_str() method.
server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/plain", readTemp().c_str()); });
The aforementioned happens when the ESP receives a request on the /humidity and /pressure URLs.
server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/plain", readHumi().c_str()); }); server.on("/force per unit area", HTTP_GET, [](AsyncWebServerRequest *request){ asking->send_P(200, "text/plain", readPres().c_str()); });
The following lines initialize the BME280 sensor.
bool status; // default settings // (you can also pass in a Wire library object like &Wire2) status = bme.begin(0x76); if (!status) { Serial.println("Could not find a valid BME280 sensor, check wiring!"); while (1); }
Finally, outset the server.
server.begin();
Because this is an asynchronous web server, in that location'south nothing in the loop().
void loop(){ }
Testing the ESP8266 Server
Upload the lawmaking to your lath and open the Serial Monitor. You should get something equally follows:
This ways that the access betoken was gear up successfully.
Now, to make certain it is listening for temperature, humidity and pressure level requests, you demand to connect to its network.
In your smartphone, go to the Wi-Fi settings and connect to the ESP8266-Access-Point. The countersign is 123456789.
While connected to the access betoken, open up your browser and type 192.168.4.1/temperature
You should go the temperature value in your browser:
Endeavor this URL path for the humidity 192.168.iv.1/humidity:
Finally, go to 192.168.4.ane/pressure URL:
If you're getting valid readings, it ways that everything is working properly. Now, you need to gear up the other ESP8266 board (client) to make those requests for y'all and display them on the OLED display.
#2 ESP8266 Client (Station)
The ESP8266 Client is a Wi-Fi station that connects to the ESP8266 Server. The client requests the temperature, humidity and pressure from the server by making HTTP GET requests on the /temperature, /humidity, and /pressure level URL routes. And so, it displays the readings on the OLED display.
Schematic Diagram
Connect an OLED display to your ESP8266 board as shown in the following schematic diagram.
Pin | ESP8266 |
Vin | iii.3V |
GND | GND |
SCL | GPIO five (D1) |
SDA | GPIO 4 (D2) |
Arduino Sketch for #two ESP8266 Client
Upload the following code to the other ESP8266 (the client):
/* Rui Santos Complete project details at https://RandomNerdTutorials.com/esp8266-client-server-wi-fi/ Permission is hereby granted, costless of charge, to whatever person obtaining a copy of this software and associated documentation files. The higher up copyright notice and this permission notice shall exist included in all copies or substantial portions of the Software. */ #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <WiFiClient.h> #include <ESP8266WiFiMulti.h> ESP8266WiFiMulti WiFiMulti; const char* ssid = "ESP8266-Admission-Signal"; const char* password = "123456789"; //Your IP address or domain name with URL path const char* serverNameTemp = "http://192.168.4.one/temperature"; const char* serverNameHumi = "http://192.168.4.i/humidity"; const char* serverNamePres = "http://192.168.iv.1/pressure"; #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #ascertain SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 64 // OLED brandish height, in pixels // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) #define OLED_RESET -ane // Reset pin # (or -ane if sharing Arduino reset pivot) Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); String temperature; String humidity; String pressure; unsigned long previousMillis = 0; const long interval = 5000; void setup() { Serial.begin(115200); Serial.println(); // Accost 0x3C for 128x64, you might need to modify this value (utilise an I2C scanner) if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { Series.println(F("SSD1306 allocation failed")); for(;;); // Don't go along, loop forever } display.clearDisplay(); brandish.setTextColor(WHITE); Series.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { filibuster(500); Serial.print("."); } Serial.println(""); Serial.println("Connected to WiFi"); } void loop() { unsigned long currentMillis = millis(); if(currentMillis - previousMillis >= interval) { // Bank check WiFi connexion status if ((WiFiMulti.run() == WL_CONNECTED)) { temperature = httpGETRequest(serverNameTemp); humidity = httpGETRequest(serverNameHumi); pressure = httpGETRequest(serverNamePres); Series.println("Temperature: " + temperature + " *C - Humidity: " + humidity + " % - Pressure: " + pressure + " hPa"); brandish.clearDisplay(); // display temperature display.setTextSize(2); display.setCursor(0,0); brandish.print("T: "); display.print(temperature); display.impress(" "); display.setTextSize(ane); brandish.cp437(true); display.write(248); display.setTextSize(2); display.impress("C"); // display humidity brandish.setTextSize(2); display.setCursor(0, 25); display.impress("H: "); display.print(humidity); display.impress(" %"); // display pressure display.setTextSize(two); brandish.setCursor(0, 50); display.print("P:"); display.print(pressure); display.setTextSize(ane); display.setCursor(110, 56); display.print("hPa"); brandish.display(); // salve the final HTTP Go Request previousMillis = currentMillis; } else { Serial.println("WiFi Asunder"); } } } String httpGETRequest(const char* serverName) { WiFiClient client; HTTPClient http; // Your IP address with path or Domain proper noun with URL path http.begin(client, serverName); // Send HTTP POST asking int httpResponseCode = http.Get(); String payload = "--"; if (httpResponseCode>0) { Series.print("HTTP Response lawmaking: "); Serial.println(httpResponseCode); payload = http.getString(); } else { Serial.impress("Error code: "); Serial.println(httpResponseCode); } // Free resources http.end(); return payload; }
View raw code
How the code works
Include the necessary libraries for the Wi-Fi connection and for making HTTP requests:
#include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <WiFiClient.h> #include <ESP8266WiFiMulti.h>
You need to create a WiFiMulti example.
ESP8266WiFiMulti WiFiMulti;
Insert the ESP8266 server network credentials. If you lot've inverse the default network credentials in the ESP8266 server, you should change them hither to lucifer.
const char* ssid = "ESP8266-Access-Indicate"; const char* password = "123456789";
Then, save the URLs where the client will be making HTTP requests. The ESP8266 server has the 192.168.4.1 IP address, and we'll be making requests on the /temperature, /humidity and /pressure URLs.
const char* serverNameTemp = "http://192.168.4.1/temperature"; const char* serverNameHumi = "http://192.168.4.ane/humidity"; const char* serverNamePres = "http://192.168.4.one/pressure";
Include the libraries to interface with the OLED display:
#include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h>
Set up the OLED brandish size:
#define SCREEN_WIDTH 128 // OLED display width, in pixels #ascertain SCREEN_HEIGHT 64 // OLED brandish height, in pixels
Create a brandish object with the size you've defined earlier and with I2C communication protocol.
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
Initialize cord variables that will hold the temperature, humidity and pressure readings retrieved past the server.
String temperature; String humidity; String pressure level;
Set the time interval betwixt each request. Past default, it's prepare to five seconds, but y'all tin change it to whatever other interval.
const long interval = 5000;
In the setup(), initialize the OLED display:
// Address 0x3C for 128x64, yous might demand to change this value (use an I2C scanner) if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { Serial.println(F("SSD1306 allotment failed")); for(;;); // Don't go along, loop forever } display.clearDisplay(); display.setTextColor(WHITE);
Note: if your OLED brandish is not working, bank check its I2C accost using an I2C scanner sketch and change the code accordingly.
Connect the ESP8266 client to the ESP8266 server network.
while (WiFi.status() != WL_CONNECTED) { delay(500); Series.print("."); } Serial.println(""); Series.println("Continued to WiFi");
In the loop() is where we make the HTTP Become requests. We've created a function called httpGETRequest() that accepts every bit argument the URL path where we desire to make the request and returns the response as a Cord.
You tin utilize the next function in your projects to simplify your code:
String httpGETRequest(const char* serverName) { WiFiClient client; HTTPClient http; // Your IP address with path or Domain name with URL path http.begin(client, serverName); // Send HTTP POST asking int httpResponseCode = http.GET(); String payload = "--"; if (httpResponseCode>0) { Serial.print("HTTP Response code: "); Series.println(httpResponseCode); payload = http.getString(); } else { Serial.print("Error code: "); Serial.println(httpResponseCode); } // Complimentary resources http.end(); render payload; }
We use that function to become the temperature, humidity and pressure level readings from the server.
temperature = httpGETRequest(serverNameTemp); humidity = httpGETRequest(serverNameHumi); pressure level = httpGETRequest(serverNamePres);
Print those readings in the Serial Monitor for debugging.
Serial.println("Temperature: " + temperature + " *C - Humidity: " + humidity + " % - Pressure: " + pressure + " hPa");
Then, brandish the temperature in the OLED display:
brandish.setTextSize(2); brandish.setTextColor(WHITE); brandish.setCursor(0,0); display.print("T: "); display.print(temperature); brandish.print(" "); brandish.setTextSize(ane); display.cp437(true); display.write(248); display.setTextSize(2); display.print("C");
The humidity:
display.setTextSize(2); display.setCursor(0, 25); display.impress("H: "); display.print(humidity); display.print(" %");
Finally, the pressure level reading:
brandish.setTextSize(2); display.setCursor(0, 50); brandish.print("P:"); display.print(pressure); display.setTextSize(1); display.setCursor(110, 56); display.print("hPa"); display.display();
We use timers instead of delays to make a request every x number of seconds. That's why we take the previousMillis, currentMillis variables and use the millis() office. We have an article that shows the divergence between timers and delays that you might detect useful (or read ESP8266 Timers).
Upload the sketch to #two ESP8266 (client) to test if everything is working properly.
Testing the ESP8266 Client
Having both boards fairly close and powered, you'll run across that ESP #2 is receiving new temperature, humidity and pressure readings every 5 seconds from ESP #1.
This is what yous should see on the ESP8266 Client Serial Monitor.
The sensor readings are too displayed in the OLED.
That's it! Your ii ESP8266 boards are talking with each other.
Wrapping Up
In this tutorial we've shown y'all how to send information from ane ESP8266 board to the other using HTTP requests. This projection can be very useful if you need to setup a wireless advice between 2 boards or more than and y'all don't have a router nearby.
For sit-in purposes, nosotros've shown how to send BME280 sensor readings, but y'all tin can apply whatsoever other sensor or ship whatever other information. Other recommended sensors:
- ESP8266 DHT11 or DHT22 (Guide)
- ESP8266 DS18B20 (Guide)
- DHT11 vs DHT22 vs DS18B20 vs BME280
We have a similar tutorial for the ESP32 that you might discover useful:
- ESP32 Customer-Server Wi-Fi Advice Betwixt Two Boards
Nosotros hope you liked this tutorial. We're preparing more tutorials like these. So, stay tuned and subscribe to our blog!
Thanks for reading.
Source: https://randomnerdtutorials.com/esp8266-nodemcu-client-server-wi-fi/
0 Response to "Correct Connection Needed to Upload From Client to Server"
Post a Comment