Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 11 ■ IOT PATTERNS: MACHINE TO MACHINE


The final component is another Arduino device that controls lights. If the light sensor
publishes a message to the MQTT broker that light brightness level is LOW, the device
will automatically turn the lights on. In real life, this system could be utilized to turn
street lights on or off only when they are required instead of doing it at scheduled times,
regardless of how bright it is.


Learning Objectives


At the end of this chapter, you will be able to:



  • Read data from a light sensor

  • Publish messages to an MQTT broker

  • Control LEDs

  • Subscribe Arduino to an MQTT broker


Light Sensor Device


The first component of your IoT application is an Arduino device that will monitor the
light brightness levels and publish a message when they are low.


■ Note You already built this circuit in Chapter 4 , so for the hardware and software


requirements and circuit instructions, refer back to Chapter 4. Changes are in Arduino


code only, which in this case publishes a message to an MQTT broker instead of starting


a Node-RED flow.


Code (Arduino)


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

  • Read sensor data

  • MQTT (publish)

  • Standard functions

Free download pdf