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-2016
|
---|
7 |
|
---|
8 | #include <SPI.h>
|
---|
9 | #include <Ethernet.h>
|
---|
10 | #include <ArduinoJson.h>
|
---|
11 |
|
---|
12 | byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
|
---|
13 | IPAddress localIp(192, 168, 0, 177);
|
---|
14 | IPAddress remoteIp(192, 168, 0, 109);
|
---|
15 | unsigned int remotePort = 8888;
|
---|
16 | unsigned localPort = 8888;
|
---|
17 | EthernetUDP udp;
|
---|
18 |
|
---|
19 | JsonObject& buildJson(JsonBuffer& jsonBuffer) {
|
---|
20 | JsonObject& root = jsonBuffer.createObject();
|
---|
21 |
|
---|
22 | JsonArray& analogValues = root.createNestedArray("analog");
|
---|
23 | for (int pin = 0; pin < 6; pin++) {
|
---|
24 | int value = analogRead(pin);
|
---|
25 | analogValues.add(value);
|
---|
26 | }
|
---|
27 |
|
---|
28 | JsonArray& digitalValues = root.createNestedArray("digital");
|
---|
29 | for (int pin = 0; pin < 14; pin++) {
|
---|
30 | int value = digitalRead(pin);
|
---|
31 | digitalValues.add(value);
|
---|
32 | }
|
---|
33 |
|
---|
34 | return root;
|
---|
35 | }
|
---|
36 |
|
---|
37 | void sendJson(JsonObject& json) {
|
---|
38 | udp.beginPacket(remoteIp, remotePort);
|
---|
39 | json.printTo(udp);
|
---|
40 | udp.println();
|
---|
41 | udp.endPacket();
|
---|
42 | }
|
---|
43 |
|
---|
44 | void setup() {
|
---|
45 | Ethernet.begin(mac, localIp);
|
---|
46 | udp.begin(localPort);
|
---|
47 | }
|
---|
48 |
|
---|
49 | void loop() {
|
---|
50 | delay(1000);
|
---|
51 |
|
---|
52 | StaticJsonBuffer<300> jsonBuffer;
|
---|
53 | JsonObject& json = buildJson(jsonBuffer);
|
---|
54 | sendJson(json);
|
---|
55 | }
|
---|