How to Link Two ESP8266s via WiFi: A Complete Guide

Creating a decentralized smart home network often requires direct communication between devices without the use of a central router. Modules ESP8266 are ideal for this task due to their low cost and library support ESP8266WiFiIn this article, we'll look at how to enable two such modules to communicate directly using point-to-point operation.

To implement the project, you will need two chip-based devices. ESP8266, for example, popular boards NodeMCU or WeMos D1 Mini. It is important to understand that one device will operate in access point mode (AP), creating a network, and the second one is in client mode (STA), connecting to it. This architecture allows for the transmission of commands and data even without internet access.

Before you begin, make sure your development environment is set up Arduino IDE The necessary libraries for board support are installed. The standard set of tools makes it easy to set up networking, but requires careful consideration of IP addressing. Proper configuration TCP protocol or UDP guarantees stable transmission of packets between nodes of your system.

Selecting a connection scheme and preparing equipment

The first step is to physically connect the modules to the computer for flashing. Since we'll be using two devices, you'll need either two USB cables or a single cable to sequentially flash each module one at a time. Make sure you have the drivers for the USB-UART converter (usually CH340 or CP2102) are correctly installed in the system.

The connection diagram is standard for working with Arduino IDEContacts TX And RX on the module board must be connected to the corresponding contacts on the USB adapter. For power supply, it is recommended to use an external power source. 3.3 Volts, since the computer's USB port may not be sufficient for stable operation of the WiFi module under load.

β˜‘οΈ Equipment preparation

Completed: 0 / 4

When assembling the circuit, pay attention to the soldering of the contacts. Poor contact in the power supply often leads to cyclic reboots of the module, making it impossible to establish a network connection. Use high-quality wires and, if possible, add a 10-20 Β΅F capacitor in parallel with the power contacts.

Setting up the Arduino IDE and libraries

For programming microcontrollers of the family ESP You need to add support for the board in the device manager menu. Open the settings. Arduino IDE and in the "Additional URLs for the board manager" field, paste the link to the repository http://arduino.esp8266.com/stable/package_esp8266com_index.jsonThis will allow you to install the kernel to work with the chip.

After adding the URL, go to Tools β†’ Board β†’ Board Manager and find the package esp8266Install the latest stable version. The installation process will download all necessary compilers and libraries, including ESP8266WiFi And ESP8266WebServer, which we will use to organize communication.

What to do if the board is not detected?

If the computer doesn't detect the device, check the quality of the USB cable. Many cables are designed only for charging and do not have data lines. Also, try pressing the power button. FLASH or RST on the board during connection.

It's important to select the correct board parameters before compiling. In the "Tools" menu, select your model (e.g. NodeMCU 1.0), the port the device is connected to, and the download speed. For most modules, the optimal speed is 115200 baud, although it can be used for debugging 9600.

Server Programming (AP)

The first module will act as a server, creating a local WiFi network. In the sketch, you need to initialize WiFi in the following mode: WIFI_APWe'll set the network name (SSID) and password that the second device will use to connect. This creates an isolated perimeter for data exchange.

To handle incoming connections, we will run a server on the standard port. 80 ilin, for example, 8080The server will wait for connections from the client and send an acknowledgement of data receipt. This is implemented in the code through the object WiFiServer and the client verification cycle in the function loop.

#include 

const char* ssid ="ESP_Network";

const char* password ="12345678";

WiFiServer server(8080);

void setup {

Serial.begin(115200);

WiFi.softAP(ssid, password);

server.begin;

Serial.println("Server started");

Serial.print("IP Address:");

Serial.println(WiFi.softAPIP);

}

void loop {

WiFiClient client = server.available;

if (client) {

while (client.connected) {

if (client.available) {

String data = client.readStringUntil('\n');

Serial.println("Received:" + data);

client.print("OK");

client.stop;

}

}

}

}

Please note the usage IP addresses, which is assigned to the server automatically. In access point mode, the address is usually 192.168.4.1The client device will need to know this address to establish a successful connection. Outputting the address to the serial port helps quickly find it during debugging.

Client Programming (STA Mode)

The second module will operate in station mode (WIFI_STA). Its task is to find the network created by the first module and connect to it. To do this, the client sketch specifies the same SSID and password as the server. After a successful connection, the client receives an IP address from the server's network range.

To transfer data, the client creates a TCP connection to the server's IP address. In the function loop We can read data from the computer's serial port or from sensors and send it through the object. WiFiClientIt is important to implement connection status checking to avoid sending errors.

Parameter Server (AP) Client (STA)
WiFi mode SoftAP Station
IP Address 192.168.4.1 (usually) 192.168.4.x (dynamic)
Port 8080 (listening) 8080 (connects)
Main function Waiting for data Sending data

The client code must contain a reconnection mechanism. If the connection to the access point is lost, the device must automatically attempt to reconnect. This is critical for autonomous systems where human intervention is limited.

πŸ“Š What protocol are you planning to use?
TCP (guaranteed delivery)
UDP (fast forwarding)
MQTT (via broker)
HTTP requests

Organization of two-way data exchange

Simply sending commands is only half the task. For a smart home to function properly, devices often need to confirm actions or request data from each other. Implementing bidirectional communication requires both the server and the client to be able to both send and receive bytes.

In the implementation shown above, the server only reads data. To make the connection fully functional, the logic needs to be modified: the server must be able to initiate sending data to the client, and the client must constantly poll the port for incoming messages. This turns the connection into a full-fledged dialogue.

⚠️ Warning: TCP is a blocking protocol in some implementations. If a client is waiting for a response from the server, it may hang until it receives a packet or the timeout expires. Always set connection timeouts using the [unspecified] method. client.setTimeout.

Simple text commands, such as "GET_STATUS" or "LED_ON," can be used to synchronize data exchange. Parsing such strings on the receiving device allows for easy control of the logic without complex binary protocols. This is especially convenient for debugging via the serial monitor.

Troubleshooting and optimization

The most common issue when connecting two ESP8266 modules is unstable power supply. When WiFi is enabled, the module draws up to 300-500 mA per pulse. If the power supply is weak, the voltage drops, and the module reboots, breaking the connection. Use power supplies with at least 500 mA of current capacity per module.

The second important aspect is interference. If you're testing devices in an apartment with dozens of other WiFi networks, the channels may be overloaded. You can specify the access point's operating channel in the code (parameter channel in function softAP), choosing the least loaded one, for example, 1, 6 or 11.

Memory limitations should also be considered. Receive and transmit buffers are limited. If you're transmitting large amounts of data, break it into small packets. This will prevent buffer overflows and data loss.

⚠️ Note: Libraries and WiFi methods may be updated by the ESP8266 core developers. If you are using older sketches, please check the documentation for the latest library version, as the syntax of some functions may have changed.

Advanced Features and Security

The basic configuration does not provide encryption for transmitted data other than the standard WPA2 for network connection. If you are transmitting sensitive information, consider implementing simple application-level encryption or using SSL/TLS, although this will require more CPU resources.

Two linked modules can form the basis of more complex systems. You can add a third module, connecting it to the same access point, creating a one-to-many network. Alternatively, you can implement a mesh network, where devices relay signals to each other, increasing coverage.

Can these modules be used outdoors?

Standard NodeMCU boards are not protected against moisture or dust. For outdoor use, they must be placed in sealed enclosures with an IP65 rating or higher, and heat dissipation must be provided, as they can overheat in direct sunlight.

What is the maximum distance between modules?

In open spaces, the range with a standard antenna can reach 50-100 meters. In urban areas or indoors with concrete walls, the range decreases to 10-20 meters. Using an external antenna can significantly increase this range.

Do I need a router for this connection to work?

No, the described setup (AP-STA) doesn't require a router. The modules create their own local network. However, if you want the devices to access the internet, the server (AP) must be connected to the router via an Ethernet shield or have a second WiFi module in client mode for uplink connection.