JsonUdpBeacon.ino 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Send a JSON object on UDP at regular interval
  2. //
  3. // You can easily test this program with netcat:
  4. // $ nc -ulp 8888
  5. //
  6. // by Benoit Blanchon, MIT License 2015-2017
  7. #include <ArduinoJson.h>
  8. #include <Ethernet.h>
  9. #include <SPI.h>
  10. byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  11. IPAddress localIp(192, 168, 0, 177);
  12. IPAddress remoteIp(192, 168, 0, 109);
  13. unsigned int remotePort = 8888;
  14. unsigned localPort = 8888;
  15. EthernetUDP udp;
  16. JsonObject& buildJson(JsonBuffer& jsonBuffer) {
  17. JsonObject& root = jsonBuffer.createObject();
  18. JsonArray& analogValues = root.createNestedArray("analog");
  19. for (int pin = 0; pin < 6; pin++) {
  20. int value = analogRead(pin);
  21. analogValues.add(value);
  22. }
  23. JsonArray& digitalValues = root.createNestedArray("digital");
  24. for (int pin = 0; pin < 14; pin++) {
  25. int value = digitalRead(pin);
  26. digitalValues.add(value);
  27. }
  28. return root;
  29. }
  30. void sendJson(JsonObject& json) {
  31. udp.beginPacket(remoteIp, remotePort);
  32. json.printTo(udp);
  33. udp.println();
  34. udp.endPacket();
  35. }
  36. void setup() {
  37. Ethernet.begin(mac, localIp);
  38. udp.begin(localPort);
  39. }
  40. void loop() {
  41. delay(1000);
  42. // Use https://bblanchon.github.io/ArduinoJson/assistant/ to
  43. // compute the right size for the buffer
  44. StaticJsonBuffer<300> jsonBuffer;
  45. JsonObject& json = buildJson(jsonBuffer);
  46. sendJson(json);
  47. }