In the first two lines, we define constants for the analog pin the sensor is
connected to and for the Arduino’s supply voltage. Then we have a pretty
normal
setup
method followed by a
loop
method that outputs the current tem-
perature every second. The whole sensor logic has been encapsulated in the
get_temperature
method. It returns the temperature in degrees Celsius, and we
convert it to a Fahrenheit value, too.
For the PING))) sensor, we only needed a digital pin that could be
HIGH
or
LOW
.
Analog pins are different and represent a voltage ranging from 0V to the cur-
rent power supply (usually 5V). We can read the Arduino’s analog pins using
the
analogRead
method that returns a value between 0 and 1023, because
analog pins have a resolution of 10 bits (1024 = 2
10
). We use it in line 20 to
read the current voltage supplied by the TMP36.
How to Encode Sensor Data
Encoding sensor data is a problem that has to be solved often in Arduino projects,
because all the nice data we collect usually has to be interpreted by applications
running on regular computers.
When defining a data format, you have to take several things into account. Among
others, the format shouldn’t waste the Arduino’s precious memory. In our case, we
could’ve used XML for encoding the sensor data:
<sensor-data>
<temperature>30.05</temperature>
<distance>51.19</distance>
</sensor-data>
Obviously this isn’t a good choice, because now we’re wasting a multiple of the
actual data’s memory for creating the file format’s structure. In addition, the receiving
application has to use an XML parser to interpret the data.
But you shouldn’t go to the other extreme, either. That is, you should use binary
formats only if absolutely necessary or if the receiving application expects binary data
anyway.
All in all, the simplest data formats, such as character-separated values (CSV), are
often the best choice.
There’s one problem left, though: we have to turn the value returned by
analogRead
into an actual voltage value, so we must know the Arduino’s current
power supply. It usually is 5V, but there are Arduino models (such as the
Arduino Pro, for example) that use only 3.3V. You have to adjust the constant
SUPPLY_VOLTAGE
accordingly.
Chapter 5. Sensing the World Around Us • 88
report erratum • discuss
www.it-ebooks.info