Creating a mesh network with ESP32 devices can be a complex task, as it requires setting up each device to both send and receive data to/from its peers. For a mesh network on the ESP32, you might use the painlessMesh library, which simplifies the process of creating a mesh network.
Below is a simple example of how to initialize a mesh network on an ESP32 using the painlessMesh library. This example assumes that you have the painlessMesh library installed in your Arduino IDE.
- First, install the painlessMesh library using the Library Manager in the Arduino IDE.
- Next, create a new sketch in the Arduino IDE and input the following code:
#include <painlessMesh.h>
#define MESH_PREFIX "meshNetwork"
#define MESH_PASSWORD "meshPassword"
#define MESH_PORT 5555
painlessMesh mesh;
void setup() {
Serial.begin(115200);
mesh.setDebugMsgTypes(ERROR | STARTUP | CONNECTION); // Set log type
mesh.init(MESH_PREFIX, MESH_PASSWORD, MESH_PORT);
mesh.onReceive(&receivedCallback);
mesh.onNewConnection(&newConnectionCallback);
mesh.onChangedConnections(&changedConnectionCallback);
mesh.onNodeTimeAdjusted(&nodeTimeAdjustedCallback);
}
void loop() {
mesh.update();
}
void receivedCallback(uint32_t from, String &msg) {
Serial.printf("Received from %u msg=%s\n", from, msg.c_str());
}
void newConnectionCallback(uint32_t nodeId) {
Serial.printf("New Connection, nodeId = %u\n", nodeId);
}
void changedConnectionCallback() {
Serial.printf("Changed connections\n");
}
void nodeTimeAdjustedCallback(int32_t offset) {
Serial.printf("Adjusted time %u. Offset = %d\n", mesh.getNodeTime(), offset);
}
This code sets up your ESP32 to join a mesh network with the specified prefix and password. The onReceive callback function is called when this node receives a message from another node. The onNewConnection callback is called when a new node joins the network, and the onChangedConnections callback is triggered when the network topology changes.
To create a full mesh network, load this same code onto multiple ESP32 devices, making sure they are all within range of each other. Once powered, they will automatically create a mesh network and be able to pass messages between them.
Remember to replace MESH_PREFIX and `MESH_PASSWORD