title: esp32自组网
ESP32自组网
通过plainlessmesh来完成esp32直接的自组网
参考了国外大神的文章
ESP-MESH with ESP32 and ESP8266: Getting Started | Random Nerd Tutorials
基本设置
#include "painlessMesh.h"
//库文件肯定要包含
//mesh组网
#define MESH_PREFIX "whateverYouLike"
//组网名字
#define MESH_PASSWORD "somethingSneaky"
//组网密码
#define MESH_PORT 5555
//组网端口
#define mesh_who 1
//1为接收端 0为发送端 方便后续开发
//初始化
// mesh.setDebugMsgTypes( ERROR | MESH_STATUS | CONNECTION | SYNC | COMMUNICATION | GENERAL | MSG_TYPES | REMOTE ); // all types on
mesh.setDebugMsgTypes(ERROR | STARTUP);
mesh.init(MESH_PREFIX, MESH_PASSWORD, &userScheduler, MESH_PORT);
直接使用的函数
发送函数
void meshSendMessage(String msg)
{
msg = "Hi from node";
msg += mesh.getNodeId();
mesh.sendBroadcast(msg);
}
发送并说明来自哪个节点
后续要采用回调函数去使用的函数
mesh.onReceive(&meshReceivedCallback);
mesh.onNewConnection(&meshNewConnectionCallback);
mesh.onChangedConnections(&meshChangedConnectionCallback);
mesh.onNodeTimeAdjusted(&nodeTimeAdjustedCallback);
为以下函数的回调
接受函数
void meshReceivedCallback(uint32_t from, String &msg)
{
Serial.printf("startHere: Received from %u msg=%s\n", from, msg.c_str());
}
接受
新的连接节点
void meshNewConnectionCallback(uint32_t nodeId)
{
Serial.printf("--> startHere: New Connection, nodeId = %u\n", nodeId);
}
更改连接
void meshChangedConnectionCallback()
{
Serial.printf("Changed connections\n");
}
调整节点时间
void nodeTimeAdjustedCallback(int32_t offset)
{
Serial.printf("Adjusted time %u. Offset = %d\n", mesh.getNodeTime(), offset);
}
总的示例
#include <你要的环境>
#include "painlessMesh.h"
painlessMesh mesh;
void meshSendMessage(String msg)
{
msg = "Hi from node";
msg += mesh.getNodeId();
mesh.sendBroadcast(msg);
}
void meshReceivedCallback(uint32_t from, String &msg)
{
Serial.printf("startHere: Received from %u msg=%s\n", from, msg.c_str());
}
void meshNewConnectionCallback(uint32_t nodeId)
{
Serial.printf("--> startHere: New Connection, nodeId = %u\n", nodeId);
}
void meshChangedConnectionCallback()
{
Serial.printf("Changed connections\n");
}
void nodeTimeAdjustedCallback(int32_t offset)
{
Serial.printf("Adjusted time %u. Offset = %d\n", mesh.getNodeTime(), offset);
}
void meshdo()
{
// mesh.setDebugMsgTypes( ERROR | MESH_STATUS | CONNECTION | SYNC | COMMUNICATION | GENERAL | MSG_TYPES | REMOTE ); // all types on
mesh.setDebugMsgTypes(ERROR | STARTUP);
mesh.init(MESH_PREFIX, MESH_PASSWORD, &userScheduler, MESH_PORT);
mesh.onReceive(&meshReceivedCallback);
mesh.onNewConnection(&meshNewConnectionCallback);
mesh.onChangedConnections(&meshChangedConnectionCallback);
mesh.onNodeTimeAdjusted(&nodeTimeAdjustedCallback);
}
void setup()
{
// 串口
Serial.begin(115200);
//mesh初始
meshdo();
}
void loop()
{
//组网
// if(!mesh_who)
// {
// meshSendMessage("hello???");
// }
mesh.update();
}