Building Arduino Projects for the Internet of Things

(Steven Felgate) #1
CHAPTER 8 ■ IOT PATTERNS: WEB APPS

Code (Arduino)


The final component of this project is the Arduino code for connecting to the Internet
using WiFi, reading data from the temperature sensor, and publishing it to a server.
Start your Arduino IDE and either type the code provided here or download it from
book’s site and open it. All the code goes into a single source file ( *.ino ), but in order to
make it easy to understand and reuse, it has been divided into five sections.


  • External libraries

  • Internet connectivity (WiFi)

  • Read sensor data

  • HTTP (publish)

  • Standard functions


External Libraries..................................................................................................


The first section of code, as provided in Listing 8-6 , includes all the external libraries
required to run the code. Since you are connecting to the Internet wirelessly, the main
dependency of code is on <WiFi.h>.

Listing 8-6. Code for Including External Dependencies

#include <SPI.h>
#include <WiFi.h>

Internet Connectivity (Wireless)


The second section of the code defines variables, constants, and functions that are going
to be used for connecting to the Internet. Use the code from Listings 2-7 , 2-8 , and 2-9
(in Chapter 2 ) here.

Read Sensor Data


The third section of code, as provided in Listing 8-7 , defines the variables, constants, and
functions that are going to be used for reading sensor data.
The readSensorData() function reads data from Analog Pin A0 and the result is
between 0 and 1023. The greater the value returned, the higher the temperature. The
sensor value does not directly provide the temperature in Celsius or Fahrenheit, so a
formula, as highlighted in Listing 8-7 , is used to convert the sensor value into the required
formats.
Free download pdf