Communication between two ESP8266

This guide shows you how to establish a connection between two ESP8266 devices using TCP/IP over WiFi and exchange data. One ESP8266 will function as a TCP client, while the other will act as a TCP server. We'll delve into this process through an example:

Hardware Preparation

2×ESP8266 NodeMCU
2×Micro USB Cable
1×(Optional) ESP8266 Screw Terminal Adapter

Or you can buy the following sensor kit:

1×DIYables Sensor Kit 30 types, 69 units
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you. We appreciate your support.

Communication between two ESP8266 - Overview

Let us think of a particular example: ESP8266 #1 interacting with ESP8266 #2. There are numerous ways to enable communication between the two ESP8266. We can select one of them based on the distance of communication. The table below displays some methods and the corresponding communication range.

Methods Range
I2C very short
SPI very short
UART (TTL) very short
UART (RS-232/485/422) short
Bluetooth short
LoRa long
Ethernet/WiFi unlimited(*)

※ NOTE THAT:

  • If two ESP8266 are connected to the Internet, the communication range is unrestricted.
  • However, if two ESP8266 are not connected to the Internet, but instead connected in the same LAN network, their communication range is confined to that local area network.

Among the methods mentioned above, this tutorial uses WiFi to enable communication between two ESP8266 as it allows for an unrestricted range of communication.

Communication between two ESP8266 via local LAN or Internet

Two ESP8266 can communicate with one another through WiFi when:

  • They are in the same Local Area Network (LAN), and an Internet connection is not necessary
  • They are in different LANs, and an Internet connection is needed

No matter if two ESP8266 are connected within a local LAN network or via the Internet, there are two ways of communication:

When it comes to direct communication, typically one ESP8266 is the TCP client and the other is the TCP server.

In the instance of utilizing a centralized server for communication, typically both ESP8266 act as TCP clients.

When deciding on an application protocol for communication between two ESP8266, we have several options to choose from:

  • Self-defined protocol over raw TCP
  • Modbus TCP
  • HTTP
  • Telnet
  • SSH
  • MQTT (which requires a centralized server)

Example Application

Let's make a reality of the following program: A button/switch attached to ESP8266 #1 will be used to turn on and off an LED connected to ESP8266 #2 through WiFi.

communication between two esp8266

As stated previously, there are a few application protocols available. To simplify this example, we will create our own protocol (a self-defined protocol).

Self-defined Protocol

Let us set up a straightforward protocol:

  • Establish a TCP connection between ESP8266 #1 and ESP8266 #2
  • ESP8266 #1:
    • Behave as a TCP client, initiating the TCP connection to ESP8266 #2
    • When the switch is flipped to ON, send a byte (command) with value 1 to ESP8266 #2.
    • When the switch is flipped to OFF, send a byte (command) with value 0 to ESP8266 #2.
  • ESP8266 #2:
    • Serve as TCP server, listening for TCP connection requests from ESP8266 #1
    • If the received byte is 1, turn ON the LED
    • If the received byte is 0, turn OFF the LED

    Wiring Diagram

    • ESP8266 #1 - Wiring diagram between ESP8266 and button
    The wiring diagram between ESP8266 NodeMCU and Button

    This image is created using Fritzing. Click to enlarge image

    See more in ESP8266's pinout and how to supply power to the ESP8266 and other components.

    • ESP8266 #2 - Wiring diagram between ESP8266 and LED
    The wiring diagram between ESP8266 NodeMCU and LED

    This image is created using Fritzing. Click to enlarge image

    ESP8266 Code for ESP8266 #1

    /* * This ESP8266 NodeMCU code was developed by newbiely.com * * This ESP8266 NodeMCU code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp8266/communication-between-two-esp8266 */ #include <ezButton.h> #include <ESP8266WiFi.h> #define BUTTON_PIN D7 // The ESP8266 pin connected to button #define SERVER_IP "192.168.0.180" #define SERVER_PORT 4080 ezButton button(BUTTON_PIN); // create ezButton attached to pin D7 const char WIFI_SSID[] = "YOUR_WIFI_SSID"; // CHANGE TO YOUR WIFI SSID const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // CHANGE TO YOUR WIFI PASSWORD WiFiClient TCPclient; void setup() { Serial.begin(9600); button.setDebounceTime(50); // set debounce time to 50 milliseconds Serial.println("ESP8266 #1: TCP CLIENT + A BUTTON/SWITCH"); // Connect to WiFi WiFi.begin(WIFI_SSID, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); // Connect to TCP server (ESP8266 #2) if (TCPclient.connect(SERVER_IP, SERVER_PORT)) Serial.println("ESP8266 #1: Connected to TCP server"); else Serial.println("ESP8266 #1: Failed to connect to TCP server"); } void loop() { button.loop(); // MUST call the loop() function first if (!TCPclient.connected()) { Serial.println("ESP8266 #1: Connection is disconnected"); TCPclient.stop(); // Reconnect to TCP server (ESP8266 #2) if (TCPclient.connect(SERVER_IP, SERVER_PORT)) Serial.println("ESP8266 #1: Reconnected to TCP server"); else Serial.println("ESP8266 #1: Failed to reconnect to TCP server"); } if (button.isPressed()) { TCPclient.write('1'); TCPclient.flush(); Serial.println("ESP8266 #1: - The button is pressed, sent command: 1"); } if (button.isReleased()) { TCPclient.write('0'); TCPclient.flush(); Serial.println("ESP8266 #1: - The button is released, sent command: 0"); } }

    ESP8266 Code for ESP8266 #2

    /* * This ESP8266 NodeMCU code was developed by newbiely.com * * This ESP8266 NodeMCU code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp8266/communication-between-two-esp8266 */ #include <ESP8266WiFi.h> #define LED_PIN D6 // The ESP8266 pin connected to LED #define SERVER_PORT 4080 const char WIFI_SSID[] = "YOUR_WIFI_SSID"; // CHANGE TO YOUR WIFI SSID const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // CHANGE TO YOUR WIFI PASSWORD WiFiServer TCPserver(SERVER_PORT); void setup() { Serial.begin(9600); pinMode(LED_PIN, OUTPUT); Serial.println("ESP8266 #2: TCP SERVER + AN LED"); // Connect to Wi-Fi WiFi.begin(WIFI_SSID, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); // Start the TCP server TCPserver.begin(); } void loop() { // Check if a client has connected WiFiClient client = TCPserver.available(); if (client) { // Read the command from the TCP client char command = client.read(); Serial.print("ESP8266 #2: - Received command: "); Serial.println(command); if (command == '1') digitalWrite(LED_PIN, HIGH); // Turn LED on else if (command == '0') digitalWrite(LED_PIN, LOW); // Turn LED off client.stop(); // Close the connection } }

    Detailed Instructions

    To get started with ESP8266 on Arduino IDE, follow these steps:

    • Check out the how to setup environment for ESP8266 on Arduino IDE tutorial if this is your first time using ESP8266.
    • Wire the components as shown in the diagram.
    • Connect two ESP8266 boards to your computer using a USB cable.
    • Open the Arduino IDE (called Arduino IDE #1).
    • Open the Arduino IDE (called Arduino IDE #2).
    • Choose the correct ESP8266 board, such as (e.g. NodeMCU 1.0 (ESP-12E Module)), and its respective COM port.
    • Install the ezButton library on Arduino IDE.
    • Copy the ESP8266 #1 code, paste it to Arduino IDE #1 and save it (named ESP8266-1).
    • Copy the ESP8266 #2 code, paste it to Arduino IDE #2 and save it (named ESP8266-2).
    • Upload ESP8266 #2 code to ESP8266 #2 first.
    • Open the Serial Monitor on Arduino IDE #2, get the TCP Server IP address.
    COM6
    Send
    ARDUINO #2: TCP SERVER + AN LED TCP Server IP address: 192.168.0.2 -> Please update the serverAddress in ESP8266 #1 code
    Autoscroll Show timestamp
    Clear output
    9600 baud  
    Newline  
    • Change the TCP Server IP address in the code of ESP8266 #1.
    • Upload ESP8266 #1 code to ESP8266 #1
    • Open the Serial Monitor on the Arduino IDE #1.
    • Press and hold the button on ESP8266 #1 and observe the LED's state on ESP8266 #2 (it should be ON).
    • Release the button on ESP8266 #1 and observe the LED's state on ESP8266 #2 (it should be OFF).
    • Press, hold, and release the button several times.
    • Check the output on Serial Monitor #1:
    COM6
    Send
    ARDUINO #1: TCP CLIENT + A BUTTON/SWITCH Connected to TCP server ESP8266 #1: - The button is pressed, sent command: 1 ESP8266 #1: - The button is released, sent command: 0 ESP8266 #1: - The button is pressed, sent command: 1 ESP8266 #1: - The button is released, sent command: 0
    Autoscroll Show timestamp
    Clear output
    9600 baud  
    Newline  
    • Check the output on Serial Monitor #2:
    COM6
    Send
    ARDUINO #2: TCP SERVER + AN LED TCP Server IP address: 192.168.0.2 -> Please update the serverAddress in ESP8266 #1 code ESP8266 #2: - Received command: 1 ESP8266 #2: - Received command: 0 ESP8266 #2: - Received command: 1 ESP8266 #2: - Received command: 0 ESP8266 #2: - Received command: 1 ESP8266 #2: - Received command: 0
    Autoscroll Show timestamp
    Clear output
    9600 baud  
    Newline  

Video Tutorial

How to connect two ESP8266 via Internet

There are two types of IP address: private and public. The IP address typically used in a home network is a private one.

It is simple to recognize a private IP address. There are three formats of private IP address: 10.x.x.x, 172.16.x.x, 192.168.x.x

It is not important to utilize the private IP address in the following scenarios:

  • When two ESP8266 are within the same local area network, regardless of whether they are communicating directly or through a centralized server, and regardless of whether the LAN is connected to the internet or not.
  • When two ESP8266 are in separate local area networks and are communicating with one another through a centralized server.

In the case of two ESP8266 being in different LAN networks and communicating with each other directly, the ESP8266 TCP client can utilize a private IP address. However, the ESP8266 TCP server must use either:

  • A public IP address
  • A private IP address with "Port Forwarding" on the Router/Access Point

The technique of "Port Forwarding" varies from router/AP to router/AP. This tutorial does not cover this topic.

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!