Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <painlessMesh.h>
- #define MESH_PREFIX "yourMeshNetwork"
- #define MESH_PASSWORD "yourMeshPassword"
- #define MESH_PORT 5555
- #define LED_PIN 2 // Pin untuk LED indikator
- Scheduler userScheduler; // to control your personal task
- painlessMesh mesh;
- uint32_t lastSendTime = 0;
- uint32_t sendInterval = 5000; // Kirim data setiap 5 detik
- 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");
- if (mesh.getNodeList().size() == 0) {
- digitalWrite(LED_PIN, LOW); // Matikan LED jika tidak ada koneksi
- } else {
- digitalWrite(LED_PIN, HIGH); // Nyalakan LED jika ada koneksi
- }
- }
- void nodeTimeAdjustedCallback(int32_t offset) {
- Serial.printf("Adjusted time %u. Offset = %d\n", mesh.getNodeTime(), offset);
- }
- void sendRandomData() {
- uint32_t now = millis();
- if (now - lastSendTime >= sendInterval) {
- lastSendTime = now;
- if (mesh.getNodeList().size() > 0) {
- uint32_t randomData = random(100);
- String message = "Random Data: " + String(randomData);
- mesh.sendBroadcast(message);
- Serial.println("Sent: " + message);
- } else {
- Serial.println("Not connected to the mesh network");
- }
- }
- }
- void setup() {
- Serial.begin(115200);
- pinMode(LED_PIN, OUTPUT);
- digitalWrite(LED_PIN, LOW); // Mematikan LED pada awalnya
- mesh.setDebugMsgTypes(ERROR | STARTUP);
- mesh.init(MESH_PREFIX, MESH_PASSWORD, &userScheduler, MESH_PORT);
- mesh.onReceive(&receivedCallback);
- mesh.onNewConnection(&newConnectionCallback);
- mesh.onChangedConnections(&changedConnectionCallback);
- mesh.onNodeTimeAdjusted(&nodeTimeAdjustedCallback);
- Task sendRandomDataTask(1000, TASK_FOREVER, &sendRandomData); // Buat objek Task
- userScheduler.addTask(sendRandomDataTask); // Tambahkan objek Task ke scheduler
- sendRandomDataTask.enable(); // Aktifkan objek Task
- }
- void loop() {
- mesh.update();
- userScheduler.execute(); // Jalankan scheduler
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement