Building Arduino Projects for the Internet of Things

(Steven Felgate) #1
CHAPTER 10 ■ IOT PATTERNS: MACHINE TO HUMAN

Code (Arduino)


Next you are going to write the code for the first component of this application. This code
will connect Arduino to the Internet using WiFi, read the proximity sensor data to get
garbage levels, and publish that information to an MQTT broker.
Start your Arduino IDE and type the code provided here or download it from the 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

  • MQTT (publish)

  • Standard functions


External Libraries


The first section of code, as provided in Listing 10-1 , includes all the external libraries
required to run the code. This sketch has two main dependencies—for Internet
connectivity, you need to include <WiFi.h> (assuming you are using a WiFi shield) and
for MQTT broker communication, you need to include <PubSubClient.h>.


Listing 10-1. Code for Including External Dependencies


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


Internet Connectivity (Wireless)


The second section of the code defines the 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 (Chapter 2 ) here.


Read Sensor Data


The third section of code, as provided in Listing 10-2 , defines the variables, constants, and
functions that are going to be used for reading the sensor data.
The calibrateSensor() function waits for the proximity sensor to calibrate properly.
Once the calibration is complete, the proximity sensor is active and can start detecting.
If you do not give it enough time to calibrate, the proximity sensor might return incorrect
readings.

Free download pdf