How to Connect Two ESP8266s via WiFi: A Complete Guide

Establishing wireless communication between microcontrollers opens up enormous possibilities for home automation, allowing data exchange without unnecessary wires. When the need arises to connect two modules ESP8266 When connecting devices into a single network, the developer faces a choice of architecture: a classic router-based design or a direct connection between devices. Understanding these processes is critical for the stable operation of IoT projects.

In this guide, we'll cover basic interaction scenarios where one device acts as a server or access point, and the other as a client. Exchange of data packets Communication can occur via TCP or UDP sockets, providing flexibility depending on your project's requirements for speed and reliability of data delivery. It's important to determine the network topology from the outset, as this determines the choice of software code and parameter settings.

We'll cover not only the theoretical aspects but also practical implementation using the popular Arduino IDE. You'll learn how to configure static IP addresses, avoid conflicts on a local network, and properly handle interrupts. Direct ESP-to-ESP connection in SoftAP+Station mode requires precise tuning of WiFi channels to avoid packet loss. This knowledge will allow you to create autonomous systems that do not depend on the Internet or an external router.

Selecting network architecture and operating modes

Before you begin programming, you need to clearly define how exactly your devices will interact with each other. There are several proven designs, each with its own advantages and limitations in terms of range and power consumption. Choosing the right topology is the foundation upon which all subsequent system logic is built.

The most common option is to use an external router to which both modules are connected. In this case, both devices operate in standby mode. Station (STA), receiving IP addresses from the router's DHCP server. This simplifies setup, as it eliminates the need to write complex code to manage network interfaces, but it makes the system dependent on the existing infrastructure.

If there is no router or autonomy is required, one device switches to access point mode Access Point (AP), creating its own network. The second device connects to this network as a client. This approach is ideal for paired devices, such as a remote control and an actuator. However, it's worth remembering that in AP mode, the module consumes more power.

📊 What network mode are you planning to use?
Via router (both STA)
Direct connection (AP + STA)
Mesh network
I don't know, I choose randomly

There is also a more complex but powerful simultaneous mode AP+STAIn this scenario, the module can simultaneously distribute WiFi and connect to another network. This allows, for example, data to be transmitted to the cloud via one interface while remaining accessible for local configuration via another. This flexibility is often required in industrial controllers.

Necessary equipment and environment preparation

To implement the project, you will need a minimal set of components that can be easily found in any electronics store. The basis will be two modules NodeMCU or Wemos D1 Mini, which already have a built-in antenna and programming interface. You'll also need two USB cables for power and code upload.

It's critical to ensure stable power for both devices, especially if they will be transmitting data via WiFi. At peak loads, current consumption can reach 300-500 mA, exceeding the capacity of a standard computer USB port when connecting multiple devices through a hub without additional power. Use high-quality cables and, if necessary, external 5V power sources.

☑️ Project readiness check

Completed: 0 / 5

The software requires installing support for ESP8266 boards in the Arduino IDE. This is done through the Additional URLs settings menu in the Boards Manager. After installation, select the correct board model in the menu. Toolsto ensure the compiler uses the appropriate memory and pin settings. Incorrect board selection may result in the firmware failing to load.

⚠️ Important: When connecting both modules to the same computer, make sure they detect different COM ports. If the ports conflict or are not detected, try connecting the devices one at a time for initial setup or use different USB hubs.

Scenario 1: Both modules are connected to the router

This option is the most stable and easiest to debug, as all devices are on the same local network managed by a router. Both modules act as clients (Station) and obtain IP addresses automatically. To communicate with them, you only need to know the IP address of the receiving device.

In the code of the first module (Server), you need to initialize the WiFi connection and start the server on a specific port, for example, 80 or 8080. Server will wait for incoming connections and process received data. The second module (Client) will initiate the connection by connecting to the server's IP address.

To implement the server part, a library is used WiFiServer. In the cycle loop The program checks for connected clients using the method available()If the client has connected, the server reads the data and can respond with an acknowledgement. This is the classic request-response model.

WiFiServer server(80);

void setup() {

WiFi.begin("SSID", "PASSWORD");

while (WiFi.status() != WL_CONNECTED) {

delay(500);

}

server.begin();

}

The client side works differently: it actively tries to establish a connection. The class used is WiFiClientIt is important to provide a mechanism for retrying connections if the server is temporarily unavailable. Timeouts Connections must be configured correctly so that the system does not "hang" while waiting for a response.

Scenario 2: Direct Connection (AP and Station)

When an external router is unavailable, one of the ESP8266 modules takes over as an access point. This mode is called SoftAPThe device creates a network with a specified name (SSID) and password, to which the second module connects. This creates an isolated local network between the two devices.

In this scenario, it's important to configure IP addresses correctly, as the default DHCP server may not exist or may be unstable. It's recommended to set a static IP for the access point (e.g., 192.168.4.1) and a static IP for the client (e.g., 192.168.4.2). This ensures that the devices "see" each other immediately after connecting.

The code for AP mode differs in initialization. Instead of WiFi.begin() is used WiFi.softAP()Once the network is created, you can launch the server in the same way as in the previous scenario. The only difference is that now the network is created by the microcontroller itself, not by external hardware.

Parameter Station Mode (Client) SoftAP (Point) mode AP+STA mode
Function WiFi.begin() WiFi.softAP() Both at once
IP address Receives from the router Set manually (gateway) Two different addresses
Energy consumption Low/Medium High Maximum
Range Depends on the router Limited by module Limited by module

When implementing a direct connection, it is worth considering that the module in AP mode may heat up more than usual. Heat sink This becomes an important factor if the devices are located in a closed case. Also, the range of such a network is usually shorter than that of a full-fledged router.

Data exchange and TCP/UDP protocols

Once a physical connection is established, logical information exchange begins. The choice of protocol depends on the tasks: TCP guarantees the delivery of packets and their correct sequence, which is critical for control commands. UDP It works faster, but does not guarantee delivery, which is suitable for streaming telemetry, where the loss of a single frame is not a problem.

When working with TCP, it's important to handle connection interruptions correctly. If the client disconnects abruptly, the server may continue to consider the connection active until a timeout occurs. It's necessary to implement a heartbeat mechanism or regularly check the socket status using the [unclear] method. client.connected().

Features of data buffering

Frequent sending of small data packets can overload the network with overhead. It's recommended to accumulate data in a buffer and send it in larger packets, or use Nagle's algorithm if the library supports this parameter.

The following methods are used to send data: print() or write()The difference is that print() converts data to a string, and write() Sends bytes as is. For binary protocols or transmitting raw data from sensors, it is preferable. write(), as this saves processor resources.

⚠️ Caution: Don't send data too frequently. The ESP8266 WiFi stack requires time to process interrupts. If the loop loop If the process runs too quickly without any delays, the device may lose its WiFi connection or reboot. Add yield() or minor delays delay() in cycles of intensive transmission.

Debugging and troubleshooting common errors

When debugging wireless connections, you often encounter problems that aren't immediately obvious. The most common error is an inability to connect to the network. This can be caused by an incorrect password, a weak signal, or incompatible security standards (WPA2/WPA3). Always check the logs using Serial Monitor.

Another common problem is device freezing. This is often caused by a stack overflow or watchdog timer. If your code performs lengthy calculations or waits for a network response without calling yield(), the system may consider the module frozen and reboot it. Code optimization and breaking up long operations into smaller chunks solve this problem.

For in-depth diagnostics, use the built-in WiFi debugging features. Method WiFi.status() Returns the current connection status, allowing you to understand at what stage the failure occurs. Analyzing return codes helps quickly isolate the problem, whether it's an authentication error or a network outage.

It's also worth paying attention to interference in the airwaves. If there are many WiFi networks or microwave ovens nearby, the channel may be heavily polluted. In such cases, manually changing the WiFi channel in the access point settings or using less crowded frequencies can help.

Frequently Asked Questions (FAQ)

Is it possible to connect more than two ESP8266 modules into one network?

Yes, this is possible. In router mode, up to 4-5 clients can connect to the network simultaneously. In SoftAP mode, one module can serve up to 4 connected devices, but network performance is reduced. For larger networks, it's better to use external infrastructure or protocols like MQTT.

What is the maximum communication range between two ESP8266?

Indoors with obstacles (walls, furniture), the range is approximately 20-40 meters. In open spaces with a clear line of sight, modules with an external antenna can maintain communication at a distance of up to 100-200 meters. Using directional antennas can significantly increase this range.

Is internet required for the ESP-to-ESP connection to work?

No, internet access is not required. The devices communicate via a local area network (LAN). Even if you use a router, it's enough for it to simply assign IP addresses; WAN access is not required for data transfer between the modules.

Why does ESP8266 frequently disconnect from WiFi?

Common causes include unstable power supply (insufficient current), weak signal, overheating, or software errors (interrupt blocking). Check the power supply, add delays to the code, and ensure the device isn't overheating.