ESP8266 Sending Data Over Wi-Fi to another ESP8266

Two ESP8266 boards with OLEDs

A simple guide to sending data from one ESP8266 to another over Wi-Fi using an ad-hoc, device to device network, without using a wifi router.

The ESP8266WebServer library allows you run an ESP8266 as a basic webserver and access point. This can process data received from a remote sensor over Wi-Fi without connecting the devices to a network or router.

For this tutorial I’m using two NodeMCU boards from eBay but you can do this with any ESP8266 based board. To simulate the output from a sensor I’m using a trim pot potentiometer like these from eBay. I’m also using two small OLED screens from AliExpress so you can see the data easily but you don’t need these if you want to see the results in the serial monitor.

As you can see in the video below, when the potentiometer pot is adjusted the value shown on the transmitting module OLED changes to reflect the change in voltage to pin A0. On the receiver, the value on the OLED is updated as the data is received from the transmitter.


If you don’t have the Arduino IDE set up for the ESP8266 range yet you can find a tutorial here – https://robotzero.one/heltec-wifi-kit-8/ under Setting Up the Arduino IDE for the ESP8266 Range.

I’m using these settings in the IDE (Tools menu) ..

NodeMCU IDE Settings

The wiring is identical for both the transmitter and receiver except the transmitting device has the potentiometer connected to the power and analogRead(A0) pins. You might need to connect the A0 pin via a resistor on some boards as they only read up to 1v on this pin.

ESP8266 to ESP8266 Wifi Wiring

ESP8266 to ESP8266 Wi-Fi Wiring Diagram

ESP8266 to ESP8266 Wifi Breadboard

ESP8266 to ESP8266 Wi-Fi Breadboard Layout

If it’s not installed already you will need to install the U8g2 display library (for the OLED) It can be installed using the Arduino IDE library manager – open Sketch > Include Library > Manage Libraries and search for and then install U8g2.

Here’s the sketch for the transmitter. There’s a more verbose version if you want to see the output in the serial monitor or need to debug here.

#include <ESP8266WiFi.h>
#include <U8g2lib.h>

//U8g2 Constructor List - https://github.com/olikraus/u8g2/wiki/u8g2setupcpp#introduction
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4);

const char *ssid = "poopssid";
const char *password = "pingu4prez";

const int analogInPin = 0;  // Analog input pin that the potentiometer is attached to
int sensorValue = 0;        // value read from the potentiometer
int outputValue = 0;        // value sent to server

void setup() {
  Serial.begin(115200);
  delay(10);

  // Explicitly set the ESP8266 to be a WiFi-client
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  u8g2.begin();
  u8g2.setFont(u8g2_font_logisoso62_tn);
  u8g2.setFontMode(0);    // enable transparent mode, which is faster
}

void loop() {
  // read the analog in value:
  sensorValue = analogRead(A0);
  // map to range. The pot goes from about 3 to 1023. This makes the sent value be between 0 and 999 to fit on the OLED
  outputValue = map(sensorValue, 3, 1023, 0, 999);

  char intToPrint[5];
  itoa(outputValue, intToPrint, 10); //integer to string conversion for OLED library
  u8g2.firstPage();
  u8g2.drawUTF8(0, 64, intToPrint);
  u8g2.nextPage();

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const char * host = "192.168.4.1";
  const int httpPort = 80;

  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request. Something like /data/?sensor_reading=123
  String url = "/data/";
  url += "?sensor_reading=";
  url += intToPrint;

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\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;
    }
  }

  delay(500);
}

On the server (receiver) the sketch looks like this. Again, if you want a version with serial outputs to see more details you can download that here.

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

//U8g2 Constructor List - https://github.com/olikraus/u8g2/wiki/u8g2setupcpp#introduction
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4);

const char *ssid = "poopssid";
const char *password = "pingu4prez";

ESP8266WebServer server(80);

void handleSentVar() {
  if (server.hasArg("sensor_reading")) { // this is the variable sent from the client
    int readingInt = server.arg("sensor_reading").toInt();
    char readingToPrint[5];
    itoa(readingInt, readingToPrint, 10); //integer to string conversion for OLED library
    u8g2.firstPage();
    u8g2.drawUTF8(0, 64, readingToPrint);
    u8g2.nextPage();
    server.send(200, "text/html", "Data received");
  }
}

void setup() {
  delay(1000);

  u8g2.begin();
  u8g2.setFont(u8g2_font_logisoso62_tn);
  u8g2.setFontMode(0);    // enable transparent mode, which is faster

  WiFi.softAP(ssid, password);
  IPAddress myIP = WiFi.softAPIP();

  server.on("/data/", HTTP_GET, handleSentVar); // when the server receives a request with /data/ in the string then run the handleSentVar function
  server.begin();
}

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

Hopefully this tutorial helps you start off in the right direction with using Wi-Fi on these devices. I’ve seen other tutorials that made things a lot more complicated than they need to be.

126 Replies to “ESP8266 Sending Data Over Wi-Fi to another ESP8266”

  1. dave says:

    Thanks for posting this.
    I am trying to have ESP8266 units and send temperatures. one in the basement, one in the attic all to the one near the WiFi router. 2 sending, 1 receiving

    1. WordBot says:

      You’ll need to change the query string sent so the receiving ESP will know which one sent the data. Something like:
      Basement ESP: ?sensor_reading_basement=
      Attic ESP: ?sensor_reading_attic=

      On the receiver you’ll need a smaller font to fit everything on the screen and change the handleSentVar to listen to the two new variables above. This system doesn’t use your WiFi, it runs on its own network.

  2. Mauro says:

    Hi, is it possible to send sensor value from an esp8266 to an esp32 with the same technic ?

    best regards

    1. WordBot says:

      Yep. The data is sent as a GET request like this: /data/?sensor_reading=123 so any web server can parse the information and use it. I’m not sure exactly which libraries you need but the ESP32 has equivalents to the ESP8266WiFi and ESP8266WebServer libraries.

  3. Alexander says:

    Hello! Could you help me a little bit? I just want to send an int value from one esp board to other.
    I’ve connetcted a pontentiometer on the first esp(Wemos D1 mini), and gets a value using map() function. I want to send it to the second board for changing blink interval of LED.
    I tried to change your sketch, but got no luck =(.

    Thank you in advance!

    1. WordBot says:

      Hi there.
      First check the simple blink sketch works:

      void setup() {
      pinMode(BUILTIN_LED, OUTPUT); // initialize onboard LED as output
      }
      void loop() {
      digitalWrite(BUILTIN_LED, HIGH); // turn on LED with voltage HIGH
      delay(1000); // wait one second
      digitalWrite(BUILTIN_LED, LOW); // turn off LED with voltage LOW
      delay(1000); // wait one second
      }

      If that’s OK then something like the following might work. I don’t have the project set up at the moment.

      #include < ESP8266WiFi.h > //(remove spaces – wordpress comment workaround)
      #include < ESP8266WebServer.h >

      const char *ssid = “poopssid”;
      const char *password = “pingu4prez”;

      int varDelay = 1000;
      int ledState = LOW;
      unsigned long previousMillis = 0;

      ESP8266WebServer server(80);

      void handleSentVar() {
      if (server.hasArg(“sensor_reading”)) {
      varDelay = server.arg(“sensor_reading”).toInt();
      server.send(200, “text/html”, “Data received”);
      }
      }

      void setup() {
      delay(1000);
      pinMode(BUILTIN_LED, OUTPUT);
      WiFi.softAP(ssid, password);
      IPAddress myIP = WiFi.softAPIP();
      server.on(“/data/”, HTTP_GET, handleSentVar);
      server.begin();
      }

      void loop() {
      server.handleClient();

      unsigned long currentMillis = millis();
      // if enough millis have elapsed
      if (currentMillis – previousMillis >= varDelay) {
      previousMillis = currentMillis;

      // toggle the LED
      ledState = !ledState;
      digitalWrite(BUILTIN_LED, ledState);
      }
      }

      1. Alexander says:

        Yeah! =) It works. Thank you so much!

  4. kave says:

    hi,
    It`s very useful project
    I need help for my project,
    I want to send data via serial form ESP-12 to ESP-01 , That way one RC522 RFID connect to ESP-12 and read tag card and it should be send tag to the ESP-01 with high speed like your project.
    Thanks so much if you can help me 🙂

    1. WordBot says:

      Hi,
      Do you have the code for the reading the tag? In that code you just need to have it send the data in the same way the transmitter code above sends data to the other ESP.

  5. Ron says:

    Hi,

    Thanks for the example. It saves me a lot of work/time finding out the wheel as I’m a basic electronics engineer and not a TCP/IP/HTML specialist. I’m lazy and have replaced the potmeter for a random generator and the output is written to a serial monitor. All seems to work fine however in my example I have contineously timeouts on client.connect() and client.available(). Any suggestions?

    1. WordBot says:

      Hi,
      At a guess I would say that there are too many connection attempts for the webserver in the ESP8266. Maybe try a delay() command in the loop to slow down the connection attempts? Or if you are feeling brave you could try another webserver: https://github.com/me-no-dev/ESPAsyncWebServer

  6. Tudor says:

    HI,
    I try to do a project in which I have 2 transmitters and one receiver. Each transmitter has a switch and if I press the switch (from a transmitter or the other transmitter) the LED on the receiver should go on. Could you please help me? Thank you.

    1. WordBot says:

      It shouldn’t be too hard. Both transmitters would have the same code that detects the button press and sends this in the URL “?sensor_reading=on”; to the listening receiver. On the receiver you would set the LED high in the handleSentVar() function.

      1. Tudor says:

        Thank you. I am a beginner. Could you please help me with the code? I do not understand exactly which lines should I keep and which not.

        1. WordBot says:

          If you are new to this you should break it down into small parts so you can understand what is happening so you can work with it later. The first thing you need is add a switch to the transmitter. The simplest way (not necessarily the best) is to pull the pin connected to the onboard LED to ground with a your switch (or just connect D4 to GND with a piece of wire).

          Then use the code below to see the change in the serial monitor:

          const int button = 2; // D4/GPIO2 is connected to the internal LED (which is lit when the pin is LOW).
          int pinState= 0;

          void setup() {
          Serial.begin(9600);
          pinMode(button, INPUT);
          }

          void loop() {
          pinState = digitalRead(button);
          if (pinState == LOW) {
          Serial.println(“LED Turned ON”);
          delay(1000);
          }
          else {
          Serial.println(“LED Turned OFF”);
          delay(1000);
          }
          }

        2. WordBot says:

          Then you need to edit the code in the tutorialfor the transmitter so it sends the button state rather than the sensor reading something like this:

          String url = “/data/”;
          url += “?button_state=”;
          url += pinState;

  7. Mitchell says:

    Hi, cool project with great info! I want to output the potentiometer reading via pwm instead of seeing the value on screen. Could you guide me on the coding portion?

    1. WordBot says:

      Do you have the code for the PWM part on the receiver? It shouldn’t be too hard to change the code in the tutorial to update the PWM code rather than the screen.

      1. Mitchell says:

        No I have very basic understanding of programming. I usually troll tutorials such as this looking for code similar to what I need and then try to stitch the bits together 🙁

        1. Mitchell says:

          I have your original code with the oled portions omitted on both mcu

          1. WordBot says:

            I don’t really have time to look at this but if you ask on the forum here – https://www.esp8266.com/ someone will probably help. Tell them how far you’ve got and what you want to achieve.

  8. hassan11 says:

    can you help me i need code to send data between two esp32 , data from sensors in one esp32 to onther

    1. WordBot says:

      The code should be mostly the same. You’ll need to use different libraries for the wifi and wifi server and possibly change the pins for the oleds if you are using them.

  9. Arduino93 says:

    i used this code to transmit the data from esp32 and they connected together but sensorValue still constant at “4095” in both esp32 , what should i do ?

    1. WordBot says:

      Do you have code similar to this on the transmitter so you can see the output from the sensor:

      // read the analog in value:
      sensorValue = analogRead(A0);

      // map to range. The pot goes from about 3 to 1023. This makes the sent value be between 0 and 999 to fit on the OLED
      outputValue = map(sensorValue, 3, 1023, 0, 999);

      // print the results to the Serial Monitor:
      Serial.print(“sensor = “);
      Serial.print(sensorValue);
      Serial.print(“\t output = “);
      Serial.println(outputValue);

  10. Safei says:

    this code is work correctly with me ..
    but i wanna send 5 values from esp instead of 1 value and save values in the other esp , what edits can i do ?
    Thank you in advance

    1. WordBot says:

      So you want to take 5 sensor values and send them together? You can just make 5 variables to hold each one and send it like this.
      url += “?sensor_reading1=”;
      url += intToPrint1;
      url += “?sensor_reading2=”;
      url += intToPrint2;
      etc…

      Or maybe a tidier way is to put them all into one string, send that and process it on the other side. One way of sending strings: https://randomnerdtutorials.com/decoding-and-encoding-json-with-arduino-or-esp8266/

      1. Safei says:

        I already do this but it didn’t receive values in the other esp and it display “Client Timeout !” in serial monitor of transmitter esp …

        Thank u very much for your support .

        1. WordBot says:

          Client timeout is not connecting to your WiFi. Try some of the ESP8266 Wifi examples to get this working. It’s always best to start simple and then add things bit by bit to check as you go. If you are new to this.. it’s much better to do that than try and edit a more complicated script to fit your case.

  11. Dieffy says:

    In your example the oled on the receiver is updating very quickly. I implemented the example code on two of my nodeMCU’s and I get a much slower response time. Did you use a different code for the video? Thanks for the tutorial by the way.

    1. WordBot says:

      It’s the same script. In the tutorial there’s a version with more output on the serial port which might help diagnose. Someone in the comments said theirs worked better with this line:
      WiFi.mode(WIFI_AP);
      added above this line:
      WiFi.softAP(ssid, password);
      in the receiver code but this isn’t in the examples code I developed this from.

  12. drdra says:

    Hey WordBot, thanks for your patience, can you tell me how can I send to multiple receivers?

    1. WordBot says:

      Looking quickly at this. If you take the part // We now create a URI for the request. Something like /data/?sensor_reading=123 and turn it into a function. Then take this part // Use WiFiClient class to create TCP connections and do something like

      const char * host = “192.168.4.1”;
      const int httpPort = 80;
      if (client.connect(host, httpPort)) {
      // new function here
      }

      Once you have that working the same as the existing example you can then make it a loop that loops through the IP addresses you have for the clients.

  13. Jeevan says:

    Hi

    the project you have explained in a crispy and simple way thanks for the new thing which I learned from you.
    But when I am trying to compile your code I am getting an error saying

    WARNING: Spurious .github folder in ‘Adafruit Fingerprint Sensor Library’ library
    WARNING: Spurious .github folder in ‘Adafruit GPS Library’ library
    WARNING: Spurious .github folder in ‘RTClib’ library
    In file included from C:\Users\KERNEL\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwip/opt.h:51:0,

    from C:\Users\KERNEL\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwip/init.h:40,

    from C:\Users\KERNEL\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/IPAddress.h:27,

    from C:\Users\KERNEL\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi\src/ESP8266WiFi.h:31,

    from C:\Users\KERNEL\Documents\Arduino\NodeMCU_Transmitter\NodeMCU_Transmitter.ino:1:

    C:\Users\KERNEL\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwipopts.h:1301:2: error: #error TCP_MSS must be defined

    #error TCP_MSS must be defined

    I am not getting this error what actually its saying. Please help me ,thanks in advance

    1. WordBot says:

      Your installation for the ESP8266 package is bad. How did you set up the esp8266 library? There’s a tutorial on this page for that: https://robotzero.one/heltec-wifi-kit-8/

  14. Deepanshu Kumar says:

    Hey,
    I’m trying to transfer values from one arduino UNO to other arduinoUNO using ESP8266. I ‘m in the process of doing the same but I’m not able to transfer data neither I’m able to connect at the same HTTP address and port. For keeping program simple, initially, I’m trying to transfer a specific value of ‘temp’ to other ESP8266.

    1. WordBot says:

      Hi, Have you tried with the client IP as:

      const char * host = “192.168.4.1”;

      1. Deepanshu Kumar says:

        Yes, I tried. The default IP which is being allocated to the client is “192.168.4.2”.

        1. WordBot says:

          Did you see the server example with more verbose output – https://robotzero.one/wp-content/uploads/2018/04/ESP8266-wifi-receiver.ino maybe this will help. Maybe paste your current client and server code at https://pastebin.com/ and I’ll try to take a look.

          1. Deepanshu Kumar says:

            Hey, thanks. I’m getting something better than earlier now. The client is printing the values. Server program still needs some editing.

          2. Deepanshu Kumar says:

            I want to transfer GPS values from system 1 to system 2 using Wi-Fi module ESP8266 along with Arduino UNO. I’ve written the main codes for server and client end. I’m not able to print anything on LCD if I’m using ESP8266 and selected ‘generic ESP8266’ boards. What could be the issue?

            1. WordBot says:

              Which LCD are you using? Try some of the examples for that LCD first.

  15. Sarah says:

    Hi, I’m trying to set up 3 nodemcu esp8266 to be both client and server. Basically what it would do is, if ESP01 sense a motion it will turn on the led then notify the other two esp that there is someone so that they could also turn on their led. At the same time, the ESP01 will also be ready for any incoming notification that the other two esp might send. Do you have any idea to make this work?

    1. WordBot says:

      I’m pretty sure you can have client and server running on the same ESP8266. Think of them as a triangle. Each one sends to the other two it’s connected to via their IP addresses. You could include in the message a code to say which device was triggered and the receiving device could flash the LED in a pattern to show the device number.

  16. Sarah says:

    Thank you for replying.
    Do you have any example that I can refer to?

    1. WordBot says:

      I don’t have an example but you can look in the ESP8266 example in the IDE and hack something together. Another (possibly better) way to do this is to use a mesh network: https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFiMesh

  17. Syira says:

    Hi,
    how to make one esp8266 ask another esp8266 to light up it’s led at a certain brightness.

    1. WordBot says:

      Hi, In the Arduino IDE: File>Examples>Basics>Fade has a very basic setup for controlling the brightness of an LED. You can use similar code on the receiver from the tutorial above to control brightness. Search ESP8266 PWM for other tutorials.

  18. Kyle says:

    Hello.
    How can i turn this sketch into a simple dimmer that would send from the nodemcu a pwm signal from a touchscreen dimmer slider to output from the receiver the same input that came from the transmitter?
    Also, can this be done with 2 nodemcu receivers to output the same dimmer function simultaneously?
    thank you
    Kyle

    1. WordBot says:

      Hi, you need to read up about PWM input on the ESP32. You might be able to use the same pin and read the voltage but PWM can be quite complicated. Do you have to use the touchscreen slider?

  19. Dan Murphy says:

    Hi!

    I loved your project! Im trying to do same, but instead read a potentiometer on analog input, Im using HX711 load cell interface on board…. My idea is measure value on nodemcu main, and show value on second nodemcu with oled display… same as your example, but getting this value instead of potentiometer… here is my adapted code (Im totally newbie)… I know routine for weight is correct as I tested… but I cant get it together with wifi transmission… can you help me?

    //==================load cell routine =================================

    #include “HX711.h”
    #define DOUT D5
    #define CLK D6

    HX711 balanca;

    float calibration_factor = 4142130; // initial value

    void setup()
    {
    Serial.begin(9600); // serial 9600 Bps
    balanca.begin(DOUT, CLK); // start load cell

    balanca.set_scale();
    zeraBalanca (); // Zero Load CEll
    }

    void zeraBalanca ()
    {
    Serial.println();
    balanca.tare();
    Serial.println(“Balança Zerada “);
    }

    void loop()
    {
    balanca.set_scale(calibration_factor);
    Serial.print(“Peso: “);
    Serial.print(balanca.get_units(), 3); // print weight 3 digits
    Serial.print(” kg”);

    delay(500) ;

    }

    //=======================================================
    Value I want show on display is this one: balanca.get_units()

    so I replaced it on your code on sensorValue

    What Im doing wrong?

    Much thanks for your help!

    1. WordBot says:

      Assuming the result of balanca.get_units() is an integer you should be able to do this

      String url = “/data/”;
      url += “?sensor_reading=”;
      url += balanca.get_units();

      If you test with this sketch you will see more information in the serial monitor: https://robotzero.one/wp-content/uploads/2018/04/ESP8266-wifi-transmitter.ino

  20. Dan Murphy says:

    Hi

    thanks for reply… Ufortunatelly it not worked… I get info on serial monitor but no info on both display…. Sorry for my newbie…. here is full code.. I just mixed code you provided with one from post above….. Any tip to help me please? You are my only hope….lol

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    #include
    #include

    //====================
    #include “HX711.h”
    #define DOUT D5
    #define CLK D6
    //====================

    //U8g2 Constructor List – https://github.com/olikraus/u8g2/wiki/u8g2setupcpp#introduction
    U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 5, /* data=*/ 4);

    const char *ssid = “poopssid”;
    const char *password = “pingu4prez”;

    const int analogInPin = 0; // Analog input pin that the potentiometer is attached to
    int sensorValue = 0; // value read from the potentiometer
    int outputValue = 0; // value sent to server

    //======================================
    HX711 balanca;
    float calibration_factor = 4142130;
    //=====================================

    void setup() {
    Serial.begin(115200);
    delay(10);

    //=====================================
    balanca.begin(DOUT, CLK);
    balanca.set_scale();
    zeraBalanca ();
    //=====================================

    // We start by connecting to a WiFi network
    Serial.println();
    Serial.println();
    Serial.print(“Connecting to “);
    Serial.println(ssid);

    /* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
    would try to act as both a client and an access-point and could cause
    network-issues with your other WiFi-devices on your WiFi-network. */
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(“.”);
    }

    Serial.println(“”);
    Serial.println(“WiFi connected”);
    Serial.println(“IP address: “);
    Serial.println(WiFi.localIP());
    Serial.begin(115200);
    u8g2.begin();
    u8g2.setFont(u8g2_font_logisoso62_tn);
    u8g2.setFontMode(0); // enable transparent mode, which is faster
    }

    //===============================================
    void zeraBalanca ()
    {
    Serial.println();
    balanca.tare();
    Serial.println(“Balança Zerada “);
    }
    //==============================================

    void loop() {
    // read the analog in value:
    //sensorValue = analogRead(A0);
    sensorValue = (balanca.get_units());

    balanca.set_scale(calibration_factor);
    Serial.print(“Weight: “);
    Serial.print(balanca.get_units(), 3);
    Serial.println(” kg”);

    delay(500) ;
    sensorValue = (balanca.get_units());
    // map to range. The pot goes from about 3 to 1023. This makes the sent value be between 0 and 999 to fit on the OLED
    outputValue = map(sensorValue, 3, 1023, 0, 999);

    // print the results to the Serial Monitor:
    Serial.print(“sensor = “);
    Serial.print(balanca.get_units());
    Serial.print(“\t output = “);
    Serial.println(balanca.get_units());
    // Serial.print(“Comunic = “);
    //Serial.println(intToPrint[5]);

    char intToPrint[5];
    itoa(outputValue, intToPrint, 10); //integer to string conversion for OLED library

    Serial.print(“Comunic = “);
    Serial.println(intToPrint);

    u8g2.firstPage();
    u8g2.drawUTF8(0, 64, intToPrint);
    u8g2.nextPage();

    // Use WiFiClient class to create TCP connections
    WiFiClient client;
    const char * host = “192.168.4.1”;
    const int httpPort = 80;

    if (!client.connect(host, httpPort)) {
    Serial.println(“connection failed”);
    return;
    }

    // We now create a URI for the request
    String url = “/data/”;
    url += “?sensor_reading=”;
    url += balanca.get_units();
    //url += intToPrint;

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

    // This will send the request to the server
    client.print(String(“GET “) + url + ” HTTP/1.1\r\n” +
    “Host: ” + host + “\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;
    }
    }

    Serial.println();
    Serial.println(“Closing connection”);
    Serial.println();
    Serial.println();
    Serial.println();

    delay(500);
    }

    +++++++++++++++++++++++++++++++++++++++++++++++++++++

    thats full code…. and thats info I get on serial monitor:

    +++++++++++++++++++++++++++++++++++++++++++++
    09:01:35.282 -> Weight: 0.506 kg
    09:01:35.785 -> sensor = 0.51 output = 0.51
    09:01:35.887 -> Comunic = -2
    09:01:36.090 -> Requesting URL: /data/?sensor_reading=0.51
    09:01:36.258 ->
    09:01:36.258 -> Closing connection
    ++++++++++++++++++++++++++++++++++++++++++++

    and my display shows “0 ” all the time

    Thank you!

    1. WordBot says:

      I think it’s because you are sending a float 0.51(kg) rather than an int 510(g). You can either switch to grams or, on the receiver, change itoa(…) to use this function: http://www.hobbytronics.co.uk/arduino-float-vars

  21. Dan Murphy says:

    how i change it to int? would fit me perfectly…..

    1. WordBot says:

      Can you do it with the library to weigh in grams rather than Kgs? If not multiple your sensor value by 1000 (* 1000) to make the Kg value a gram value.

  22. Dan Murphy says:

    I have no idea, either how to change to grams or where do I multiple *1000 to make it works…. on above code…:/ I know is out of your example idea, but I have no idea how to do it… :/ totally newbie..

    thats only thing missing to make it works…. my weight goes from 10grams to 700grams.. dot need to be kg….

    1. WordBot says:

      I thought it was going to be just changing a setting but this explains how to do it properly: https://github.com/bogde/HX711/issues/70

  23. Carlos says:

    Hello,
    First I’m sorry for my very bad English.
    I hope you can help me with a problem, and I want to send 4 variables (first I am testing with 2), as I read lines above I must use something similar to this:

      // We now create a URI for the request
      String url = “/ data /”;
      url + = “? sensor_reading1 =”;
      url + = intToPrint;
      url + = “/”;
      url + = “? sensor_reading2 =”;
      url + = “2469”; // number for test

    I guess it’s fine since according to serial port monitoring, I’m sending:

    Requesting URL: / data /? Sensor_reading1 = 702 /? Sensor_reading2 = 2469

    Closing connection

    My mistake I think is on the receiver side, the code I am using is:

     void handleSentVar () {
      Serial.println (“handleSentVar function called …”);
      if (server.hasArg (“sensor_reading1”)) {// this is the variable sent from the client
        Serial.println (“Sensor 1 reading received …”);

        int readingInt1 = server.arg (“sensor_reading1”). toInt ();
        int readingInt2 = server.arg (“sensor_reading2”). toInt ();

        Serial.print (“Reading 1:”);
        Serial.println (readingInt1);
        Serial.println ();
        Serial.print (“Reading 2:”);
        Serial.println (readingInt2);
        Serial.println ();
        server.send (200, “text / html”, “Data received”);
      }

    and what I get by serial is:

    handleSentVar function called …
    Sensor 1 reading received …
    Reading 1: 710

    Reading 2: 0

    I hope you can help me, I will be eternally grateful, a greeting from a distance …

    1. WordBot says:

      Hi,
      Sending via a URL follows this format: /data/?firstvar=value1&secondvar=value2&thirdvar=value3 so the first variable has the ? in front and the others all have &
      Your code on the receiving side looks OK to me

  24. Carlos says:

    Dear WordBot,
    Everything works fine, I am indebted to you.
    thank you

  25. Idmus says:

    Hello great article, it really helped me a lot.

    I am currently trying to send data (temperature and humidity from each one respectively) from two sender to a receiver, for the first sender i use the following code:

    String sensor1 = “/data/”;
    sensor1 += “?sensor1h=”;//hum
    sensor1 += intToPrint2;
    sensor1 += “&sensor1t=”;//temp
    sensor1 += intToPrint;

    And for the second one im using the following code:

    String sensor2 = “/data/”;
    sensor2 += “?sensor2h=”;//hum
    sensor2 += intToPrint2;
    sensor2 += “&sensor2t=”;//tem
    sensor2 += intToPrint;

    My problem is with the function “handleSentVar” on the receiver side, which has the following written:

    void handleSentVar() {
    Serial.println(“handleSentVar function called…”);
    if (server.hasArg(“sensor1h”) && server.hasArg(“sensor1h”) )

    The function does not receive parameters from sensor 2 , how can I do it?

    1. WordBot says:

      Hi, Probably easier to have two server.on methods like

      server.on("/data1/", HTTP_GET, handleSentVar1);
      server.on("/data2/", HTTP_GET, handleSentVar2);

      on one sender: String url = “/data1/”;
      on the other: String url = “/data2/”;

      You can then have the two handleSentVar functions displaying the results in each half of the screen.

  26. Idmus says:

    Thank you very much for your quick response, it helped me a lot.

    I have another doubt, is there a way to get the received data to be displayed at defined time intervals?

    I receive data from both clients now but it seems that the time in which the server shows data from one and the other is random, for example sometimes it shows too much time readings from sensor 1, and then shows few readings received from sensor 2.

    I hope I explained myself well.

  27. Idmus says:

    Oh nevermind, i just increase the delay at the end of each client to 2000

    delay(2000)

    thanks again for the first answer

  28. Jonathan Seeburger says:

    Any idea of the range of this system?

    1. WordBot says:

      Hmm. I haven’t tested that. It will depend on your circumstances but I have had ESP32 and ESP8266 working on the roof when the router is some distance away. ESP8266 to ESP8266 over Wi-Fi I imagine would be similar. Some ESP32s have an antennae socket. Maybe someone makes an ESP8266 with the same.

  29. Jonathan Seeburger says:

    Does this require an internet router nearby to work properly, or can it be used without the presence of an internet router?

    1. WordBot says:

      This project doesn’t use a router.

  30. igor says:

    hello! thanks for posting this tutorial.. i am trying to use my PC as sender, and the wimos d1 mini as receiver.. but, how can i send the data to the wimos? also, is this reactive? i am trying to control a LED from the pc, but need it to react quickly when i send some data..
    Thanks

    1. WordBot says:

      Hi, It should be as fast as any other Wi-Fi based project. On the PC you need some way of requesting URLs on your local network. Something like http://esp_ip_address/data/?sensor_reading=123 You can do this in the browser but I don’t know a way of automating it.

  31. Daniel M. says:

    Hi, I’m trying to configure this code for my nodeMCU, but I’m not able to understand that i need an live internet connection or is it OK to use it as it is..??
    Because of some hardware issue I’m not able to use my second nodeMCU.. please help me with this..thankyou!!!

    1. WordBot says:

      Hi, You don’t need internet or even a router if you use the server code. It runs as an access point with the server mounted.

  32. Antônio Victor says:

    Hello, thanks for the post. I’m trying to send data from one esp8266 to another one connected with the computer to show the results in serial monitor. I’m trying to send the values from MPU-6050, which is already working fine but I need to get he results wireless, thats why i want to send to another one and read using serial monitor. Im not sure how to do it… tried the code in this page but did not have success. Is there any ideia how i should do it ? Thanks in advance.

    1. WordBot says:

      Hi. How many values do you need to send? You probably need to change this code so you can send your data in the query string:

      sensorValue = analogRead(A0);
      // map to range. The pot goes from about 3 to 1023. This makes the sent value be between 0 and 999 to fit on the OLED
      outputValue = map(sensorValue, 3, 1023, 0, 999);

      char intToPrint[5];
      itoa(outputValue, intToPrint, 10); //integer to string conversion for OLED library

      Have a look at the comments above for variations on sending data.

  33. Mike Petersen says:

    Is a connection required (from the Station device to the AP device) to transfer data?

    My ESP8266’s are configured for SoftAP+Station mode and I’d like them to broadcast a simple byte-array status message (basically 1 ethernet frame) in station mode to the other ESP8266’s in SoftAP mode. Basically so they can all update each other on their status. I’d like to issue the status as a brief broadcast frame so they can all see it and hopefully I can eliminate actually making a connection.

    Finally is it possible to generate a transmit frame (byte array) and monitor/capture an incoming broadcast frame from the UART side of the device – i.e. using AT commands?

    Thoughts?

    1. WordBot says:

      Whaaaa… this is a bit over my head but maybe look into one of the mesh networks?

  34. CHARH says:

    Hi, I’ve searched all over the internet for something so simple!

    Are there many changes needed to simply send a pushbutton signal to the other board to turn on an LED? I can work around any button parameters, but with the transmit/receive code be the same?

    1. WordBot says:

      Hi, should be pretty easy. Change this code:
      outputValue = map(sensorValue, 3, 1023, 0, 999);
      to something like:
      outputValue = digitalRead(pin);
      and you should see a ‘1’ for outputValue but I’m not 100% sure if HIGH is read as an int.
      https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/

  35. othman says:

    sir what should i add in the client and server, if i want to send more than 1 sensor value?

  36. omar smith says:

    hello sir great tutorial, but i have a little trouble here. I made 2 clients and 1 server . First if client1 is connected to the server, the server is able to handle the data. But if i connect client 2 to the server , suddenly both clients are replying “client timeout!”. I didnt know whats happen to the client? Im really greatfull if you help me out sir thx very much.
    ==========================================================
    //this is the code for client 1 :
    String url = “/data/”;

    url += “?sensor_reading=”;
    url += cm1 ; //data 1
    url += “&sensor_reading2=”;
    url += cm2; //data2

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

    // This will send the request to the server
    client.print(String(“GET “) + url + ” HTTP/1.1\r\n” +
    “Host: ” + host + “\r\n” +
    “Connection: close\r\n\r\n”);
    ===========================================================
    and this is for client 2 :
    String url = “/data2/”;
    url += “?sensor_reading3=”;
    url += cm3;

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

    // This will send the request to the server
    client.print(String(“GET “) + url + ” HTTP/1.1\r\n” +
    “Host: ” + host + “\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;
    }
    }
    ===============================================================
    and this is the server :

    void handleSentVar1() {
    Serial.println(“handleSentVar function called…”);
    if (server.hasArg(“sensor_reading”) && server.hasArg(“sensor_reading2”) ){
    Serial.println(“Sensor reading received…”);

    readingInt = server.arg(“sensor_reading”).toFloat();
    readingInt2 = server.arg(“sensor_reading2”).toFloat();

    void handleSentVar2() {
    Serial.println(“handleSentVar function called2…”);
    if (server.hasArg(“sensor_reading3”)) {
    Serial.println(“Sensor reading received2…”);

    readingInt3 = server.arg(“sensor_reading3”).toFloat();

    server.on(“/data/”, HTTP_GET, handleSentVar);
    server.on(“/data2/”, HTTP_GET, handleSentVar2);

    1. WordBot says:

      Hi,
      if (server.hasArg(“sensor_reading”) && server.hasArg(“sensor_reading2”) )
      Maybe should be
      if (server.hasArg(“sensor_reading”) || server.hasArg(“sensor_reading2”) )
      I don’t think you can read both client values at the same time.

  37. othman says:

    thanks sir finally i made it. Really thx a lot.
    im new in this HTTP field, can you explain to me what is tehcnically happening between esp8266 client and server communication?
    i didnt understand about HTTP GET, Response and others.

    1. WordBot says:

      Great! This explains about HTTP GET etc. It’s the same for any client server system: https://www.w3schools.com/tags/ref_httpmethods.asp

  38. MT says:

    Hi

    Great Article!

    I was wondering if it is possible to display the text with another font such as the ttf files found for Microsoft word?
    If not is it possible to display a simple black and white image? perhaps a BMP image?

    Thank you and I look forward to your response!

    1. WordBot says:

      Hi, There’s a list of fonts you can use here: https://github.com/olikraus/u8g2/wiki/fntlistall
      Other font help: https://github.com/olikraus/u8g2/issues/1140
      Bitmaps: https://github.com/olikraus/u8g2/wiki/u8g2reference#drawxbm
      I don’t have any experience of the custom fonts and bitmaps.

  39. TANGO elc says:

    Could you assist me to an article that explain how to transmit data for 1 to another ESP8266? For example i use 6 ESPs that working as WiFi Client, all of them connected into a WiFi Router. I search everywhere and couldn.t find a clue for data transmission between Clients using HTTP GET. Maybe i was in a wrong searching keywords?

    1. WordBot says:

      Could you explain the situation a bit more.. what do the eps8266 do? Send data to each other or just one other?

  40. Guhan says:

    What is maximum range achieved by this communication??
    Means wifi to wifi can we replace with rf!! 🙂

    1. WordBot says:

      You should be able to use any form of communication but you will have to change the way the data is sent.

  41. Teddy says:

    How about if the client(nodemcu) deactivate and the server(nodemcu) deactivate too?
    And server cut off the output.

    1. WordBot says:

      I don’t understand what you mean.

  42. charan kalyan says:

    hi,
    I want to connect 4 nodeMCU through wifi connection , so can you suggest me an idea?

    1. WordBot says:

      Hi, maybe this will help – https://www.youtube.com/watch?v=gf39MLqPGkQ (using a mesh network)

  43. Jip says:

    Hi ,thank you for your great work!
    I want to build 3 tally lights for live streaming. So 1 transmitter and 3 receivers. On the transmitter 1 want to use 6 pin’s to check if the line is high(through our switcher). On the reciever side, I want to use 2 pin out’s to used with led’s. We can use the wifi in the builiding.
    Thank you 🙂

    1. WordBot says:

      Hi, what have you so far with the project? Do you have code for the transmitter apart from the sending to the receivers?

  44. Jip says:

    Hi, I have done nothing. It is a idea. But I want to know if it’s possible before I sink in the time(not to say I am short on time 🙂 ).
    I was thinking to use your code, because it looked promising. But I am kinda new to all of this.

    1. WordBot says:

      Should be pretty easy. Just monitor the pins for a change (in the loop) and if one goes high then pass the pin number to a function that uses if/else or a switch statement to send the ‘light led’ command to the correct IP address.

  45. Loek says:

    Hi,
    I just want to sent the following “http:///control?cmd=gpio,1,1” with an esp8266, connected to my router, running an exsisting sketch, instead of making a port hi or low. Could you please point me in the right direction?
    Thanks in advance.

    1. WordBot says:

      Hi, How do you want to trigger sending the message to the other device?

  46. Loek says:

    Hi WordBot,
    I am controling valves of my heating by wires so i make a pin low to switch a relay.
    Now I want to go places where i cant use wires so I was thinking of using a esp with easy esp and a relais to accomplish my needs.
    I hope you understand.
    Regards Loek

    1. WordBot says:

      Hi, How about using Sonoffs? – https://robotzero.one/unlock-door-face-detection-sonoff/ ? There’s loads of tutorials on the net and it might be safer than using ESP8266s with relays.

  47. Loek says:

    Hi, i found a httpclient function named put. Works like a charme.
    Thanks for your suggestion.

  48. AVITUS URANUS says:

    hi there,i am a beginner,
    I want to use a 16*2 lcd connected with I2C in place of the oled,and some push buttons wich will allow a simple text to be sent from the transmitter to the receiver,what modification can i make to the code

    1. WordBot says:

      Hi, I don’t really have time at the moment to look at this but take it step by step and look at some other tutorials on the internet.

  49. Jip says:

    Hi,

    is it possible to make it connect to your WiFi instead of using the integrated system? For both the receiver and transmitter? Using it for the long lost tally light project :).

    1. WordBot says:

      Hi, I don’t have the code to hand but if you give the devices a fixed IP address on your network you can communicate between them via their IP address.

      1. jip says:

        Hi,

        thank you for the reply.
        I got it figured out, it wasn’ that dificult.

  50. Rambo says:

    Hello I’m new to using the nodemcu and when is use servo.attach, I think it makes both nodemcus not work together and all I get is this.
    Configuring access point…AP IP address: 192.168.4.1
    HTTP server started

    ets Jan 8 2013,rst cause:4, boot mode:(3,6)

    wdt reset
    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    vffffffff
    ~ld
    ⸮”l r⸮olph
    Configuring access point…AP IP address: 192.168.4.1

    1. WordBot says:

      Hi, Is the servo attached when you do this?

        1. WordBot says:

          Try it without the servo. I think it’s crashing because of the power.

          1. Rambo says:

            It didn’t work, I’m still getting the same feedback from the nodemcu. It only happens when the code is uncommented, if I comment the code it fixes, but then I cant use the servo.

            1. WordBot says:

              Does the servo work if you flash an example that uses it? You should make sure both parts of the project work separately first. Then when you join them together you will have more idea of where the problem is.

              1. Rambo says:

                It has something to do with servo code but it doesn’t seem like the .attach wants work or the Digital pins don’t want to work. I tested all of the nodemcus I had but none of them worked. Sadly no it still doesn’t work when I separate the code

                1. Rambo says:

                  I think i might have figured it out, I found this code: servo.attach(2); //D4 I think it means that the code and the digital pins are 2 points off, so to attach the servo to pin D5, I would need to write servo.attach(3); But I’m not home to test it, so ill see later.

                  1. WordBot says:

                    Yeah the pins on the board don’t match the pins in code on the ESP8266. You need to find a pinout for your board similar to this: https://commons.wikimedia.org/wiki/File:Nodemcu_pins.png

                    1. Rambo says:

                      Thank you this helped a lot, now all I need to do is get home and see if this fixes everything.

  51. Jos Versteege says:

    Thanks for this simple to understand sketch!
    Can I use the same function the other way around? I would also like to send a value from the server to the client.

    1. WordBot says:

      It’s a while since I did this but I’m pretty sure the devices can both send and receive. Maybe installing client and server on both or having the client listen for something from the server.

  52. ghadeer says:

    hello.. i have a car and i control its movement from geroscope sensor on my hand.. and i have 2 pices of esp-01s .. i want to connect pice on my hand with pice on the car
    how can your code help me ?

    1. WordBot says:

      Hi, You just need to get the output from the sensor and send them in the URL as in this tutorial. Check out the comments for how to add more than one variable.

      1. ghadeer says:

        my code become like this :
        transmitter

        #include

        const int analogInPin = 0; // Analog input pin that the potentiometer is attached to
        int sensorValue = 0; // value read from the potentiometer
        int outputValue = 0; // value sent to server

        void setup() {
        Serial.begin(115200);
        delay(10);

        // Explicitly set the ESP8266 to be a WiFi-client
        WiFi.mode(WIFI_STA);

        while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        }

        }

        void loop() {
        // read the analog in value:
        sensorValue = analogRead(A0);

        // Use WiFiClient class to create TCP connections
        WiFiClient client;
        const char * host = “192.168.4.1”;
        const int httpPort = 80;

        if (!client.connect(host, httpPort)) {
        Serial.println(“connection failed”);
        return;
        }

        // We now create a URI for the request. Something like /data/?sensor_reading=123
        String url = “/data/”;
        url += “?sensor_reading=”;
        url += intToPrint;

        // This will send the request to the server
        client.print(String(“GET “) + url + ” HTTP/1.1\r\n” +
        “Host: ” + host + “\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;
        }
        }

        delay(500);
        }

        and for reciver :
        reciver

        #include
        #include

        ESP8266WebServer server(80);

        void handleSentVar() {
        if (server.hasArg(“sensor_reading”)) { // this is the variable sent from the client
        int readingInt = server.arg(“sensor_reading”).toInt();

        server.send(200, “text/html”, “Data received”);
        }
        }

        void setup() {
        delay(1000);

        WiFi.softAP(ssid, password);
        IPAddress myIP = WiFi.softAPIP();

        server.on(“/data/”, HTTP_GET, handleSentVar); // when the server receives a request with /data/ in the string then run the handleSentVar function
        server.begin();
        }

        void loop() {
        server.handleClient();
        }
        is there any wrong ?

  53. Joseph says:

    Hi, I am fairly new to Arduino and the ESP8266 module and I have not read all the comments, so somebody else may have already written about it. On the diagram the pot is connected between GND and the 3V3 rail, meaning this is the Voltage that is fed to A0 input. The datasheet of the ESP8266 writes that the maximum input Voltage is 1.0V to the AtoD. Is the A0 input over-Voltage protected? Or if the input is in the 1.0V and 3.3V range, it just gives a reading of 1024 without damaging the chip?
    Thanks a lot.

    1. WordBot says:

      Hi, The chip itself has a max of 1.0v but a lot of the boards have the analogue inputs at 3.3v max ie the NodeMCU boards.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

scroll to top