Advertisement
mudhita_triari

Tugas Akhir - ESP32 Node Mesh

May 23rd, 2024
871
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.18 KB | Source Code | 0 0
  1. #include <painlessMesh.h>
  2.  
  3. #define MESH_PREFIX     "yourMeshNetwork"
  4. #define MESH_PASSWORD   "yourMeshPassword"
  5. #define MESH_PORT       5555
  6.  
  7. #define LED_PIN 2 // Pin untuk LED indikator
  8.  
  9. Scheduler userScheduler; // to control your personal task
  10. painlessMesh mesh;
  11.  
  12. uint32_t lastSendTime = 0;
  13. uint32_t sendInterval = 5000; // Kirim data setiap 5 detik
  14.  
  15. void receivedCallback(uint32_t from, String &msg) {
  16.   Serial.printf("Received from %u msg=%s\n", from, msg.c_str());
  17. }
  18.  
  19. void newConnectionCallback(uint32_t nodeId) {
  20.   Serial.printf("--> New Connection, nodeId = %u\n", nodeId);
  21. }
  22.  
  23. void changedConnectionCallback() {
  24.   Serial.printf("Changed connections\n");
  25.   if (mesh.getNodeList().size() == 0) {
  26.     digitalWrite(LED_PIN, LOW);     // Matikan LED jika tidak ada koneksi
  27.   } else {
  28.     digitalWrite(LED_PIN, HIGH);    // Nyalakan LED jika ada koneksi
  29.   }
  30. }
  31.  
  32. void nodeTimeAdjustedCallback(int32_t offset) {
  33.   Serial.printf("Adjusted time %u. Offset = %d\n", mesh.getNodeTime(), offset);
  34. }
  35.  
  36. void sendRandomData() {
  37.   uint32_t now = millis();
  38.   if (now - lastSendTime >= sendInterval) {
  39.     lastSendTime = now;
  40.     if (mesh.getNodeList().size() > 0) {
  41.       uint32_t randomData = random(100);
  42.       String message = "Random Data: " + String(randomData);
  43.       mesh.sendBroadcast(message);
  44.       Serial.println("Sent: " + message);
  45.     } else {
  46.       Serial.println("Not connected to the mesh network");
  47.     }
  48.   }
  49. }
  50.  
  51.  
  52. void setup() {
  53.   Serial.begin(115200);
  54.  
  55.   pinMode(LED_PIN, OUTPUT);
  56.   digitalWrite(LED_PIN, LOW); // Mematikan LED pada awalnya
  57.  
  58.   mesh.setDebugMsgTypes(ERROR | STARTUP);
  59.   mesh.init(MESH_PREFIX, MESH_PASSWORD, &userScheduler, MESH_PORT);
  60.   mesh.onReceive(&receivedCallback);
  61.   mesh.onNewConnection(&newConnectionCallback);
  62.   mesh.onChangedConnections(&changedConnectionCallback);
  63.   mesh.onNodeTimeAdjusted(&nodeTimeAdjustedCallback);
  64.  
  65.   Task sendRandomDataTask(1000, TASK_FOREVER, &sendRandomData); // Buat objek Task
  66.   userScheduler.addTask(sendRandomDataTask); // Tambahkan objek Task ke scheduler
  67.   sendRandomDataTask.enable(); // Aktifkan objek Task
  68. }
  69.  
  70. void loop() {
  71.   mesh.update();
  72.   userScheduler.execute(); // Jalankan scheduler
  73. }
  74.  
Tags: #esp32
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement