Building Arduino Projects for the Internet of Things

(Steven Felgate) #1
CHAPTER 6 ■ IOT PATTERNS: REMOTE CONTROL

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


The first section of code includes all the 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 the MQTT broker
communication, you need to include <PubSubClient.h>.
Listing 6-12 provides the first section of the code with all the required libraries.


Listing 6-12. 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
(in Chapter 2 ) here.


Data Publish


The third section of the code defines variables, constants, and functions that are going
to be used for connecting to an MQTT broker and callback when a new message arrives
(for details, see Chapter 3 ).
This is the same code that you saw in Chapter 3. You do not need to make any
changes for the code to work, but it is recommended that you customize some of the
code so that your messages do not get mixed up with someone else who is using the same
values. All values that can be changed have been highlighted in bold in Listing 6-13. If you
are using your own MQTT server, make sure to change the server and port values. The
two recommended changes include the value of the topic variable and the name of client
that you need to pass while connecting to the MQTT broker.
Whenever a new message is received, the callback() function is called. It extracts
payload and calls the turnLightsOnOff() function.


Listing 6-13. Code for Subscribing to an MQTT Broker


// IP address of the MQTT broker
char server[] = {" iot.eclipse.org "};
int port = 1883 ;
char topic[] = {" codifythings/lightcontrol "};


PubSubClient pubSubClient(server, port, callback, client);

Free download pdf