Building Arduino Projects for the Internet of Things

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

External Libraries


The first section of the code, as provided in Listing 11-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 11-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 (in Chapter 2 ) here.


Read Sensor Data


The third section of code, as provided in Listing 11-2 , defines the variables, constants, and
functions that are going to be used for reading the sensor data.
The readSensorData() function reads the data from Analog Pin A0 ; the result is
between 0 and 1023. The greater the value returned, the brighter the light source. The
light sensor value is assigned to the lightValue variable. Based on the lightValue
variable, the corresponding LOW or HIGH value is passed as a parameter to the
publishSensorData() function.


Listing 11-2. Code for Reading the Light Sensor Data


int lightValue;


void readSensorData()
{
//Read Light Sensor Value
lightValue = analogRead(A0);


Serial.print("[INFO] Light Sensor Reading: ");
Serial.println(lightValue);


if(lightValue < 500)
{
publishSensorData("LOW");
}

Free download pdf