JsonServer.ino 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. #include <ArduinoJson.h>
  5. #include <Ethernet.h>
  6. #include <SPI.h>
  7. byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  8. IPAddress ip(192, 168, 0, 177);
  9. EthernetServer server(80);
  10. bool readRequest(EthernetClient& client) {
  11. bool currentLineIsBlank = true;
  12. while (client.connected()) {
  13. if (client.available()) {
  14. char c = client.read();
  15. if (c == '\n' && currentLineIsBlank) {
  16. return true;
  17. } else if (c == '\n') {
  18. currentLineIsBlank = true;
  19. } else if (c != '\r') {
  20. currentLineIsBlank = false;
  21. }
  22. }
  23. }
  24. return false;
  25. }
  26. JsonObject& prepareResponse(JsonBuffer& jsonBuffer) {
  27. JsonObject& root = jsonBuffer.createObject();
  28. JsonArray& analogValues = root.createNestedArray("analog");
  29. for (int pin = 0; pin < 6; pin++) {
  30. int value = analogRead(pin);
  31. analogValues.add(value);
  32. }
  33. JsonArray& digitalValues = root.createNestedArray("digital");
  34. for (int pin = 0; pin < 14; pin++) {
  35. int value = digitalRead(pin);
  36. digitalValues.add(value);
  37. }
  38. return root;
  39. }
  40. void writeResponse(EthernetClient& client, JsonObject& json) {
  41. client.println("HTTP/1.1 200 OK");
  42. client.println("Content-Type: application/json");
  43. client.println("Connection: close");
  44. client.println();
  45. json.prettyPrintTo(client);
  46. }
  47. void setup() {
  48. Ethernet.begin(mac, ip);
  49. server.begin();
  50. }
  51. void loop() {
  52. EthernetClient client = server.available();
  53. if (client) {
  54. bool success = readRequest(client);
  55. if (success) {
  56. // Use https://bblanchon.github.io/ArduinoJson/assistant/ to
  57. // compute the right size for the buffer
  58. StaticJsonBuffer<500> jsonBuffer;
  59. JsonObject& json = prepareResponse(jsonBuffer);
  60. writeResponse(client, json);
  61. }
  62. delay(1);
  63. client.stop();
  64. }
  65. }