Selasa, 12 April 2016

Arduino Aquaponics JSON

**UPDATE**
To see JSON, have a look at the Pump Controller project.

In a previous post, Online Relay Control, we demonstrated how to manually trigger a relay from a web application.  The Arduino polled App Engine on a set interval and received the status of the relay as a string; the Arduino sketch parsed the response and then analyzed the response using "if" conditionals.

While that works well for setups involving a single relay, we realize it is inherently limiting, particularly for those who want to control two relays with their Environment DAQ.  Similarly, we wanted to pair the Depth Sensor with two pumps that could be controlled independently and we needed a method of differentiating them with data from a single response.  Enter JSON.

To parse the JSON, you need aJson Library made by Marcus Nowotny.  Download, extract it and put a copy in your libraries folder.  Name the it aJSON.

The Arduino sketch below receives the following response for a GET request:

{RELAY1: ON}

and then toggles the relay.




digitalWrite(relayPin, HIGH); // Start serial Serial.begin(9600); // Start Ethernet Ethernet.begin(mac); delay(1000); // Assign the pin mode pinMode(relayPin, OUTPUT); Serial.println("Setup complete"); } void loop() { // Calls the GAE function and passes the complete link. GAE(webapp + "adacs/getUpdate"); delay(30000); } void GAE(String link) { httpRequest(link); delay(5000); boolean currentLinkIsBlank = true; String readString = ""; char newString[100]; while (client.connected()) { if (client.available()) { char c = client.read(); // Serial.write(c); // Optional - for dev mode if (c == && currentLineIsBlank) { Serial.println("Reached end of request."); while(client.connected()) { char f = client.read(); readString += f; } } if (c == ) { currentLineIsBlank = true; } else if (c != ) { currentLineIsBlank = false; } } } client.stop(); // The input for the JSON part requires a character array rather than a String readString.toCharArray(newString, 100); // Begin JSON section. // Parse the character array into an aJsonObject aJsonObject* jsonObject = aJson.parse(newString); // Grab the particular JSON key you want. // This example only has one key aJsonObject* relayState = aJson.getObjectItem(jsonObject, RELAY1); String relayStateString = relayState->valuestring; if (relayStateString == "ON") { digitalWrite(relayPin, LOW); } else { digitalWrite(relayPin, HIGH); } } void httpRequest(String link) { if (client.connect(server, 80)) { client.println("GET " + link + " HTTP/1.0"); client.println(); } else { Serial.println("Connection Failed"); client.stop(); } }

You can see then, that returning more than one key-value pair can still be parsed from a single request.

Related Posts by Categories

0 komentar:

Posting Komentar