Transmit Data between two ESP32 with TCP

Let's assume following usecase with two ESP: One ESP requests several data elements from the other ESP. This second ESP is a "weather station" with several sensors. Beside temperature, humidity and pressure it will also transmit the current runtime to the client. This page will show how to establish a WiFi connection between the two ESP and how to exchange data.

The rolls of the two ESP are like following:

  • ESP A initiates the connection
  • ESP A requests data from ESP B
  • ESP B responds with data to ESP A

The ESP A will act as client, the ESP B will act as server. For the transmission protocol we choose TCP.

The ESP B should transmit several data elements, we will encode the data in JSON.

On end of the page you will find the download of two sketches for the ESP32.

The JSON data format

If you want to transmit a single value, you can just transmit this value. If you want to transmit several data I propose to encode the data as JSON.

This is an example of a simple JSON structure with 4 fields:

{
  "runtime":2181,
  "temperature":38.2,
  "humidity":93.2,
  "pressure":1024.4
}

 There are several advantages using JSON:

  • When your project is growing you can modify the structure of transmitted data.
  • When you add new data fields or delete fields it is very likely that clients will still be able to parse the old data. New fields within the Data structure should not interfere the client.
  • JSON is human readable - makes debugging easier.
  • JSON adds less overhead to the payload than XML.

Generating ("encoding") a simple JSON could be done manually. Decoding of a JSON is complicated, but there is the ArduinoJson library available. ArduinoJson is quite substantial, but also offers an online code generator called "ArduinoJson Assistant" which will help you to generate the right code. As we will need the ArduinoJson library anyway in this project, we will use it for encoding also.

The ESP TCP Server

The TCP server will be started to listen on a specified port. I have chosen 1040 because it is a "free" unused port.

When another client has connected, the server will collect local data, generate a JSON and respond with the data (= payload).

To generate the JSON encoder go to the homepage of ArduinoJson and configure the ArduinoJson Assistant:

Click through all steps, provide the requested data until you get to step 4:

Copy paste the result in the function handleTcpServer(). Obvious you should replace the fix values with real sensor readings. The server demo sketch doesn't come with real sensors, so it just generates some random values. Modify this code to your needs.

StaticJsonDocument<128> doc;

doc["runtime"] = millis() / 1000;
doc["temperature"] = random(0, 500) / 10.0;
doc["humidity"] = random(100, 1000) / 10.0;
doc["pressure"] = 1024.4;

serializeJson(doc, output);

Flash the program to the ESP and note the server IP address from the serial monitor.
 

ESP TCP Client

The TCP client sketch is based on the the IDE Example "Wifi / WifiClient". It consists of several functions

tcpRequest()
main function to send a TCP request
tcpTimer()
is a timer to trigger tcpRequest() in your specified interval
readResponse()
reads incoming data after the TCP request was startet
handleSerial()
is a helper function. When you enter a t (like tcp) in the serial monitor, the tcpRequest() will be triggered immediately.

As mentioned above, the TCP server will respond with data encoded in JSON format. When you have modified the server to transmit your specific kind of data, start again the ArduinoJson Assistant and let it generate the code to deserialize data:

now copy / paste the generated code into the function tcpRequest.

Before you upload the code to your ESP, you must set the IP address of your server. Also the port must fit to the used port on the server.

const char* serverAddress = "172.18.67.218"; // the module will send information to that server/resource. Use an URI or a IP address
const uint16_t serverPort = 1040;            // the same port like defined in the server

Wifi Setup

In both sketches you need to provide your WiFi credentials or you can link to a file with your credentials.

//#include <credentials.h>      // if you have a config file with your credentials

#ifndef STASSID
#define STASSID "your-ssid"     // set your SSID
#define STAPSK "your-password"  // set your wifi password
#endif

Summary

The example code shows how to transmit data between two microcontrollers using JSON.

Links

(*) Disclosure: Some of the links above are affiliate links, meaning, at no additional cost to you I will earn a (little) comission if you click through and make a purchase. I only recommend products I own myself and I'm convinced they are useful for other makers.

History

First upload: 2024-03-07 | Version: 2024-03-22