Wireless connection between two microcontrollers ESP8266 Opens up wide possibilities for creating distributed smart home systems, sensors with remote data transmission, or even simple chatbots based on IoT devices. Unlike the classic wired Arduino connection, Wi-Fi communication allows modules to be placed at a distance of up to 100 meters (under ideal conditions) without losing stability. However, many encounter problems when first attempting to establish such interaction: one module fails to see the other, data transfer is delayed, or the connection constantly breaks.
In this article we will look at three main methods of communication between ESP8266: through TCP server/client, UDP protocol and data exchange through MQTT brokerEach method has its pros and cons—for example, TCP is more reliable for transmitting critical data, while UDP is faster and easier to implement. We'll cover the configuration of each option in detail and provide ready-made sketches for Arduino IDE, and we will also tell you how to diagnose errors of the type connection failed or WiFi disconnectedIf you've never worked with network protocols on microcontrollers before, don't worry: all examples are tailored for beginners, with explanations for every line of code.
1. Preparation of equipment and software
Before you start programming, make sure you have everything you need. You'll need:
- 🔌 Two modules ESP8266 (For example, NodeMCU or Wemos D1 Mini). Any version will do, but it is better to use models with external antenna for greater connection stability.
- 💻 Computer with installed Arduino IDE (version 2.0 or later). Alternative - PlatformIO, but in this article we will use the classic environment.
- 🔌 USB cables for flashing and powering modules. Please note: some cheap cables may not provide sufficient current, resulting in unstable Wi-Fi operation.
- 📡 Wi-Fi router (router) with support for the standard
802.11 b/g/n. Modules ESP8266 don't work with modern onesWi-Fi 6, so if you have a new router, you may need to enable compatibility mode.
Also check that in Arduino IDE drivers are installed for ESP8266To do this, go to File → Settings and in the field Additional links for the board manager add:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
Then in Tools → Board → Board Manager find esp8266 and install the latest version. If you already have experience with ESP32, remember: libraries and settings for ESP8266 may differ!
⚠️ Attention: If you use modules ESP-01 with a limited number of pins, please note that firmware may require jumper betweenGPIO0AndGNDWithout it, loading the code will not be possible.
2. Method 1: Communication via TCP server and client
This is the most reliable method of data exchange, because The TCP protocol guarantees packet delivery. and monitors the integrity of the transmitted information. One module will act as servers, and the second one is clientThe server listens for incoming connections on a specified port, and the client initiates the connection and sends data.
Below is a sample code for servers (download to the first one) ESP8266):
#include <ESP8266WiFi.h>const char* ssid = "your_SSID";
const char* password ="your_password";
WiFiServer server(80); // Port 80 (you can use any free one)
void setup {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status!= WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Server IP address:");
Serial.println(WiFi.localIP);
server.begin;
}
void loop {
WiFiClient client = server.available;
if (client) {
Serial.println("New client connected!");
while (client.connected) {
if (client.available) {
String data = client.readStringUntil('\n');
Serial.print("Received:");
Serial.println(data);
client.print("Server accepted:" + data); // Response to the client
}
}
client.stop;
Serial.println("The client has disconnected.");
}
}
Code for client (we load it on the second one) ESP8266):
#include <ESP8266WiFi.h>const char* ssid = "your_SSID";
const char* password ="your_password";
const char* host ="IP_address_of_the_server"; // Specify the IP that the server returned
const uint16_t port = 80;
void setup {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status!= WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void loop {
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("Connection failed...");
delay(5000);
return;
}
client.print("Greetings from the client!\n");
while (client.connected) {
if (client.available) {
String response = client.readStringUntil('\n');
Serial.println("The server responded:" + response);
}
}
client.stop;
delay(2000); // Pause before reconnecting
}
After downloading the code, open Serial Monitor V Arduino IDE (speed 115200 baud) and check the data exchange. If the connection is not established:
- 🔍 Make sure both modules are connected to one Wi-Fi network.
- 📡 Check that the server's IP address is specified correctly (you can set it in your router settings).
- 🔌 Try changing the port (for example, to
8080), If80busy.
3. Method 2: Fast data transfer via UDP
UDP protocol It doesn't guarantee packet delivery, but it's significantly faster than TCP and requires fewer resources. This is the ideal option for transmission. non-critical data, for example, temperature sensor readings or LED control signals, where the loss of one or two packets is not critical.
Sample code for UDP servers:
#include <ESP8266WiFi.h>#include <WiFiUdp.h>
const char* ssid = "your_SSID";
const char* password ="your_password";
WiFiUDP udp;
unsigned int localPort = 4210; // Listening port
void setup {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status!= WL_CONNECTED) delay(500);
udp.begin(localPort);
Serial.print("UDP server started on port");
Serial.println(localPort);
}
void loop {
int packetSize = udp.parsePacket;
if (packetSize) {
char packetBuffer[255];
int len = udp.read(packetBuffer, 255);
if (len > 0) packetBuffer[len] ='\0';
Serial.print("Received:");
Serial.println(packetBuffer);
// Sending a response
udp.beginPacket(udp.remoteIP, udp.remotePort);
udp.write("The server has accepted your message!");
udp.endPacket;
}
}
Code for UDP client:
#include <ESP8266WiFi.h>#include <WiFiUdp.h>
const char* ssid = "your_SSID";
const char* password ="your_password";
WiFiUDP udp;
const char* serverIP ="IP_address_of_the_server";
unsigned int serverPort = 4210;
void setup {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status!= WL_CONNECTED) delay(500);
}
void loop {
udp.beginPacket(serverIP, serverPort);
udp.print("Greetings from UDP client!");
udp.endPacket;
delay(1000);
// Check the response from the server
int packetSize = udp.parsePacket;
if (packetSize) {
char reply[255];
int len = udp.read(reply, 255);
if (len > 0) reply[len] ='\0';
Serial.print("The server responded:");
Serial.println(reply);
}
}
The main advantages of UDP:
- ⚡ Minimal delays - no delivery confirmation.
- 📉 Less CPU load compared to TCP.
- 🔄 Supports broadcast (multicast).
⚠️ Note: UDP is not suitable for transmitting sensitive data (such as relay control commands or alarms). In such cases, use TCP or MQTT.
Uploaded code to both modules|
You have specified the correct server IP address|
The port on the server and client is the same|
Both modules are on the same Wi-Fi network|
Opened Serial Monitor for debugging-->
4. Method 3: Data exchange via MQTT broker
Protocol MQTT (Message Queuing Telemetry Transport) is ideal for systems with a large number of devices where each module needs to send data to a central server (broker) and receive commands from it. Unlike a direct TCP/UDP connection, there is no need to know the IP addresses of the devices—they communicate via topics (topics).
To work you will need:
- Set up an MQTT broker (e.g. Mosquitto on Raspberry Pi or use a cloud service like HiveMQ or EMQX).
- Connect the library
PubSubClientV Arduino IDE (Sketch → Include Library → Manage Libraries). - Set up topics for exchange (for example,
esp8266/sensor1Andesp8266/command).
Sample code for MQTT client (one of the modules):
#include <ESP8266WiFi.h>#include <PubSubClient.h>
const char* ssid = "your_SSID";
const char* password ="your_password";
const char* mqtt_server ="broker.hivemq.com"; // Public broker
const char* topic_pub ="esp8266/sensor1";
const char* topic_sub ="esp8266/command";
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message in topic [");
Serial.print(topic);
Serial.print("]:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println;
}
void setup {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status!= WL_CONNECTED) delay(500);
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void reconnect {
while (!client.connected) {
if (client.connect("ESP8266Client")) {
client.subscribe(topic_sub);
} else {
delay(5000);
}
}
}
void loop {
if (!client.connected) reconnect;
client.loop;
// Send data every 2 seconds
static unsigned long lastMsg = 0;
if (millis - lastMsg > 2000) {
lastMsg = millis;
int value = random(0, 100);
char msg[50];
snprintf(msg, 50,"Sensor value: %d", value);
client.publish(topic_pub, msg);
}
}
Advantages of MQTT:
| Characteristic | TCP | UDP | MQTT |
|---|---|---|---|
| Reliability of delivery | ✅ High | ❌ Low | ✅ High (with QoS) |
| Transfer speed | 🐢 Average | ⚡ Fast | 🐢 Average |
| Scalability | ❌ Limited | ❌ Limited | ✅ High |
| Difficulty of setup | 🔧 Average | 🟢 Simple | 🔧 Average (broker required) |
⚠️ Warning: When using public MQTT brokers (e.g. test.mosquitto.org) your data may be intercepted. For critical systems, configure your broker with encryption (TLS).
5. Common mistakes and their solutions
Even with the correct settings, the connection between ESP8266 may be unstable. Here are the most common problems and how to fix them:
- 🔌 The module does not connect to Wi-Fi:
- Please check that you entered the correct information.
SSIDand password (case sensitive!). - Make sure your router isn't blocking new devices (sometimes rebooting the router helps).
- Try connecting to a different network (for example, from your phone in hotspot mode).
- Please check that you entered the correct information.
- 📡 The connection is broken after a few seconds.:
- Increase the interval between data sendings (for example, from
delay(1000)ondelay(5000)). - Check the power supply to the modules - unstable voltage leads to Wi-Fi failures.
- Update the firmware ESP8266 through
Arduino IDE(Tools → Board → Update).
- Increase the interval between data sendings (for example, from
- 🔄 Data is transmitted with delays:
- For TCP/UDP, reduce the packet size (send data in 50-100 byte chunks).
- For MQTT, reduce the level
QoS(for example, with1on0). - Check your network load - your router may be overloaded with other devices.
If the problem is not solved, turn on debug mode in the code, adding the output of additional information in Serial. For example:
Serial.print("Wi-Fi status:");
Serial.println(WiFi.status); // Prints the numeric status code
Decoding status codes:
0— WL_IDLE_STATUS (connection broken).3— WL_CONNECTED (successful connection).6— WL_DISCONNECTED (manually disabled).
How to check the quality of Wi-Fi signal?
Open Serial Monitor and run the command:
Serial.print("Signal level (RSSI):");Serial.print(WiFi.RSSI);
Serial.println(" dBm");
RSSI values:
- -30 dBm - excellent signal.
- -60 dBm — average (packet loss is possible).
- -90 dBm - weak (the connection will be unstable).
6. Optimizing your connection: tips for stable operation
To connect between ESP8266 To ensure it works without any problems, follow these recommendations:
- 📶 Place the modules in a strong reception areaWalls, metal structures, and household appliances (microwaves!) can degrade the signal. For testing, use apps like WiFi Analyzer (Android) to find the least loaded channel.
- 🔋 Use high-quality power supplies. ESP8266 sensitive to voltage drops. Optimal:
5V/2Afor each module. If you're powering from USB, avoid extension cords. - 🔄 Set up static IP addresses in the router for both modules. This will prevent problems when changing the IP after a reboot. In most routers, this is done in the
DHCP Reservation. - 🛡️ Disable Wi-Fi power saving mode on the router (optional)
Wi-Fi Power SaveorGreen AP). It can break the connection with ESP8266.
For critical projects (such as security systems), duplicate communication channels. For example, you can combine:
- 📡 Main channel - Wi-Fi (TCP/MQTT).
- 📟 Backup channel - LoRa or low frequency radio modules (For example, NRF24L01).
7. Alternative methods of communication between ESP8266
If Wi-Fi isn't an option for some reason (for example, you don't have a router or need a long-distance connection), consider these options:
| Method | Range | Speed | Complexity | Example of use |
|---|---|---|---|---|
| Wi-Fi Direct (ESP-NOW) | Up to 200 m | High | Average | Direct exchange without a router |
| LoRa (SX1278) | Up to 10 km | Low | High | Long-range sensors |
| NRF24L01 | Up to 100 m | Average | Low | Local sensor networks |
| Bluetooth (ESP32) | Up to 10 m | Average | Low | Control from your phone |
For example, protocol ESP-NOW allows you to organize a direct connection between ESP8266 Without a router, but requires preliminary "pairing" of devices. Sample initialization code:
#include <espnow.h>// MAC address of the second module (specify yours!)
uint8_t broadcastAddress = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
void setup {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
if (esp_now_init!= 0) {
Serial.println("ESP initialization error - NOW!");
return;
}
esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER);
esp_now_add_peer(broadcastAddress, ESP_NOW_ROLE_SLAVE, 1, NULL, 0);
}
Read more about ESP-NOW Read our separate article (you will find the link in the "Related Materials" section).
FAQ: Frequently Asked Questions about ESP8266 Communications
Is it possible to connect ESP8266 directly without a router?
Yes, the protocol will work for this. ESP-NOW or mode Wi-Fi Ad-Hoc (point-to-point). In the first case, modules exchange data via MAC addresses, in the second - one ESP8266 One creates its own network, and the other connects to it. Both options work without the internet, but the connection range is limited (up to 100 m under ideal conditions).
How to increase the communication range between modules?
There are several ways:
- Use ESP8266 With external antenna (For example, ESP-12F).
- Install signal amplifier (for example, module PA+LNA for ESP8266).
- Change it Wi-Fi channel in the router to a less loaded one (use WiFi Analyzer).
- Reduce transmission speed in the router settings (for example, with
300 Mbpson54 Mbps).
You can also use directional antennas or Wi-Fi repeaters, but this will complicate the system.
Why is data transmission delayed?
Delays may occur for the following reasons:
- 📶 Weak Wi-Fi signal - check the level
RSSI(should be higher-70 dBm). - 🖥️ Router overload - Disconnect unnecessary devices from the network.
- 🐢 Slow protocol — TCP is more reliable, but slower than UDP. For sensors it is better to use UDP.
- 🔋 Out of memory - if there are many variables or libraries in the code, ESP8266 may "slow down".
For diagnostic purposes, add the output of the packet sending/receiving time to the code:
unsigned long startTime = millis;//... sending data...
unsigned long endTime = millis;
Serial.print("Delay:");
Serial.print(endTime - startTime);
Serial.println("ms");
How to protect transmitted data?
By default, the data between ESP8266 are transmitted in clear text. For protection, use:
- 🔐 Encryption - library
Crypto(For example, AES). - 🌐 VPN for IoT - connect the modules to the VPN server (for example, OpenVPN).
- 🔒 MQTT with TLS - set up a broker with encryption support (for example, Mosquitto + Let's Encrypt).
- 🔑 Authentication — check the MAC addresses of devices before exchanging data.
An example of simple encryption using XOR (not for sensitive data!):
String encrypt(String data, char key) {String result ="";
for (int i = 0; i < data.length; i++) {
result += char(data[i] ^ key);
}
return result;
}
Is it possible to interface ESP8266 with ESP32?
Yes, these modules are fully protocol compatible. Wi-Fi, TCP/UDP And MQTTThe only nuances:
- IN ESP32 more memory, so you can use more complex libraries.
- For ESP-NOW you will need to update the firmware on ESP8266 to the latest version.
- ESP32 supports Bluetooth, which is not in ESP8266.
Example of communication code ESP8266 (client) And ESP32 (server) via TCP is identical to the one above - just adjust the IP addresses.