Example Codes
Sender Node
Below is an example code of a node which broadcasts a message to every other node in the mesh network every 10 seconds. A sender node usually behaves as child nodes.
#include <painlessMesh.h>
// Mesh network parameters
#define MESH_PREFIX "yourMeshNetwork"
#define MESH_PASSWORD "yourMeshPassword"
#define MESH_PORT 5555
painlessMesh mesh;
// FreeRTOS Task Handle for mesh updates
TaskHandle_t meshUpdateTaskHandle;
// Function to handle received messages
void receivedCallback(uint32_t from, String &msg) {
Serial.printf("Received message from node %u: %s\n", from, msg.c_str());
}
// Task to continuously update the mesh network
void meshUpdateTask(void *pvParameters) {
while (true) {
mesh.update();
vTaskDelay(10 / portTICK_PERIOD_MS); // Short delay to yield to other tasks
}
}
void setup() {
Serial.begin(115200);
// Initialize mesh network
mesh.setDebugMsgTypes(ERROR | STARTUP | CONNECTION); // Debug message types
mesh.init(MESH_PREFIX, MESH_PASSWORD, MESH_PORT);
mesh.onReceive(&receivedCallback); // Register the message receive callback
// Create FreeRTOS task for updating mesh
xTaskCreate(
meshUpdateTask, // Function to implement the task
"MeshUpdateTask", // Task name
8192, // Stack size
NULL, // Task input parameter
1, // Priority
&meshUpdateTaskHandle // Task handle
);
}
void loop() {
}
Receiver Node
Below is an example code of a node which receives messages from every other node in the mesh network that are within range. A receiver node usually behaves as parent nodes.
#include <painlessMesh.h>
// Mesh network parameters
#define MESH_PREFIX "yourMeshNetwork"
#define MESH_PASSWORD "yourMeshPassword"
#define MESH_PORT 5555
painlessMesh mesh;
// FreeRTOS Task Handle for mesh updates
TaskHandle_t meshUpdateTaskHandle;
// Function to handle received messages
void receivedCallback(uint32_t from, String &msg) {
Serial.printf("Received message from node %u: %s\n", from, msg.c_str());
}
// Task to continuously update the mesh network
void meshUpdateTask(void *pvParameters) {
while (true) {
mesh.update();
vTaskDelay(10 / portTICK_PERIOD_MS); // Short delay to yield to other tasks
}
}
void setup() {
Serial.begin(115200);
// Initialize mesh network
mesh.setDebugMsgTypes(ERROR | STARTUP | CONNECTION); // Debug message types
mesh.init(MESH_PREFIX, MESH_PASSWORD, MESH_PORT);
mesh.onReceive(&receivedCallback); // Register the message receive callback
// Create FreeRTOS task for updating mesh
xTaskCreate(
meshUpdateTask, // Function to implement the task
"MeshUpdateTask", // Task name
8192, // Stack size
NULL, // Task input parameter
1, // Priority
&meshUpdateTaskHandle // Task handle
);
}
void loop() {
}