HackSpace_-_April_2020

(Frankie) #1

TUTORIAL


Monitoring Air Quality


The previous code will download the text
containing the data we want, but we need to pull
out the relevant information. In our case, we’re
interested in the NO 2 reading. The data is encoded
using a format called JavaScript Object Notation
(JSON). Fortunately, there’s an Arduino library that
understands this, and we can use it to get the data
out automatically:

String line = "";
while (client.available()) {
line = client.readStringUntil('\r');

if (line.indexOf('{')>=0) {
DynamicJsonDocument json_doc(6000);
DeserializationError json_error =
deserializeJson(json_doc, line);
if (json_error) {
Serial.println("parseing failed");
Serial.println(json_error.c_str());
}
else {

Serial.println("NO2");
String no2=json_doc["records"][0]
["fields"]["no2"];
Serial.println(no2);

}
}
}

A lot is going on in here, but most of it is just
shuffling data from one place to another. First, it’s
read from the client (which is the HTTPS client),
and then deserializeJson is called, which converts
the string of text into a data object that we can
extract the necessary data from. The JSON doc
is a hierarchical data structure. You can think of
it as the directory structure in a computer where
there’s a root, and inside of this, there can be either
named folders or named files (they can be ordered
as well as named in this case – if they are, we use
a number to extract the one we want). We need
to navigate this structure to get out the pieces we
need. In our case, the latest NO 2 reading is at json_
doc["records"][0]["fields"]["no2"];

DATA IN AND DATA OUT
Now that we’ve got the data, the next step is to find
a way of displaying it. We decided to use a servo to
make a simple pointer. We’re mounting this on top
of an LED weather display (see HackSpace magazine
issue 24), and didn’t want any more lights on there.
Our servo has a 180-degree range, and we decided
to have 0 degrees (horizontal, pointing left) as zero
milligrams of NO 2 , and 180 degrees (horizontal
pointing right) as 40 milligrams. This is the maximum
legal limit for air in the UK.
Servos have three pins to connection: ground,
power, and data. Ground should be connected to
ground, power to 5 V, and data to any IO pin. It just so

The data is encoded using a format called
JavaScript Object Notation (JSON). Fortunately,
there’s an Arduino library that understands this



Above
Servos are motors
combined with
feedback and control
electronics to let you
easily turn them to
a set position with
your code

Right
We’re a bit lucky
that the LOLIN32
happens to have
pins in the correct
position to slot our
servo straight into
the pin headers
Free download pdf