Building Arduino Projects for the Internet of Things

(Steven Felgate) #1
CHAPTER 5 ■ IOT PATTERNS: REALTIME CLIENTS

Code (Arduino)


Next you are going to write code for connecting Arduino to the Internet using WiFi,
reading motion sensor data, and publishing it to an MQTT broker.
Start your Arduino IDE and 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

  • MQTT (publish)

  • Standard functions


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


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


Listing 5-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 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
(from Chapter 2 ) here.


Read Sensor Data


The third section of code is shown in Listing 5-2. It defines variables, constants, and
functions that are going to be used for reading the sensor data.


Listing 5-2. Variables for Reading Motion Sensor Data


int calibrationTime = 30;
long unsigned int lowIn;
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int pirPin = 3;

Free download pdf