ESP-MESH Tutorial: Setup and Optimize Your ESP32 Mesh

Mesh networks are a powerful way to extend the range and reliability of wireless communication, especially in IoT applications where devices are spread across large areas. ESP-MESH is a protocol developed by Espressif that allows multiple ESP32 devices to form a mesh network, enabling them to communicate with each other and relay data seamlessly. This article will guide you through the process of setting up a mesh network using ESP-MESH on the ESP32, covering everything from architecture and setup to optimization and real-world applicationsArquitetura ESP32: SoC dual-core, subsistemas RF integradosArquitetura ESP32: SoC dual-core, subsistemas RF integradosDiscover the ESP32’s dual-core prowess and integrated RF subsystems for efficient, innovative IoT applications—from smart homes to industrial sensors..

Table of Contents🔗

What is ESP-MESH?🔗

ESP-MESH is a networking protocol built on top of the standard Wi-Fi stack that allows multiple ESP32 devicesPeer-to-Peer NFC Communication Between ESP32 DevicesPeer-to-Peer NFC Communication Between ESP32 DevicesDiscover how to set up NFC P2P communication on ESP32 devices. Our tutorial covers hardware, software integration, and practical security measures. to form a decentralized mesh network. Unlike traditional Wi-Fi networks, where all devices must connect to a central access point, ESP-MESH enables devices to communicate directly with each other, forming a self-organizing network. This makes it ideal for applications like smart homes, industrial automation, and large-scale sensor networks.

In an ESP-MESH network:

Understanding ESP-MESH Architecture🔗

ESP-MESH operates on Layer 2 (Data Link Layer), allowing nodes to communicate peer-to-peerUsing Wi-Fi Direct on ESP32 for Peer-to-Peer CommunicationUsing Wi-Fi Direct on ESP32 for Peer-to-Peer CommunicationLearn to set up Wi-Fi Direct on ESP32 for secure P2P IoT communication. Our tutorial offers practical guidance, real-world examples, and troubleshooting tips. without relying on a central router. Unlike traditional star topologies:

  • Self-Organizing: Nodes auto-join the network and find optimal paths.
  • Dynamic Routing: Data hops through intermediate nodes to reach the root.
  • Fault Tolerance: Failed nodes trigger automatic re-routing.

Key Components:

Advantages of Using ESP-MESH🔗

1. Extended RangeQuick Comparison: Range, power consumption, costs, and complexity of each technologyQuick Comparison: Range, power consumption, costs, and complexity of each technologyDiscover the ideal wireless solution for your ESP32 IoT project by analyzing range, power, cost, and complexity. Optimize connectivity now.: Devices can relay data through intermediate nodes, extending the network's reach beyond the range of a single Wi-Fi access pointSetting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips..

2. Self-Healing: If a node fails or is removed, the network automatically reconfigures itself to maintain connectivity.

3. Scalability: The network can grow dynamically as more nodes are added.

4. Decentralized: No single point of failure, making the network more robust.

Hardware Setup and Requirements🔗

What You’ll Need:

WiringUsing Quectel BC66/BG96 Modules with ESP32 for NB-IoT ConnectivityUsing Quectel BC66/BG96 Modules with ESP32 for NB-IoT ConnectivityExplore our detailed tutorial on integrating Quectel BC66/BG96 with ESP32 for low-power, reliable NB-IoT connectivity. Learn hardware setup and AT commands.:

No special wiringUsing Quectel BC66/BG96 Modules with ESP32 for NB-IoT ConnectivityUsing Quectel BC66/BG96 Modules with ESP32 for NB-IoT ConnectivityExplore our detailed tutorial on integrating Quectel BC66/BG96 with ESP32 for low-power, reliable NB-IoT connectivity. Learn hardware setup and AT commands.-communication is wireless. Ensure antennas are unobstructed.

Setting Up ESP-MESH🔗

To set up an ESP-MESH network, you’ll need the following:

Step 1: Install ESP-IDF

If you haven’t already, install the ESP-IDFZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsSecure your IoT network with OTA firmware upgrades using an ESP32 coordinator. Our guide details firmware setup, packaging, security, and troubleshooting. by following the official guide.

Step 2: Include ESP-MESH in Your Project

ESP-MESH is part of the ESP-IDFZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsSecure your IoT network with OTA firmware upgrades using an ESP32 coordinator. Our guide details firmware setup, packaging, security, and troubleshooting., so you can include it in your project by adding the following header:

#include "esp_mesh.h"

Step 3: Initialize ESP-MESH

Initialize the ESP-MESH stack in your app_main() function:

void app_main() {
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    // Initialize Wi-Fi
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_start());
    // Initialize ESP-MESH
    ESP_ERROR_CHECK(esp_mesh_init());
}

Configuring Nodes and Root Node🔗

In an ESP-MESH network, one device must act as the root node, while the others act as nodes. The root node is responsible for connecting the mesh network to an external network.

Configuring the Root Node

The root node connects to an external Wi-Fi networkConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. and routes data to and from the mesh network. Here’s how to configure it:

// Set the root node configuration
mesh_cfg_t cfg = {
    .channel = 6, // Wi-Fi channel
    .router.ssid = "your_wifi_ssid",
    .router.password = "your_wifi_password",
    .mesh_id = "my_mesh_network",
    .allow_root_conflicts = true,
};
// Set the root node
ESP_ERROR_CHECK(esp_mesh_set_config(&cfg));
ESP_ERROR_CHECK(esp_mesh_set_type(MESH_ROOT));
ESP_ERROR_CHECK(esp_mesh_start());

Configuring Nodes

Nodes connect to the root node or other nodes to form the mesh network:

mesh_cfg_t cfg = {
    .channel = 6,
    .mesh_id = "my_mesh_network",
};
ESP_ERROR_CHECK(esp_mesh_set_config(&cfg));
ESP_ERROR_CHECK(esp_mesh_set_type(MESH_NODE));
ESP_ERROR_CHECK(esp_mesh_start());

Data Routing and Self-Healing🔗

ESP-MESH automatically handles data routing and self-healing. If a node goes offline, the network reorganizes itself to ensure data can still reach its destination. This is done through parent-child relationships, where each node selects the best parent to route data through.

Network Management and Topology Optimization🔗

Event Handling:

Event TypeDescription
MESH_EVENT_PARENT_CONNECTEDNode joins the network.
MESH_EVENT_CHILD_CONNECTEDNew child node connected.
MESH_EVENT_ROUTING_TABLE_ADDUpdated routing path.

Optimization Tips:

  • Limit network depth to 5 layers to reduce latency.
  • Use esp_mesh_set_max_layer() to control layer count.
  • Prioritize high-traffic nodes closer to the root.

Security in ESP-MESH Networks🔗

Pre-Shared Key (PSK) Authentication:

mesh_cfg_t cfg = MESH_INIT_CONFIG_DEFAULT();
cfg.crypto_funcs = &g_wifi_default_mesh_crypto_funcs;
esp_mesh_set_ie_crypto_funcs(&cfg.crypto_funcs);
esp_mesh_set_security_id(psk_id, true); // Rotate keys periodically

Best PracticesZigbee Green Power: Ultra-Low-Power Energy Harvesting SolutionsZigbee Green Power: Ultra-Low-Power Energy Harvesting SolutionsDiscover how ZGP enables battery-free IoT devices through energy harvesting with ESP32 integrations, supporting smart home and industrial applications.:

Power Consumption and Data Routing Optimization🔗

Strategies:

esp_deep_sleep(30 * 1000000); // Sleep 30 seconds
  • Packet Aggregation: Combine sensor readings into single payloads.
  • Routing Tables: Cache frequently used paths to reduce discovery overhead.

Practical Example: Building a Mesh Network🔗

Let’s build a simple mesh network where nodes send temperature data to the root node, which then forwards it to a server.

Node Code

void send_temperature_data() {
    float temperature = read_temperature_sensor();
    mesh_data_t data;
    data.proto = MESH_PROTO_BIN;
    data.size = sizeof(temperature);
    data.data = (uint8_t *)&temperature;
    esp_mesh_send(NULL, &data, MESH_DATA_P2P, NULL, 0);
}
void app_main() {
    // Initialize ESP-MESH and Wi-Fi
    // ...
    while (1) {
        send_temperature_data();
        vTaskDelay(pdMS_TO_TICKS(5000)); // Send data every 5 seconds
    }
}

Root Node Code

void receive_data_cb(mesh_addr_t *from, mesh_data_t *data) {
    float temperature = *(float *)data->data;
    printf("Received temperature: %.2f\n", temperature);
    // Forward data to the server
}
void app_main() {
    // Initialize ESP-MESH and Wi-Fi
    // ...
    esp_mesh_set_recv_cb(receive_data_cb);
    while (1) {
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

Real-World Example: Smart Building Monitoring🔗

Scenario: Temperature/Humidity sensors across 10 floors.

1. Root Node: Connected to building’s Wi-Fi, forwards data to AWS IoTConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies..

2. Layer 1 Nodes: Placed every 200 meters (ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips. with external antennas).

3. Leaf Nodes: Battery-powered sensors using deep sleepLTE Power Saving: Combining PSM and DRX with ESP32 Sleep ModesLTE Power Saving: Combining PSM and DRX with ESP32 Sleep ModesDiscover how combining LTE power-saving modes with ESP32 sleep techniques can extend battery life in IoT devices while ensuring reliable connectivity..

Data Flow:

Sensor -> Leaf Node -> Layer 3 Node -> Layer 1 Node -> Root -> Cloud

Throughput: Achieves 50 packets/sec with < 100ms latency.

Troubleshooting ESP-MESH🔗

1. Node Fails to Connect:

2. High Packet LossZigbee Network Diagnostics: Resolving Packet Loss and InterferenceZigbee Network Diagnostics: Resolving Packet Loss and InterferenceDiscover effective methods to diagnose and resolve packet loss and interference in Zigbee networks using ESP32, ensuring reliable IoT connectivity.:

3. Root Node Overload:

  • Add redundant root nodes.
  • Enable QoS with esp_mesh_set_xon_qsize().
// Debugging topology
mesh_addr_t parent_addr;
esp_mesh_get_parent_bssid(&parent_addr);
ESP_LOGI("TAG", "Parent BSSID: " MACSTR, MAC2STR(parent_addr.addr));

Conclusion & Next Steps🔗

ESP-MESH provides a versatile framework for turning ESP32 devices into a robust network of interconnected nodes, perfect for scenarios where traditional Wi-Fi might fall short. By diving into hands-on setup, practical code examples, and thoughtful optimization, you’re well on your way to creating scalable IoT solutionsConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. that can adapt to real-world challenges.

Experiment with these setups in your projects, and monitor how the network behaves under different conditions. The more you tweak and test, the more resilient and efficient your mesh network will become.

Happy meshing!

Author: Marcelo V. Souza - Engenheiro de Sistemas e Entusiasta em IoT e Desenvolvimento de Software, com foco em inovação tecnológica.

References🔗

Share article

Related Articles