Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 11 ■ IOT PATTERNS: MACHINE TO MACHINE


void loop()
{
// Read sensor data
readSensorData();


// Delay
delay(5000);
}


Your Arduino code for the light sensor device is now complete.

Lighting Control Device


The other component of your IoT application is an Arduino device that will the control
lights—it will turn them on or off depending on the messages received from the MQTT
broker. The circuit and code for this device is basically the same as the circuit and device
that you developed in Chapter 6.


■ Note You already built this circuit in Chapter 6 , so for hardware and software requirements


and circuit instructions, refer to Chapter 6. Changes are in Arduino code only, which in this case


uses a different logic to publish a message to MQTT broker.


Code (Arduino)


Next you are going to write code for connecting Arduino to the Internet using WiFi,
subscribing to an MQTT broker, and controlling the attached LED.
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)

  • MQTT (subscribe)

  • Control LED

  • Standard functions


External Libraries


The first section of code, as provided in Listing 11-5 , 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
the MQTT broker communication, you need to include <PubSubClient.h>.

Free download pdf