Building Arduino Projects for the Internet of Things

(Steven Felgate) #1
CHAPTER 3 ■ COMMUNICATION PROTOCOLS

Code (Arduino)


Next you are going to write the code for connecting Arduino to the Internet using WiFi
and publishing it to a server using MQTT.
Start your Arduino IDE and type the following code or download it from book’s site
and open it. All the code goes into a single source file ( *.ino ) in the same sequence as
provided here, but in order to make it easy to understand and reuse, it has been divided
into four sections.



  • External libraries

  • Internet connectivity (wireless)

  • Data publish (MQTT)

  • Data subscribe (MQTT)


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


The first section of code is provided in Listing 3-6. It 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 WiFi shield) and, for
MQTT broker communication, you need to include <PubSubClient.h>. You can install
the <PubSubClient.h> library from:




  • : https://github.com/knolleary/
    pubsubclient/releases/tag/v2.3


Listing 3-6. External Libraries


#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 Listing 2-9 from Chapter 2 here.


Data Publish/Subscribe MQTT


The third section of the code defines variables, constants, and functions that are going
to be used for publishing and subscribing to an MQTT broker. The code publishes and
subscribes to same topic.
Define the address and port (default is 1883 ) of the MQTT broker that you want
Arduino to connect to, as shown in Listing 3-7. The topic variable defines which topic
on the broker data will be published and subscribed. If you do not have an MQTT broker

Free download pdf