8000 Added an example with EthernetServer · littlestrange/ArduinoJson@e2016cf · GitHub
[go: up one dir, main page]

Skip to content

Commit e2016cf

Browse files
committed
Added an example with EthernetServer
1 parent 1b214a6 commit e2016cf

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

examples/JsonServer/JsonServer.ino

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// Sample Arduino Json Web Server
2+
// Created by Benoit Blanchon.
3+
// Heavily inspired by "Web Server" from David A. Mellis and Tom Igoe
4+
5+
#include <SPI.h>
6+
#include <Ethernet.h>
7+
#include <ArduinoJson.h>
8+
9+
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
10+
IPAddress ip(192, 168, 0, 177);
11+
EthernetServer server(80);
12+
13+
bool readRequest(EthernetClient& client) {
14+
bool currentLineIsBlank = true;
15+
while (client.connected()) {
16+
if (client.available()) {
17+
char c = client.read();
18+
if (c == '\n' && currentLineIsBlank) {
19+
return true;
20+
} else if (c == '\n') {
21+
currentLineIsBlank = true;
22+
} else if (c != '\r') {
23+
currentLineIsBlank = false;
24+
}
25+
}
26+
}
27+
return false;
28+
}
29+
30+
JsonObject& prepareResponse(JsonBuffer& jsonBuffer) {
31+
JsonObject& root = jsonBuffer.createObject();
32+
33+
JsonArray& analogValues = root.createNestedArray("analog");
34+
for (int pin = 0; pin < 6; pin++) {
35+
int value = analogRead(pin);
36+
analogValues.add(value);
37+
}
38+
39+
JsonArray& digitalValues = root.createNestedArray("digital");
40+
for (int pin = 0; pin < 14; pin++) {
41+
int value = digitalRead(pin);
42+
digitalValues.add(value);
43+
}
44+
45+
return root;
46+
}
47+
48+
void writeResponse(EthernetClient& client, JsonObject& json) {
49+
client.println("HTTP/1.1 200 OK");
50+
client.println("Content-Type: application/json");
51+
client.println("Connection: close");
52+
client.println();
53+
54+
json.prettyPrintTo(client);
55+
}
56+
57+
void setup() {
58+
Ethernet.begin(mac, ip);
59+
server.begin();
60+
}
61+
62+
void loop() {
63+
EthernetClient client = server.available();
64+
if (client) {
65+
bool success = readRequest(client);
66+
if (success) {
67+
StaticJsonBuffer<500> jsonBuffer;
68+
JsonObject& json = prepareResponse(jsonBuffer);
69+
writeResponse(client, json);
70+
}
71+
delay(1);
72+
client.stop();
73+
}
74+
}

0 commit comments

Comments
 (0)
0