Arduino IoT Cloud For Developers
Arduino IoT Cloud For Developers
Muhammad Afzal
BIRMINGHAM—MUMBAI
Arduino IoT Cloud for Developers
Copyright © 2023 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted
in any form or by any means, without the prior written permission of the publisher, except in the case
of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information
presented. However, the information contained in this book is sold without warranty, either express
or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable
for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and
products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot
guarantee the accuracy of this information.
ISBN 978-1-83763-717-1
www.packtpub.com
To my parents, teachers, wife, and daughter, and the memory of my grandfather Muhammad Ameer,
for their sacrifices and for exemplifying the power of determination.
– Muhammad Afzal
Note from the Founding Director
of EZIT
In the ever-expanding landscape of the Internet of Things (IoT), where the digital and physical worlds
converge, the possibilities seem boundless. This realm, once the domain of science fiction, is now a
thriving reality. Behind the myriad of connected devices, intelligent systems, and seamless automation
that define our modern age lies a remarkable and accessible platform – Arduino.
In Arduino IoT Cloud for Developers, we will embark on a journey that takes us to the heart of this
transformative technology. As our world becomes more interconnected, the need for skilled developers
who can harness the power of IoT becomes increasingly critical. This book is your key to unlocking
that potential.
Author Muhammad Afzal is not just an expert in the field; he is a passionate advocate for democratizing
technology. He understands that the true beauty of IoT is its universality, and its capacity to empower
developers of all backgrounds and skill levels. This book embodies that spirit.
Whether you’re a seasoned developer or a curious newcomer, this guide offers something for everyone.
It walks you through the fundamentals of Arduino and IoT, empowering you to create your own
innovative projects. You’ll learn how to connect sensors, capture data, and make real-world decisions
using Arduino’s powerful and intuitive platform.
However, this book goes beyond the basics. It delves into best practices to design and deploy IoT
applications, offering insights and techniques that will enable you to build not just simple projects but
complex, scalable, and reliable systems. From managing data streams to securing your devices, from
optimizing power consumption to designing user-friendly interfaces, this book equips you with the
knowledge and skills to tackle real-world IoT challenges.
What sets this book apart is its commitment to practicality. The author understands that theory alone
won’t make you an IoT expert. You need hands-on experience. You need to troubleshoot, experiment,
and iterate. With his guidance, you’ll do just that. You’ll tackle real projects, solve real problems, and
gain the confidence to explore the IoT world on your terms.
In the pages that follow, you’ll find a wealth of knowledge, insights, and inspiration. Arduino IoT Cloud
for Developers is more than a book; it’s a gateway to a world of endless possibilities. So, whether you’re
building the IoT systems of tomorrow or simply exploring the wonders of connected technology, this
book is your trusted companion on the journey ahead.
Embrace the future. Dive in, learn, experiment, and create. The IoT revolution begins here.
Ehsan Elahi
Contributors
I want to thank the people who have been close to me and supported me, especially my wife, daughter,
brothers, sister, and parents.
About the reviewer
Khadija Akter is an IoT system designer and problem solver. She has a passion for embedded
electronics and IoT. She studies at the National University, at the Faculty of Electronics and
Communication Engineering.
She loves to work in an arena that is very much related to the technological sector. She is currently
working as an IoT developer for KaziSpin TecHub. She has been active in the field of IoT and embedded
systems since 2017. She also works as a trainer and speaker at various international conferences (the
3rd Young Scientist Congress in Bangladesh, the International Conference on Electrical Engineering
and Information and Communication Technology (ICEEICT), Empathy Nation, and many more).
I would like to convey my heartfelt gratitude to my family and friends who help to support and assist
my busy schedule and stand by my side. I would also like to thank Mr. Redwan Hasan for his support
and guidance in completing the review. It was a great learning experience. The completion of the
review would not have been possible without their help and insights.
Table of Contents
Prefacexv
Summary28
viii Table of Contents
2
First Look at the Arduino IoT Cloud 29
Technical requirements 30 Introducing Node-RED 50
Understanding how the Arduino IoT The Arduino IoT Cloud and a Node-
Cloud works 30 RED Hello World example 52
The Arduino IoT Cloud and the A tour of the Node-RED editor 52
MKR1010 Hello World example 32 Installing the Arduino IoT Cloud module for
What is the Arduino Create Agent? 33 Node-RED54
Setting up the Thing, device, and variable 34 Setting up an API, variable, and dashboard
widget56
Writing a sketch 44
Creating a first project with Node-RED 57
Creating a dashboard for web and mobile
with an interactive widget 46 Assignment 2 62
Assignment 1 50 Summary62
3
Insights into the Arduino IoT Cloud Platform and Web Editor 63
Technical requirements 64 Understanding the Arduino
Introducing the Arduino IoT Cloud Web Editor 83
interface64 Sketchbook84
Devices and things 65 Examples85
Dashboards68 Libraries and the Library Manager 86
Integrations and templates 69 Monitor AKA the Serial Monitor 87
Reference, help, and preferences 88
Exploring input controls 71 Arduino IoT Web Editor features 88
Switch, push button, slider, and stepper 71
Color, dimmed light, and colored light 72 Assignments90
Time picker (configuration) 74 Assignment 1 90
Scheduler (configuration) 75 Assignment 2 90
Assignment 3 91
Delving into output controls 77
Value, status, gauge, percentage, and LED 77 Summary91
Maps and charts 79
Messenger and sticky notes 81
Table of Contents ix
5
Project #2 – Creating a Portable Thing Tracker Using MKR
GSM 1400 113
Technical requirements 114 Activating SIM cards for IoT
Enhancing operations with IoT deployment124
asset tracking and remote control 114 Configuring the Thing, network
Exploring the advantages of GSM/ credentials, cloud variables, and code 125
LTE/NB-IoT communication Cloud variables 126
technologies115 Associating a device 127
Seamless global connectivity with Network129
IoT SIM cards 116 Coding130
6
Project #3 – a Remote Asset Tracking Application with LoRaWAN 135
Technical requirements 136 Testing GPS module data 144
Understanding LoRaWAN Setting up the Thing, device
and its IoT applications 136 association, cloud variables, and code 148
Usage in IoT 136 Cloud variables 149
LoRaWAN versus other Associating a device 150
communication technologies 137 Network156
Coding157
Components of a LoRaWAN IoT
application138 Configuring the The Things Indoor
Essential hardware – sensors and Gateway158
development boards 140 Creating web and mobile dashboards 163
Designing the project architecture 142 What next? 164
Schematics design and assembly 142 Summary165
8
Working with the Arduino IoT Cloud SDK and JavaScript 189
Technical requirements 190 Creating a Thing sketch 209
Demystifying the Arduino IoT Cloud Deleting a Thing 211
SDK – functionality and operation 190 Listing Things 211
Showing a Thing 213
Securing access – unveiling API keys
and authentication 192 Exploring properties – Node.js SDK
Initial exploration – test drive using interaction techniques 214
Postman193 Creating a property 214
Diverse platform compatibility – Updating a property 216
SDKs for various environments 197 Deleting a property 217
Step-by-step – installing the Arduino Listing properties 218
Node.js SDK client 198 Crafting dashboards – unleashing
Interacting with devices – hands-on potential via the
with the Node.js SDK 199 Node.js SDK 219
Creating a device 199 Creating a dashboard 219
Updating a device 201 Updating a dashboard 220
Deleting a device 202 Deleting a dashboard 221
Listing devices 202 Listing dashboards 222
Showing a device 204
Fine-tuning with the Node.js SDK –
Device properties/variables 205
property value management 224
Engaging with Things – Node.js SDK Get a property value 224
implementation guide 206 Set a property value 225
Creating a Thing 207
Assignment226
Updating a Thing 208
Summary226
9
Project 4 – Collecting Data from the Soil and Environment
for Smart Farming 227
Technical requirements 228 Architecting your agriculture
Smart farming with IoT 228 IoT system 233
Essential hardware for your agri-tech Schematics and design 234
project229
xii Table of Contents
Perfecting sensor calibration 239 Creating web and mobile dashboards 250
Setting up things, networks, What next? 252
and cloud variables 244 Summary252
Cloud variables 245
10
Project #6 – Making Your Home Smarter with a Voice Assistant 253
Technical requirements 254 Cloud variables 264
Creating smarter homes with IoT 254 Associating a device 265
Network266
Essential components – sensors and
Coding266
development boards 256
Blueprint for your smart home IoT User-friendly controls – building web
project258 and mobile dashboards 270
Schematic design and assembly 258 Enhancing controls – integrating the
Testing the WS2812 with the Arduino IDE 260 Arduino IoT Cloud with Amazon
Alexa271
Initial setup – Thing, network
credentials, cloud variables, and code 263 What next? 275
Summary275
Summary301
12
Project #6 – Tracking and Notifying about Your Heart Rate 303
Technical requirements 304 Setting up a Thing, network
Exploring IoT for smart health credentials, cloud variables, and code 312
solutions304 Cloud variables 313
Knowing the hardware components – Device association 314
sensors and development boards 305 Network315
Coding316
Understanding the project
architecture308 Setting up a dashboard for web and
Schematics design and assembly 308 mobile317
Sensor calibration 309 Setting up the notification service 318
What next? 322
Summary323
13
Scripting the Arduino IoT Cloud with Cloud CLI 325
Technical requirements 326 Listing devices 331
What is the Arduino Cloud CLI? 326 Deleting a device 332
Tagging and untagging a device 333
Securing access – unveiling API keys
Extracting a template from a Thing 334
and authentication 327
Creating a Thing 335
Installing the Arduino Cloud CLI 329
Cloning a Thing 336
Interacting with devices 330 Listing Things 337
Creating a device 330
xiv Table of Contents
14
Moving Ahead in the Arduino IoT Cloud 351
Arduino IoT Cloud plans 351 Arduino PRO hardware 357
Plans for individuals 352 Arduino PRO software 361
Plans for schools 353 Further resources and insights 363
The enterprise base plan 354
Summary364
Arduino PRO 357
Index367
This book accommodates both beginners and experienced readers, providing a step-by-step learning
path from IoT fundamentals to advanced IoT development with the Arduino IoT Cloud. Regardless of
your background, this book equips you with the skills to design and implement innovative IoT solutions.
Chapter 11, Implementing the Arduino IoT Cloud Scheduler and Over-the-Air Features, provides a practical
demonstration of how to use the Cloud Scheduler in Arduino IoT Cloud to automate operations that
are time-dependent. In the second part of the chapter, we will explore Over-the-Air (OTA) update
features, which help us to send updates over the air without any physical connectivity to devices.
Chapter 12, Project #6 – Tracking and Notifying about Your Heart Rate, offers a practical demonstration
of a smart health project, where we will use XIAO ESP32C3 with a heart rate monitoring sensor to
build a wearable product, which will send data to the Arduino IoT Cloud. Then, we will use Webhooks
to send our beats per minute (BPM) to Zapier for notification alerts.
Chapter 13, Scripting the Arduino IoT Cloud with Cloud CLI, teaches you how to perform operations on
the Arduino IoT Cloud using the command-line tool, which includes operations on devices, Things,
and dashboards, as well as OTA. This chapter will help you learn the commands and prepare you to
create your own batch scripting for automated operations.
Chapter 14, Moving Ahead in the Arduino IoT Cloud, provides details about the different Arduino
IoT Cloud pricing plans, including the features of each plan. It also looks at Arduino PRO Hardware
and Software for Industrial IoT and provides a complete list of resources for further explorations.
Development boards:
Sensors:
• DHT22/DHT11
• MQT-135
• The NEO 6-M u-blox GPS module
• Capacitive soil moisture sensors
• DS18B20 waterproof probes with long wires
• The WS2812 RGB ring
• A pulse sensor
If you are using the digital version of this book, we advise you to type the code yourself or access
the code from the book’s GitHub repository (a link is available in the next section). Doing so will
help you avoid any potential errors related to the copying and pasting of code.
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file
extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “This
cloud variable declaration is available in the thingProperties.h file.”
A block of code is set as follows:
TinyGPSPlus gps;
unsigned long previousMillis = 0;
const long interval = 30000; //milliseconds
Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words
in menus or dialog boxes appear in bold. Here is an example: “After setting up the configuration, click
the Get new Access Token button.”
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at customercare@
packtpub.com and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen.
If you have found a mistake in this book, we would be grateful if you would report this to us. Please
visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would
be grateful if you would provide us with the location address or website name. Please contact us at
copyright@packtpub.com with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you
are interested in either writing or contributing to a book, please visit authors.packtpub.com.
https://packt.link/free-ebook/9781837637171
This first part describes the principles of the Internet of Things (IoT), gives an overview of the
Arduino IoT Cloud platform, and shows how to use it for the first time. It then provides a detailed
description of its functionalities.
This part has the following chapters:
• A digital network
• Worldwide coverage
• Standardized specifications
• Widely used for personal and professional communications
IoT devices are often called IoT Nodes because they are part of this network.
They feature sensors to detect or measure a physical property, such as the temperature of the environment
or the speed of a vehicle. In other cases, they are connected to external machinery, devices, or appliances,
always with the same purpose: collecting the values of physical properties, often called Telemetry
Elements, and transmitting them to the internet. Once the values have reached the internet, they can
arrive almost everywhere in the world in a few hundredths of a second.
You may think about interfacing an IoT node to an industrial machine to remotely transmit the
information about its running conditions, and eventually alert a maintenance operator, in case of a
fault. Or, connecting the node to your coffee machine to measure the level of the coffee grounds with
the possibility to check it remotely while you are at the supermarket so that you can buy another pack
only if required.
As a matter of fact, the IoT opens up the possibility to virtually infinite applications because connecting
a device to the internet implies the possibility to both monitor the environment and send commands
to the node remotely.
In fact, the telecommunication technologies used in the IoT are bidirectional and information can
flow from the IoT node to the internet and vice versa. The interaction among IoT nodes is mainly
related to the exchange of digital information by using the internet as the communication media.
What is the Internet of Things? 5
The choice between on-the-edge and on-the-cloud implementations is mainly driven by the application
and the required response time. Implementations on the cloud allow more freedom in terms of
programmable features. This is because the cloud is composed of multiple servers working together and
it has virtually no constraints of memory and computational power. On the other hand, deployments
on the edge remove some bottlenecks related to the latency of communication networks, reducing the
response time of an IoT node and allowing it to interact with the physical world in real time.
It’s worth noting that an implementation on the edge doesn’t preclude the benefit of implementing
manual remote control of the nodes in addition to automatic control. For example, an operator could
interact with the devices in the field through a graphical user interface visualized on a web page (called
a dashboard). They would see the actual values of environmental conditions and could trigger the
valve as they liked.
The programmer of the application is responsible for defining and configuring the dashboards, which
can be as complex as required, with widgets to visualize and insert data such as graphs and textboxes,
and trigger commands such as switches, sliders, pushbuttons, and many others.
The market sees an increasing number of on-the-edge applications for various use cases where
microcontroller devices can be successfully adopted as control units of IoT nodes. This trend has led to
the continuous, fast improvements in hardware components, with augmented computational capabilities
and a consequent decrease in their cost, as well as the mass availability of wireless telecommunication
technologies characterized by very low power consumption and long-distance transmission range.
When we consider the installation of IoT nodes in remote and not easily accessible areas, energy
autonomy is a very important aspect: we want to reduce the need for battery recharging as much as
possible to decrease the costs of human intervention. Ideally, a good IoT application is supposed to
be fully autonomous!
When you adopt one of the Low-Power Wide Area Network (LPWAN) technologies, you need to
consider that a decreased power consumption comes at the expense of a reduced quantity of data that
can be transmitted with a single message and a higher interval between messages. It’s like considering
data as a form of energy and applying the energy conservation law: if you decrease the power, you
decrease the amount of data, not only the transmission range.
A decreased amount of data per message and a longer interval between two transmissions mean that
you need to reduce the information exchanged with the cloud so that the cloud needs less time to
collect all the values to process.
When this duration, which we may call Cloud Latency Time, is too long, then it’s worth implementing
intelligence on the edge.
What is the Internet of Things? 7
When we talk about digitalization, other buzzwords are often used together with the IoT: big data,
artificial intelligence, and machine learning. These are complementary sciences that can be used to
realize complex digital projects. We’ll describe what they are and how they are used in conjunction
with the IoT next.
Big data refers to extremely large and complex datasets and to the science that studies how to process
them. Traditional data processing software is unable to handle big data in a reasonable amount of
time due to the size of the datasets and their unstructured and disaggregated nature, so dedicated
technologies are necessary to extract valuable insights and knowledge used to support decision-making
and strategic planning.
When we consider hundreds or thousands of IoT nodes sharing different values in real time, collected
from the physical world, you may understand that the size and variety of the data require much more
than a traditional database.
Big data involves an implementation of logic on the cloud. Even when an on-the-edge model is used
for a fast response time in the physical world, data can be sent to the cloud for long-term processing
without time constraints. Here, big data can be supportive.
For example, with reference to our example of smart irrigation, a node can use values from soil
moisture sensors to control a hydraulic valve on the edge and also share information with a cloud
application that uses data from multiple nodes to adapt a model for weather forecast considering, and
also additional information from national weather stations.
You may consider big data as the cloud application processing raw data to extract and store
valuable information.
Artificial intelligence and machine learning are often referred to as being the same science, but they
are not. Artificial Intelligence (AI), is a broad field that encompasses many different subdisciplines,
including Machine Learning (ML).
AI is the broader concept of machines being able to carry out tasks in a way that would normally
require human intelligence, such as visual perception, speech recognition, decision-making, language
translation, and others.
What is the Internet of Things? 9
ML is a specific subfield of AI that focuses on enabling computers to learn from data and make
predictions or decisions without being explicitly programmed to do so. Usually, ML involves training
a model on a dataset and using the trained model to make predictions or decisions on new data.
In summary, AI is the broader concept of the mimicking of human intelligence by machines, while
ML is a specific method/technique to achieve AI, which allows the machine to learn from data, instead
of being explicitly programmed.
AI and ML models can be trained by using the data collected by big data tools and used to interpret
other new data from the same or another big data platform.
Once trained, the models can be deployed on the cloud and on the edge as well, depending on their
size and the technical features of the nodes.
While big data tools processes the data directly with analytical models, AI/ML works on patterns in
data in order to recognize situations and trends.
For example, you can use big data to extract the trends of soil moisture in a wide region where thousands
of sensors collect values every hour and big data can support you in distinguishing between daily,
monthly, and seasonal changes over a period of years.
ML works differently; it ingests values of different types, such as weather forecast parameters, and
identifies patterns that affect your observations. You may create an ML model by training a neural
network with temperature, atmospheric pressure, humidity, wind speed, and soil moisture values
across a period. Then you provide another set of data from a different period, without the soil moisture
values, and the model is able to suggest indications about irrigation needs.
With reference to the following diagram, you may see the complete dataflow of a complex application,
where the IoT senses the physical world, reacts immediately on the edge when required, and forwards
the values to big data for offline or batch processing (not in real time):
Big data stores and aggregates the values that are used to train and run AI/ML models. These models
make decisions and send commands back to IoT nodes that interact with the physical world.
Important note
This is not the place to cover the implications in terms of the workforce, but I would like to say
that the IIoT doesn’t directly imply the reduction of operators, but their training and technical
growth can be managed from a cost-reduction perspective when good, fair employment policies
are adopted.
What is the Internet of Things? 11
The adoption of the IoT principles in the industrial environment requires particular attention in
the implementation and deployment of nodes because the environment can be harsher in terms of
temperatures, vibrations, and electromagnetic pollution.
The overheating caused by higher temperatures in certain industrial environments causes failures in
the electronic components of nodes and reduces their lifespan.
Vibration fatigue is another main cause of failures of electronic devices. The vibrations transfer to
the electronic board when a node is installed in contact with a machine, and they apply stress to the
components, resulting in early failure.
Industrial environments are quite dense with industrial motors in machinery, power cables, the cellular
devices of operators, and other sources of electromagnetic fields.
The preceding aspects affect IIoT nodes only, while the application of the IoT to the industrial
environment has other implications on the cloud side:
• Scalability: Cloud infrastructures for the IIoT typically require it to easily handle and store
large amounts of data from a vast number of IoT devices
• Data security: The industrial market requires improved cloud security measures to protect
against cyber threats to cloud applications and IIoT devices
• Data localization: One of the frequent requests from the industrial market is that all data
remains confidential and confined to the local country
Several reasons justify a request for cloud data to remain in the local country. Data privacy and security
concerns are evident when you consider that keeping data within a country ensures that it is subject
to the jurisdiction and protection of local laws.
Furthermore, some countries have strict regulations regarding the storage and handling of sensitive
data, and keeping it within the country helps organizations comply with these regulations.
Last but not least are considerations related to performance and cost-effectiveness: accessing data
and applications stored in a remote location can result in slower performance and higher latency.
Likewise, transferring data across international borders can be expensive and complex, making it
more cost-effective to store data within a country.
Industry 4.0, known as the Fourth Industrial Revolution, is a broader concept than the IIoT and
refers to the application of the IIoT specifically in smart factories for the production of consumer goods.
In this way, production processes are controlled and monitored in real time and digitalization empowers
machines and devices to make decisions, freeing up human workers for higher-level tasks. This is a
decentralized decision-making approach, where production is driven by data collected and analyzed
by machines and devices in order to speed up a continuous improvement of the production processes.
Flexible manufacturing processes allow the mass production of customized products in batches of
one pace having features defined by every single customer at the time of online shopping.
12 Introduction to the IoT and Arduino
Industry 4.0 means connecting a fully automated factory to the internet to improve the customer
experience and optimize the overall business performance.
Customers can go to their preferred online store to buy a pair of running shoes, select the model,
choose the materials, configure the colors of the different parts, and place an order. After payment
by credit card, the order digitally arrives at the factory, where robots and machinery are configured
in real time to get material from the warehouse, produce your custom shoes, including printing your
name on them and the box, and then return the box to the warehouse ready for shipment.
Not a single piece of paper has been printed throughout the whole process. The facility managers
can consult metrics online regarding the performance of the factory and the customer receives their
personalized shoes delivered at home.
This is not a dream, and it’s already possible with the manufacturer Nike®, famous worldwide.
Industry 4.0 requires a wider software architecture than the IIoT cloud.
You may consider that the IIoT cloud is already interfaced with the machinery and devices of a
production plant in an IIoT application. Industry 4.0 additionally connects digital systems from the
different departments of the business, including the following:
• Enterprise Resource Planning (ERP): To automate and manage core business processes for
optimal performance
• Computerized Maintenance Management System (CMMS): To manage assets, schedule
maintenance, and track work orders
• Warehouse Management Systems (WMSs): To support inventory and manage supply chain
fulfillment operations
Here, we have discussed the IoT in detail, as well as cloud versus edge processing and AI implementations.
We have covered some details about the Arduino ecosystem, including their PRO line of products.
Later, we discussed the IoT, big data, artificial intelligence, and machine learning, including the IIoT,
as they all are very important pillars in high-level projects. In the next section, we will discuss what
benefits there are for users by implementing the IoT in daily life as well as in industry.
Data collection and analysis by IoT nodes can be used to personalize our experiences and the augmented
connectivity provided by IoT solutions creates new possibilities for communication and collaboration.
Finally, the IoT and IIoT enable new and modern business models, as we’ll see in the next section.
You may ask why all this is happening now and if it comes without a cost.
The history of the IoT can be traced back to the 1980s when the term was first used by British technology
pioneer Kevin Ashton in a presentation about the potential for interconnected devices.
In the early 2000s, the development of wireless networking standards such as Bluetooth and Wi-Fi
made it easier to connect devices to the internet and cellular connectivity became a consumer market.
Ten years later, major technology companies, such as Microsoft, Google, and Amazon, began to invest
in IoT cloud platforms.
Today, after 40 years, the progress of software technology has made big data, data analytics tools, and
cloud platforms accessible and affordable for most people. The internet is a predominant medium of
communication and the decreased cost of electronics, together with ecosystems such as Arduino, has
made the technology easy to use.
The IoT indirectly brings costs to businesses of every size because they need to seize the moment,
adopt these technologies, and keep up with progress to remain competitive in the market.
The social impact of the IoT is related to the introduction of different behaviors and the risk of human
beings losing some manual and practical capabilities. For example, people who used to travel by car
before navigation applications were available on mobile phones had a certain sense of orientation;
nowadays, this skill has almost disappeared.
The IIoT introduces the risk of misleading managers to think that these technologies support cost
savings by reducing the workforce because everything is automated. Actually, the personnel need
training to maintain, troubleshoot, and improve the new systems, and it’s important that business
managers understand this.
In the end, it is the responsibility of everyone involved in an IoT project to consider the application
and manage the social effects properly. It means that it’s also your responsibility, dear reader.
The following figure, from the whitepaper Business Models and the Internet of Things by the Bosch
IoT Lab, shows the evolution of web technologies and what business models were enabled in the
different phases:
We are now fully in the Web 3.0 phase where the IoT requires a drastic shift of mindset in the creation
and the capture of commercial value. The Business School of Harvard University spotted this change
and highlighted a series of implications.
First of all, customers require their needs to be addressed in real time. The IoT even allows businesses
to address emergent needs in a predictive manner.
The possibilities offered by the IoT change the product management processes during their life cycle.
The obsolescence reduces and it happens over a longer time because new versions of a product are
evaluated by considering aggregated information about usage, collected automatically from products
themselves, and analyzed to identify the effective requirements. Furthermore, the proposed user
experience is based expressly on the collaboration of the products with others, eventually manufactured
by third parties.
This moves the value of the products in such a way that customers perceive more benefits in the
personalization of the products and their features than in commodity advantages such as lower cost,
higher quality, and immediate availability. Or, in the case of professional and industrial products,
brand and ownership of the intellectual property.
The appreciation for the collaboration capabilities of IoT products also suggests manufacturers should
invest resources in understanding how other ecosystems work and make money, with the aim of
developing a certain level of compatibility, more so than making a big effort to leverage internal core
competencies and existing resources and processes.
Once the features of the new version are identified and implemented, manufacturers can often update
many products at the same time, and remotely over the air. This is one of the appealing services that
can be offered as the intrinsic value of a product or a paid service for subscribers.
The enablement of different business models 15
The increased possibility to offer additional services moves the path to profit in the business strategy.
The new approach is the search for the optimal balance between immediate and recurrent revenues.
Immediate revenues, related to the traditional core business, often require a lot of effort and large
investments to scale the number of sold products. On the other hand, the activities required to establish
and maintain a good service offering, based on IoT capabilities, guarantee recurrent revenues in time.
When we talk about business models related to the sale of services, the subscription model is the most
well known: the user doesn’t pay to own the solution, but they pay an amount regularly to use it. This
model is usually adopted by companies offering smart home devices such as connected thermostats,
security cameras, and smart locks. Customers pay a monthly or annual fee for access to the devices,
as well as the ability to control and monitor them through a mobile app.
One type of IoT subscription business model with a growing trend in its adoption is asset tracking.
The reduction in power consumption and dimensions, as well as the decreased dimensions and costs
of IoT nodes, enable a progressive adoption to localize different assets they are attached to. In this
case, the subscriber doesn’t pay for the IoT nodes but for regular access to the localization data and
the movements of the assets.
The IoT supports the proposal of other kinds of services; for example, a predictive maintenance IoT
solution enables the sales of a convenient maintenance service, where the contract is appealing to
both the contractor and the customer. The contractor can keep their tariffs lower because they don’t
need to schedule periodical visits to their customer: the system will inform them in advance to plan
the intervention before it becomes urgent. At the same time, they can enlarge their customer base to
justify the cost of the installed solutions.
A consultancy company can install an IoT solution to measure the performance of machinery in
a production plant without stopping any machine because all data is collected by autonomous IoT
nodes that don’t need interfaces to the existing plant. Data is used to measure the Overall Equipment
Effectiveness (OEE) and suggest how to optimize the usage of the plant. In this case, the core business
of the company is not the sale of IoT solutions, but the services deriving from the data collected by
the IoT application.
The razor-blade business model in the IoT is similar to traditional models but with the added convenience
and customization of IoT technology. The goal is to get the product in the customer’s hands, at cost
or even less, to start selling your other products. The name comes from the company Gillette®, the
inventor and first adopter: its main revenues come from the sale of the blades while razors are just the
main source to bring about the sales of blades as one razor sold will generate multiple purchases of
blades. In a similar way, HP® sells inkjet printers at a very low price with the aim of gaining revenues
from the sale of the cartridges. The IoT can monitor the customer’s habits and suggest the optimal
model for the consumable. It can also increase the probability of reordering because an order can be
placed automatically by a device.
There are cases where businesses provide IoT applications with their hardware for free because its
purpose is to monetize by collecting and reselling users’ data. This pertains to the situation involving
driving habit monitoring devices. While these devices offer valuable insights to users, insurance
companies derive significant benefits by analyzing driving patterns across a large number of individuals.
Introducing this model can be seen as an expansion of your primary business, where you initially focus
on addressing the needs of your end users and subsequently explore opportunities to generate revenue
from their data. These two approaches can coexist harmoniously as long as you prioritize transparency
with your customers regarding data usage and take necessary measures to safeguard their privacy.
The architecture of an end-to-end IoT application 17
In the preceding section, we have discussed what innovations and improvements end users benefit
from due to smart products. The IoT has not only improved end users’ lifestyles but has also helped
new business models to emerge, as well as helping industries to shift toward Industry 4.0, which helps
industries run their production lines securely, quickly, and cost-effectively.
There is an important difference between cloud platforms and cloud applications. Cloud platforms
implement communication, user and device management, data storage and security, and other basic
services; cloud applications implement the logic of the application, the dashboards, and all the specific
aspects of the application.
In this sense, the Arduino IoT Cloud can be considered a cloud application running on the AWS
cloud platform.
Thanks to the connectivity offered by the internet, you may set up even a complex IoT solution that
features many different functionalities, just by exploiting multiple cloud applications, frameworks, and
services already implemented by third parties and interconnected via the internet. This means that
you don’t need to develop or configure everything from scratch and you may save time and headaches;
it also explains the reason why multiple cloud platforms and cloud applications are visualized in the
preceding figure.
18 Introduction to the IoT and Arduino
Examples of these functionalities can be Single Sign-On (SSO), a user authentication service that allows
a user to use one set of login credentials (e.g., name and password) to access multiple applications –
such as social media platforms, and tons of others. You just need to decide what you need, search on
the internet for the preferred provider, and easily integrate those features in your application without
the need to program them. This is also valid for the Arduino Cloud platform, which offers a couple
of different ways to interface with third-party applications, as we’ll see in Chapter 12.
The gateway is the last type of module we need to talk about. Gateways support the connection between
nodes and cloud platforms. Or, more precisely, they are the bridge connecting nodes to the internet
and allowing the exchange of data between nodes and cloud applications. There are many different
types of gateways, characterized by the communication technologies they implement.
Your Wi-Fi router is a perfect example of a gateway: it’s connected to the internet and it accepts
connections from other devices via Wi-Fi. It converts the Wi-Fi device into the data transportation
technology of your internet provider (landline, Ethernet, or fiber-optic cable).
Gateways may also implement additional functionalities, such as data filtering, protocol conversion,
and security. Every IoT application includes gateways in the architecture, even when they are not
directly managed by you or the programmer of the solution.
Let’s consider an application with nodes using cellular connectivity. It may look like the nodes are
directly connected to the internet, but it’s not the case. In fact, the nodes connect to the cellular network
as well as dedicated gateways managed by the network provider. It’s important to clearly understand
the presence of all the components in the architecture because each part can be a point of weakness
in the case of an issue and can make the troubleshooting longer and more complex.
In relation to the four main communication paths in the whole chain, the main distinction is related
to the wireless or wired nature of the communication.
As per the preceding figure, the field-to-device path is usually wired: sensors, actuators, and devices
connect to an IoT node thanks to wires. They pack and exchange data according to one of the standards
for wired interfaces shown in the figure.
The device-to-gateway path can be wired or wireless depending on the technical requirement of the
node for each specific application. Wireless IoT nodes offer the following benefits compared to wired
IoT nodes:
• Mobility: Wireless IoT nodes are not restricted by physical connections and can be easily
moved or relocated, providing more flexibility and freedom
• Ease of installation: Wireless nodes do not require cabling and can be installed much faster
and more easily, reducing installation costs and time
• Scalability: Adding new nodes or devices to a wireless IoT network is easier and less expensive
than adding wired nodes
• No infrastructure requirements: Wireless IoT nodes do not require a pre-existing wired
infrastructure, making them ideal for remote or hard-to-reach locations
• Improved reliability: Wireless nodes are less susceptible to failure caused by physical damage
to cables, making them more reliable for many IoT applications
However, it’s worth mentioning that wireless IoT nodes may suffer from interference from other wireless
devices, limited range, and potential security issues, so it’s important to consider these limitations
when choosing between wired and wireless IoT nodes.
For example, the IoT nodes for the load, vibrations, and structural monitoring of a bridge over a river,
which respectively provide useful information about the maintenance, traffic balance, and improvement
requirements, don’t need to be wireless. Many smart agriculture applications, on the other hand,
benefit from long-range wireless technologies because of the difficulties and the installation costs of
a wired network covering huge areas.
Considering the Kids park has a lot of IoT nodes, we can roughly divide the applications in the different
market verticals into four main groups:
• Consumer devices with a very short transmission range: Wearables, safety devices, remote
controls, and toys that typically use a Bluetooth or a Bluetooth Low Energy (BLE) connection
to a mobile phone that shares the connectivity to the internet. This approach demonstrates
the possibility of daisy-chaining multiple gateways with different technologies to reach the
required connectivity.
20 Introduction to the IoT and Arduino
• Consumer devices with a short transmission range: This is the case for home automation
devices, such as the thermostat of your house or appliances, entertainment devices, personal
instruments, and healthcare devices connected to the internet through a cabled Wi-Fi access point.
• Wireless professional devices: Automotive, smart agriculture, mining, and some logistics and
outdoor industrial applications require very long-distance transmission ranges provided by
the latest cellular technologies, which includes 3G/4G/5G or LPWAN.
• Wired professional devices: Some infrastructural projects, such as the monitoring of bridges
and dams or indoor industrial projects, require wired nodes to increase reliability, increase the
data throughput of the transmission, reduce the maintenance required for battery replacement,
and increase data security.
The gateway-to-cloud link is wired in most IoT applications and, eventually, the gateway provides a
backhaul wireless connectivity to the internet. This is the case of professional Wi-Fi and LoRa gateways
that implement an Ethernet interface and also a cellular modem: the gateway automatically swaps to
cellular if the Ethernet connection fails.
Defining the nature of the cloud-to-cloud communication path is a little bit trickier because we need
to consider that cloud apps run on cloud platforms, and these are composed of servers interconnected
to each other. The physical connection among the servers is definitely wired, but we may consider
the logical connection between cloud applications wireless because, when compared to applications
installed on a single server on the internet, wireless and wired IoT nodes offer the same benefits.
In this section, we discussed the high-level architecture of an end-to-end IoT application with multiple
nodes, gateways, and the cloud. In the second part of the section, we discussed communication
technologies and protocols, where we divided different communication technologies into wireless
and wired mediums for better understanding. In the next section, we will discuss the security of IoT
solutions, as well as device provisioning services, in detail.
Security aspects and device provisioning 21
Hardware security
Attackers can exploit security vulnerabilities due to outdated or unpatched software, and this is even
more probable when nodes are based on microcomputers running common operating systems. The
probability decreases significantly when the node features a microcontroller that runs on bare metal
as firmware, like in the case of the Arduino ecosystem. This is because the software running on the
device is reduced to the minimum strictly necessary to run the device.
The adoption of strong data encryption algorithms on nodes protects the data transmitted over the
network, making it less vulnerable to eavesdropping or tampering. In this case, too, the Arduino
ecosystem demonstrates that it is a good choice for the implementation of an IoT application: Arduino
devices for IoT embed secure elements, called crypto-chips, able to generate and manage security
keys at the hardware level, without the need to include a password in the source code of the node
application. We’ll see what this means and how it works toward the end of this section, but it’s now
necessary to talk about another security risk related to IoT nodes.
That is inadequate access controls: some IoT devices with inadequate access controls may allow
unauthorized individuals to access or control the device, potentially compromising the security of
the system as a whole.
The access can be remote or even direct to the device to extract the original firmware from the device
and overwrite it with a different version programmed by hackers. The extraction of the firmware could
also be used just for replicating the functionalities of an original device on compatible but cloned
hardware, threatening the results of an IoT business.
Arduino has engineered a safe version of their traditional bootloader to prevent these risks. A bootloader
is the first software that is executed on the device and is responsible for loading the firmware and
initializing the device’s hardware.
22 Introduction to the IoT and Arduino
The Arduino Safe Bootloader adds a secure environment to the traditional bootloader by implementing
mechanisms for firmware fail-safe authentication and secure updates. These prevent unauthorized
access to the device’s firmware and ensure that only authorized firmware can be executed on the device.
An authenticity check of the firmware is based on digital signatures and guarantees security: the
bootloader checks the digital signature of the firmware before loading it into the device’s memory
and doesn’t proceed in the case of unauthorized or wrongly signed firmware, preventing the device
from booting. In the same way, the safe bootloader protects against tampering, data corruption, and
reverse engineering: it validates a new version of the firmware before overwriting the old one and can
be configured to prevent the reading of the actual firmware from the device.
The programmer of the IoT node generates and manages their digital signatures, maintaining full
control of the device, but excluding others at the same time.
I recommend the adoption of the secure bootloader in any IoT project because the minimal effort
required to implement it is repaid immediately in terms of the security and integrity of the device
and data.
Microcontroller-based nodes, with strong hardware encryption capabilities and secure boot mechanisms,
address most of the security concerns on the node. Regular security audits ensure that the data
exchanged between IoT devices and the backend systems is protected, while the providers of cloud
platforms and cloud applications are responsible for securing the backend systems on the cloud that
process and store the data by implementing secure data storage practices and regular backups, as well
as regularly monitoring the systems to detect and respond promptly to potential security incidents.
The SSL/TLS security protocols are the most adopted for secure communications on the Internet and
use a combination of both symmetric and asymmetric encryption:
In SSL/TLS, the initial handshake between the client and the server is performed using asymmetric
encryption. The client and the server agree on a shared secret key, which is then used for symmetric
encryption of the data transmitted between them. This approach provides both security and performance,
making it a suitable encryption protocol for securing communications in IoT environments.
In the end, the device needs to know the public key for the SSL/TLS handshake and the cloud needs
to know a unique device key or device identity to recognize the connection from a legitimate device.
This data shall be configured during the provisioning phase for each IoT device that we want to deploy
for our application.
The provisioning for a limited number of devices is usually manual or semi-automatic and is performed
during the programming of each single device. In this phase, the programmer defines the unique
identifier of their device and registers it on the cloud, then generates the security key on the cloud,
and copies it to the device. It’s not a difficult process, but it may become complicated because different
clouds have different architectures and ways to do this.
Even though the wizard does everything, I still consider this process semi-automatic; in fact, if you have
multiple devices, you need to connect them to the USB one at a time. Actually, you may implement
more automatic provisioning of Arduino boards on the Arduino IoT Cloud by programming a good
script for Arduino CLI and using a smart USB hub that flexibly switches host connectivity between
ports, but the topic is beyond this book.
Open source
The concept of open source software and open source licenses was first introduced in the late 1960s and
early 1970s by computer scientists and programmers who believed that the sharing and collaboration
of software code would lead to better, more reliable, and more innovative software.
Arduino is considered to be one of the first companies in the world to adopt open source licenses for
hardware engineering too. The company released the first version of the Arduino board in 2005, along
with schematics for the board and the source code of the core firmware under an open source license.
This allowed anyone to use, modify, and redistribute the design freely, which greatly contributed to the
success and popularity of the Arduino platform. The open source approach also enabled a community
of developers and makers to collaborate and improve the platform, creating a wide range of libraries,
tutorials, and projects that are still used today.
Open source 25
• MIT License: This is one of the most permissive open source licenses and allows users to use,
modify, and distribute software or hardware for any purpose, including commercial purposes,
without the need for attribution.
• GNU General Public License (GPL): This was the first widely recognized open source software
license, released in 1989 by the Free Software Free Software Foundation.
• GNU Lesser General Public License (LGPL): The LGPL is primarily used for software
libraries, although it is also used by some standalone applications. The LGPL was developed
as a compromise between the strong copyleft of the GNU GPL and more permissive licenses
such as the BSD licenses and the MIT License.
• Free Software Foundation (FSF): It is designed to ensure that software or hardware remains
open source and free.
• Apache License: This is a permissive open source license that allows users to use, modify, and
distribute the software or hardware for any purpose, including commercial purposes. However,
users must provide attribution and must not use the original authors’ names or trademarks to
promote their products.
• BSD Licenses, including the New BSD License and the Simplified BSD License: These are
permissive open source licenses that allow users to use, modify, and distribute software or
hardware for any purpose, including commercial purposes, without the need for attribution.
• Mozilla Public License (MPL): The MPL is a copyleft license that requires users to make any
modifications to the software or hardware available under the same license, but allows them
to add proprietary extensions to the software or hardware.
Open source licenses encourage collaboration and sharing, which can lead to faster innovation and
better-quality software or hardware. Open source software or hardware engineering is often free, which
can result in significant cost savings for users: they can modify the engineering and the products to
meet their specific needs, without having to worry about proprietary restrictions. Open source brings
an improved level of transparency and security because licensed products are reviewed and audited
by many people, rather than just a few proprietary developers.
Arduino releases software and hardware under a combination of open source licenses. The Arduino
Integrated Development Environment (IDE) software is released under the GPL v2 license; the
hardware designs, including schematics and board layouts, are released under the Creative Commons
Attribution Share-Alike license; while the software libraries are released under GPL v2, LGPL v2.1,
and the MIT License, among others.
Now, this approach requires some programming skills but you may get paid support from Arduino
and its network of System Integrator Partners. These are industrial system integrators who joined a
partnership program and are officially recognized by Arduino. This network also solves concerns
about the after-sales support of Arduino-based IoT nodes and applications.
Summary
We have seen that two electronic devices can use the internet to interact with each other and exchange
information, without the need for a direct physical connection between them. Nodes can be interfaced
with other objects and cloud applications and this architecture allows the implementation of smart
solutions in different markets and with huge benefits for users.
We’ve seen the architecture of an IoT solution, the different telecommunication technologies, and
the security aspects involved.
We have talked about methods to protect your intellectual property against the duplication of your
product and how to adopt open source libraries without the need to release your source code.
Finally, please respect the Arduino trademarks when implementing a commercial solution based on
the Arduino ecosystem.
All this information is necessary to understand how things behind an IoT application work and for
you to consider the right approach for your next IoT solution.
Before stepping into the next chapter, with the first example of an IoT project based on the Arduino
IoT Cloud, it’s worth recapping the main steps to engineer a good IoT solution:
Technical requirements
Before we start, we first need to set up an Arduino IoT Cloud-compatible board. I recommend the Arduino
MKR Wi-Fi 1010, but there is a complete list of compatible boards at https://docs.arduino.
cc/arduino-cloud/getting-started/technical-reference#compatible-
hardware, which you can choose according to your requirements.
Second, you should have an Arduino IoT Cloud account. If you don’t, then sign up at https://
cloud.arduino.cc/ and select a plan according to your requirements.
Third, we need to download and install the Arduino Create Agent. Arduino has created a beautiful
web-based guide for installation at https://create.arduino.cc/getting-started/
plugin/welcome.
The second part of the chapter is related to Node-RED, which will be used for devices that are
not officially supported by the Arduino IoT Cloud such as Raspberry Pi and older versions of
Arduino development boards. Download and install Node-RED according to your operating system
from https://nodered.org/docs/getting-started/local.
Important note
All the Arduino IoT Cloud plans are available on the Arduino IoT Cloud website. You can visit
the following link for updated plans, pricing, and features: https://cloud.arduino.
cc/plans/. If you are from an educational institute, then there are plenty of good plans for
students and faculties. Arduino also offers customized plans to business organizations according
to their requirements.
Most cloud platforms work with the concept of devices and sensors, but in the Arduino IoT Cloud,
we have the concept of the Thing, which includes devices and variables known as sensors/actuators.
You may be thinking that a Thing and a Device are both the same; actually, they’re not. It’s important
to make this distinction because if we do not understand it, then it will create more complications
going forward.
To understand the difference between a Thing and a device, I am going to take an example from real
life. Let’s say we have an empty box. If we put some stuff in that box, it will be a filled box. However,
what if we put the shipping label on that box? Will it still be a box? No, now it’s a parcel. So, we can
understand that a parcel is just a logical container that consists of the box, the stuff in the box, and
the shipping label.
Like the preceding example, a Thing is a logical container that consists of a development board,
variables that act as a bridge between the cloud and sensors/actuators for read/write operations, and
network connectivity that makes the Thing live in an ecosystem (which is like the shipping label in
the box analogy).
Next, we need to understand how device configuration works in relation to the Arduino IoT Cloud.
Here, we are not talking about network connectivity but device configuration. Some cloud platforms
provide Arduino IDE libraries or Software Development Kits (SDKs) for device configuration,
but Arduino has a different, more restrictive system. Firstly, the Arduino IoT Cloud has two ways
for device configuration; the first one uses compatible boards via the Arduino Create Agent (in the
upcoming section, you will dive deep into the Arduino Create Agent) and the second way is through
an API, which is used for non-compatible devices.
So, why does Arduino have this restriction for device connectivity? Arduino cares about security for
IoT devices, and security is as vital in an IoT infrastructure as water is for living beings. Also, not all
the official Arduino development boards are compatible with the Arduino IoT Cloud. You can find
the complete list of Arduino IoT Cloud-compatible devices at https://docs.arduino.cc/
arduino-cloud/getting-started/technical-reference#compatible-hardware.
32 First Look at the Arduino IoT Cloud
The Arduino IoT Cloud directly supports some famous boards besides the Arduino official compatible
boards, which include ESP8266 Series, ESP32 Series, and LoRaWAN Nodes. An API is available for
other development boards, which can be used via any programming language. Later on in this chapter,
we will explain how to use APIs with Node-RED to communicate with the Arduino IoT Cloud.
Finally, which options are available for data visualization and data extraction? The Arduino IoT
Cloud platform provides a variety of options. For data visualization, the platform provides a flexible
dashboard option for both web and mobile, with huge widget features as well as sharing features. For
third-party application integrations, a Representational State Transfer (REST) API and webhooks are
available. For custom application development or custom integrations, Arduino provides JavaScript
and Python SDKs, which enrich the platform’s extensibility. An organization can create custom
dashboard visualization and control panels by using these SDKs.
We have discussed the Arduino IoT Cloud’s main pillars; now it’s time to explore the Arduino IoT
Cloud by implementing basic examples, which will get you started with the Arduino MKR Wi-Fi 1010
development board and the Arduino IoT Cloud.
As the Arduino Web Editor is a web-based tool, there is no way to talk to development boards via a
browser. That’s why the Arduino team developed software for all major operating systems, including
Windows, Linux, and macOS, called the Arduino Create Agent. The Create Agent acts like a bridge
between a device and the Arduino Web Editor. The preceding diagram explains the process in detail.
To get the Create Agent on your machine, visit https://create.arduino.cc/getting-
started/plugin/welcome and follow the steps. After installation, start the Create Agent, as
just installing it is not enough for connectivity. The Create Agent will run as a background process to
provide continuous integration between a device and a browser. The following is a figure that describes
all the options of the Arduino Create Agent:
When we click on the Create Agent icon, it shows the Create Agent version, a Go to Arduino Create
option, and an Open Debug Console option, which is like a serial monitor, where you can execute
different commands to get the status and information about the current process, devices, and ports.
Also from this menu, you can pause/resume the Create Agent, or if you want to close it down properly,
then click on Quit Agent.
Creating a Thing
When you first open the dashboard in the Arduino IoT Cloud (Figure 2.4), you will see menu links
such as Things, Dashboards, Devices, Integrations, and Templates, and the Create your first Thing
message. Just click on the CREATE THING button and your journey will start.
Adding a Thing is totally different compared to other IoT cloud platforms, as the Thing is a combination
of multiple ingredients. The following figure describes all the ingredients of the Thing, such as the
name, cloud variables, device, network settings, code, and Thing metadata:
The Arduino IoT Cloud and the MKR1010 Hello World example 35
All the aspects indicated in the preceding screenshot are explained, step by step, as follows:
1. Assign a name to the Thing; the name should relate to the location and functionality of the
device, which will help you to find the Thing easily in the following wizards.
2. Clicking on Select Device will show you a popup, where you can select the old device or set
up a new device, as discussed in detail in a moment.
3. After attaching the device, we need to make the device network-ready by providing a Wi-Fi
SSID and a password. Just click on the Configure button and you will see the popup for
network settings.
4. Finally, we need to add a variable for the sensors/actuators to perform read/write operations.
The Arduino IoT Cloud provides different types of variables, like the Arduino IDE; the only
difference is that in the Arduino IDE, we declare the variables, whereas here, we need to create
variables via the interface.
In this section, we have created the Thing and named it. Three further steps are required adding a
device, network configuration, and adding cloud variables. We are going to cover the remaining steps
in the following subsections.
36 First Look at the Arduino IoT Cloud
Adding a device
After assigning a name to the Thing, we need to attach a device to it. When you click on the Select
Device button, you will see a popup that shows you an available device and the option to add a new
device. If there is no device, then you will see the following figure to set up a new device:
In our case, we don’t have any device in the portal, so we will just click on SET UP NEW DEVICE to
configure a new device in the account.
Next, you will see the two options in the popup. The first option is Arduino board, and the second
option is Third party device. Here, you will see an icon in front of both names, which means you
need to use compatible devices with the Arduino IoT Cloud. Next, you will see two options: one for
the Arduino official development boards and a second option for the third-party development boards.
The Arduino IoT Cloud and the MKR1010 Hello World example 37
Select one option from the popup according to the available device. For this chapter, we will click on
Arduino board, as in this chapter, we will use the MKR Wi-Fi 1010 board. Before adding the device,
make sure that the Arduino Create Agent is running on your machine.
Important note
You can find the Arduino IoT Cloud-compatible boards at https://store-usa.arduino.
cc/pages/cloud-compatible-boards, and for third-party devices, we have three
options, which are ESP8266, ESP32, and LoRaWAN devices. For some devices, we have API
access, which will be discussed in the second part of this chapter.
38 First Look at the Arduino IoT Cloud
Next, you will see the Setup Device popup, which will start searching for your device. So, make
sure the device is properly connected to your machine. When the Arduino Create Agent detects the
compatible development board device, the following popup will be shown:
The wizard will find and list all the connected boards with their name and port details. Click on the
CONFIGURE button to move forward. If the wizard doesn’t show the device after searching, try to
plug in a different port and click on the refresh link, located at the bottom. After development board
configuration has been taken care of by the Arduino IoT Cloud, you will see a popup where you need
to provide the name of your device:
The Arduino IoT Cloud and the MKR1010 Hello World example 39
In the next configuration wizard, provide the device’s name (note that spaces and special characters
are not allowed in the device name) and then click on the NEXT button.
After that, the wizard will start the device configuration process, which will take up to five minutes.
But in most cases, it only takes one minute to configure the device.
Eventually, you will see a popup with a Congratulations! You are all set message. Click on the Done
button, and the device will be attached to your Thing.
40 First Look at the Arduino IoT Cloud
On the Thing page, you will see the device details, which are marked in the red box in the following figure:
The page shows the device name, the device ID, its type, its status (which is either Online or Offline),
and two buttons, Change and Detach:
• Change is used to switch between devices – for example, if you have chosen the wrong device,
then you can select a different one via this option.
• Detach means removing the device from the Thing. Why might we need to detach? For example,
you may have created a Thing and associated the device with it, but you are now not using that
Thing. If you want to set up a new Thing with that device, the platform will not allow you to
do so if it’s already associated with the old Thing.
Important note
The device and the Thing have a one-to-one relationship. If you want to use a device with a
new Thing, then make sure it’s not associated with another one.
After attaching the device to the Thing, we can see that the device is offline. To bring it online, we
need to provide Wi-Fi details. The following figure represents the network configuration popup, which
only consists of two fields:
On the Thing page shown in Figure 2.5, under the Network tab, click on the CONFIGURE button,
which will take you to the Configure network popup with two fields, Wi-Fi Name and Password.
Type the Wi-Fi SSID and password, and then click on the SAVE button.
In this section, we have configured the network for our device, which is MKR Wi-Fi 1010, and in the
next sub section, we will create the cloud variable.
The final part is adding a cloud variable. Before adding a variable, you have to have an idea of what
type of variables you need for your project, including the variable type, the variable permission,
and the variable update policy.
42 First Look at the Arduino IoT Cloud
For the current example, we need one variable to control the built-in LED, so the variable type will
be Boolean (either on/off):
1. Assign a meaningful name to the variable, related to the sensor/actuator type. Remember that
spaces and special characters are not allowed in the name.
2. If you want to sync the variable with other Things’ variables, then click on the Sync with other
Things option. The sync option is very beneficial if you want to share data across other Things.
Sync will be explained in later chapters alongside a practical demonstration.
The Arduino IoT Cloud and the MKR1010 Hello World example 43
3. Select the variable type from the dropdown; the platform provides dozens of variable types.
For this example, we need a Boolean variable type for LED control.
4. After selecting the variable type, you will see the variable declaration that will be used during
coding. You can see here that our variable name is LED, but the system has converted the first letter
to lowercase and the rest of the characters are left as is, making the name lED. This declaration
part is very important; you can change the declaration according to your requirements, but
keep the declaration in mind, as it will be used in coding.
5. The variable permission provides two options, Read & Write and Read Only. The permission
provides an extra layer of security for the Thing’s control. If a sensor only senses data such as
temperature/humidity, then choose the Read Only option. If you want to control actuators
such as the relay and the LED, then choose the Read & Write option. For our example, we
need to write data to the variable to control the LED, so we will simply choose Read & Write.
6. Finally, we need to choose an update policy according to our requirements. One option is
event-driven (shown onscreen as On change), which only works when there is a change. It
works when prompted by commands such as turning on/off a relay or LED. The second option
is Periodically, which means taking data from a variable, such as temperature, humidity, air
pressure, or a Light Dependent Resistor (LDR) value after a specific time. When you change
the option to Periodically, it will ask you for a time measured in seconds, whereas for On
change, there is a threshold option.
After adding the variable, our Thing now has all the mandatory ingredients. The following figure
describes all the settings and configurations when we are done with the cloud variable, device, and
network settings. Next, we need to jump to the Sketch tab for coding:
The preceding screenshot illustrates the device association, network configuration, and variable
settings, which are essential components of the Thing. Next, click the Sketch tab, where you will open
the Arduino Web Editor for coding. Here, we will add the code that will be associated with the LED
variable. In this section, we have completed all the tasks via drag and drop, but now it’s time to do some
work by putting some coding into our development board. In the next section, we will explore sketches.
Writing a sketch
Most Things are set up in the cloud via a graphical user interface (GUI), but we still need to do some
coding. The following figure describes all the options of the mini web editor, such as verifying and
uploading the code, selecting the development board on specific ports, and the code area for writing
and editing.
The code will associate a variable with physical sensors/actuators to make it work properly. Please
see the following steps:
1. Here, you will see two buttons, like with the Arduino IDE. The tick button is used to verify
code, while the arrow icon button is used to upload the code to the development board.
2. This part shows whether your device is connected to your machine or not. If the development
board is connected, then it will show the device name with the port.
3. The Arduino Cloud Editor has two variants – one is basic and the other is full. In the Thing
tab shown in Figure 2.14, we can see the mini version of the editor, but if you want to move
to the full editor for the installation of libraries or other stuff, then click on the </> button.
4. Scroll down the editor, and at the bottom, you will see the OnLEDChange() function, which
is associated with the LED variable. In this function, we need to write the code that will provide
connectivity to the sensor/physical pins of the development board.
According to our current example project, we just want a turned-on/turned-off, built-in LED for the
development board. The following is the code that will be used in the function:
if(lED==1)
{
digitalWrite(LED_BUILTIN,1);
}else{
digitalWrite(LED_BUILTIN,0);
}
First, let’s recall the declaration used during variable creation, which is shown in Figure 2.12. What
the code does is turn the built-in LED on if the lED variable contains a true value; otherwise, it turns
the built-in LED off.
To write Boolean values on development board pins, we have a method called digitalWrite,
which takes two parameters. The first parameter is a pin number and in the second parameter we will
place true/false or 1/0, while we are using LED_BUILTIN, which is a constant and contains PIN
#13. The second parameter is a value, which is either 1 or 0. This parameter changes according to the
lED variable state. Here we are done with our coding exercise. Now it’s time to create a graphical user
interface from where we turn on/off the LED. In the following section, we will set up the dashboard
to control the LED.
46 First Look at the Arduino IoT Cloud
Click on the button, and you will be taken to the dashboard builder page to create a new stunning
dashboard for your device control, as follows:
1. The dashboard has two modes, view and editing. By default, it’s on editing mode, which is
denoted by an edit icon, and we can switch to view mode by clicking on the eye icon. In view
mode, we can’t modify the widget’s settings and alignment.
2. To add controls on the dashboard, click on the green ADD button, and a drop-down menu
will appear with a variety of widgets. Here, you can select a widget by scrolling or searching.
3. This button is used to arrange the widgets. During editing, you are not able to navigate, resize,
or move the widget controls.
4. As mobile icon is representing it’s working from its icon, this means by click on this icon you
can adjust your dashboard for mobile devices. Arduino provides both views of the dashboard
for desktop and mobile. You can switch between them by clicking on the mobile/desktop icon.
5. In the textbox, type the dashboard name.
The Arduino IoT Cloud and the MKR1010 Hello World example 47
Now that we have created the dashboard, it’s time to put a widget on it. Widgets will help us to control/
view the sensors/actuators. When you click on the Add button, you will see the list of widgets. Here
you can select a widget by scrolling through the list or by searching the widgets via the search bar, as
shown in the following figure:
Select the Switch widget control for the current example project. After selecting the widget control,
a popup will appear, where we need to link the Thing variable with the widget control to read/write
the data to the device sensors. This is because the variable is the bridge between the dashboard widget
controls and the Thing sensors to read and write data.
48 First Look at the Arduino IoT Cloud
In the widget popup, we have different settings, as shown in the following figure:
1. Firstly, we need to assign a name to our widget. Make sure to give it a proper name that represents
the sensor’s name. Here, I used the name LED-Switch.
2. Hide or show the widget frame content, which is at the top and bottom of the widget.
3. Click on Link Variable to attach the Thing variable to the widget control, which will be
explained in the next figure.
4. Hide/show the widget label to hide the text that overlays the widget control. In the preceding
figure, it switches the ON/OFF button text.
The Arduino IoT Cloud and the MKR1010 Hello World example 49
It’s time to attach the widget control to the variables. Note that we can add multiple controls on the
same dashboard that are linked to different Things’ variables, which shows the versatility of Arduino
IoT Cloud dashboards, as shown in the following figure:
As shown in Figure 2.18, we have the following steps to assign the cloud variable to the widget control:
1. Select a Thing from the Things list. After selecting the Thing, it will show you the variables
that are associated with that Thing.
2. Select a variable from the Variables list.
3. Here, you will see all the details of the variables, such as the Thing name, Type, Last value,
Permission, Update policy, and Last update. The purpose of this detailed summary is to make
sure to verify that you have attached the right variable to the widget control.
After selecting the variable from the specific Thing, click on the LINK VARIABLE button, and you
will see the variable details in the widget control popup. From there, you can change or detach the
variable. Finally, click on the DONE button; now, our dashboard is ready, with a widget control to
send commands to the Thing. Just click on the eye icon on the dashboard to make it operational. After
that, start testing the dashboard controls.
Here we are done with our first example project with Arduino MKR1010 and the Arduino IoT Cloud.
Next, you need to solve Assignment 1 of this section. After that, you will jump into the second section
of this chapter, where you will learn how to use the Arduino IoT Cloud with non-compatible devices,
such as Arduino Uno, Raspberry Pi, and so on via Node-RED.
50 First Look at the Arduino IoT Cloud
Assignment 1
Congratulations! You have completed the first part of this chapter successfully, and I hope you enjoyed
that journey. Now, it’s time to verify what you have learned so far by giving you a small assignment:
1. Attach three differently colored LEDs of any color (preferably, red, yellow, and green) to the
Arduino MKR1010 development board on pin numbers 1, 2, and 3, respectively.
2. Set up a new Thing with the name IoT-Based Traffic Lights Control.
3. Associate the device, configure its network settings, and create variables according to the number
of LEDs. Variable names should be based on LED colors such as LED_Red.
4. Write the code that will turn the LED on/off according to the variable value. After writing the
code for each LED, verify and upload the code to the development board.
5. Finally, set up the dashboard with the name Traffic Light Control Dashboard.
6. Add the Switch buttons according to the number of LEDs, and link them with their
associated variables.
7. Test the LEDs by switching them on/off via a dashboard.
Important note
Try the Push Button widget control along with the Switch button widget control. Verify whether
one variable allows you to connect with more than one widget. Also, verify the behavior of the
Push Button widget control by turning the Switch button on/off.
Our world is full of different types of technologies. Whenever a new innovation comes on the market,
it always provides compatibility with older devices. In the Arduino IoT Cloud, we have a list of
devices that are currently supported, but there are millions of devices that are not compatible with
the Arduino IoT Cloud. So, while in the previous section of the chapter, we practiced an example
with Arduino IoT Cloud-compatible development boards, next, we are going to look at how we can
connect/use non-compatible devices with the Arduino IoT Cloud, such as Arduino UNO, Raspberry
Pi, BeagleBone, and so on.
Introducing Node-RED
Node-RED is a free, open source visual programming tool for IoT and other applications. It was
developed by IBM Emerging Technology and was first released in 2013. Node-RED provides a
web-based interface to wire together hardware devices, APIs, and online services in new and interesting
ways. The tool uses a graphical flow-based programming language, making it easy for users with
little or no programming experience to build complex IoT systems. Node-RED has become popular
in the IoT and smart home communities for its ease of use and ability to integrate with a wide range
of devices and services.
Introducing Node-RED 51
Node-RED is a flow-based development tool for IoT and other applications. It provides a visual, drag-
and-drop interface to connect different devices, APIs, and online services. With Node-RED, users can
wire together inputs, outputs, and functions to create sophisticated IoT solutions. As well as being open
source and free to use, Node-RED has a large user community and a library of pre-built components.
With all Node-RED’s aforementioned benefits, the following question arises: why do we need to use the
Arduino IoT Cloud? At the start of the chapter, I mentioned that the Arduino IoT Cloud only supports
a few development boards natively. Even Arduino doesn’t support all of their development boards,
especially Arduino UNO, Arduino Mega, and Raspberry Pi from the Raspberry Pi Foundation, which
are very famous among makers and hobbyists and used by industry. The solution to this is Node-RED,
which is compatible with most development boards and has an Arduino IoT Cloud module, making
it easier for developers to integrate non-compatible devices with the Arduino IoT Cloud.
Node-RED can be used with the Arduino IoT Cloud with several benefits:
• Ease of development: Node-RED’s visual, drag-and-drop interface makes it easy for users to
connect Arduino boards to the cloud and build IoT applications quickly
• Integration with the Arduino IoT Cloud: Node-RED has built-in support for the Arduino
IoT Cloud, allowing users to easily connect their Arduino boards, as well as other development
boards, and send data to the cloud
• Flexibility: The flow-based programming model of Node-RED makes it easy to build and
modify complex systems
• Flow-based programming: Node-RED’s flow-based programming model is well suited to
building IoT applications, as it allows users to quickly connect inputs, outputs, and functions
to create sophisticated systems
• Open source: Node-RED is open source, allowing users to access the source code and make
modifications if necessary
• Large user community: Node-RED has a large and active user community, providing access
to a wealth of information and pre-built components
These benefits make Node-RED a good choice for developing Arduino-based IoT applications and
connecting them to the cloud. By using Node-RED, users can leverage the power of the cloud to store,
analyze, and visualize data from their IoT systems. In this section, we have discussed the features and
benefits of Node-RED. Now it’s time to take a practical look by implementing the example project.
The following sections will take you through the implementation of the project step by step.
52 First Look at the Arduino IoT Cloud
1. These colorful boxes are called nodes. Node-RED divides different types of nodes into different
groups, such as common and function.
2. This is the working area, or canvas area, where you will drag and place the nodes.
3. The debug area is used to debug the output and input of different operations to verify that
everything is working fine.
4. Just like in other development environments, we can execute/run a program using the Deploy
option. Deploy has different options; if you click on the small downward arrow icon, you will
get a list of options, such as Full, Modified Flows, Modified Nodes, and Restart Flows.
5. The hamburger icon at the top right is the main navigation button, where you can find all the
options to control the Node-RED configuration, especially for the installation of modules. In
our case, we will install the Arduino IoT Cloud module.
54 First Look at the Arduino IoT Cloud
Here we have discussed the interface of Node-RED with all the main options. In the following section,
we will look at how to install the Arduino IoT Cloud module for Node-RED, and in the subsequent
sections, we will see its implementation.
Now that we have installed the module, it’s time to have a look at what type of nodes are available
in the Arduino IoT Cloud module. Close the installation palette, scroll down through the nodes to
the bottom, and you will arrive at the Arduino IoT Cloud section, as shown in the following figure:
1. The first one is an IN node (in Node-RED, we have nodes; that’s why I used the word node
instead of property to get the value from the Thing property/variable).
2. The second is an OUT node, used to write the value to the Thing property/variable.
3. The third is the historic node, which is used to get data from a specific property until a specific
time. This node is useful when you want to get the set of values for a specific sensor, such
as temperature/humidity.
4. The fourth is periodic and is useful when you want to get the value of a specific property after
a specific period of time, such as getting the value of soil moisture after a specific time interval.
56 First Look at the Arduino IoT Cloud
5. The fifth, which is our last node, is inject. This is used to add value to the flow of the Arduino
IoT Cloud variables after receiving some sort of input. OUT is different, as it only sends out
data, but this node will inject the value into the Arduino IoT Cloud variable.
In this section, we have discussed the nodes to work with the Arduino IoT Cloud, that are available
to developers from the Arduino IoT Cloud module. Next, we will set up the API, cloud variables, and
dashboard to proceed further.
Copy the client ID and client secret by clicking on the copy icons; never try to copy the secret name by
selecting it, as it is too long. Save both the client ID and client secret to secure the location, and after
that, click on the checkbox beside I saved my Client ID and Secret to confirm that you have saved
your keys. Finally, click on the DONE button, and you will see your API key in the panel, ready for use.
Important note
One API key has access to all the Things and their variables. So, it’s good to use one API key
to gain access to all Things instead of creating separate API keys for each one. On the other
hand, take care of your keys, as losing them can be a big security risk.
After API key generation, we need to set up an extra variable that will receive the value from Node-
RED, and a Status widget that will act according to the variable value.
For variable creation, go back to the IoT Cloud dashboard shown in Figure 2.12, select the desired
Thing, create a new variable named LEDStatus, and choose the Boolean type that we previously
created for the LED. Then, navigate back to the dashboard and select the dashboard that we developed
for the previous exercise. Click on the Add button and search for the Status widget from the dropdown.
Link the LEDStatus variable with the Status widget.
Here we have created the API keys in the Arduino IoT Cloud for Node-RED, as well as a new Thing
with cloud variables and a dashboard. Next, we are going to configure the API keys in Node-RED for
proper communication with the Arduino IoT Cloud.
1. Select the Arduino connection from the dropdown (the dropdown is only there if you have
multiple Arduino IoT Cloud connections).
2. If you don’t have a connection, click on the pencil icon, and it will take you to a new popup
where you will need to provide the name of the connection, along with the client ID and client
secret that were generated in the previous section in Figure 2.22. When you save the connection,
it will appear under the Connection dropdown.
3. After successfully creating and selecting a connection, a list of Things that are associated with
that connection will appear. From the Thing dropdown, select the target Thing that you will
use in your flow. If you do not see anything in the dropdown, it means there is an issue with
the connection.
4. After the selection of Thing, the Property dropdown will list all the variables that are associated
with the selected Thing. Select one variable that you want to sense; in our exercise, I chose the
LED variable to get its status.
5. Assign a name to the node, click on the Done button, and then you are done with the configuration.
The Arduino IoT Cloud and a Node-RED Hello World example 59
The following is a complete flow of nodes. It shows the entire workflow, from getting variable values
to the final node, which sends a value to the cloud based on input:
1. The first node is the IN node. Select the variable that you want to read; I selected the LED variable.
2. Add the switch node (node 2) to the flow; it can be found in the Functions tab on the left
sidebar of the page. This node is responsible for taking the value from node 1 and selecting
the specific node from 3 or 4, according to the value. Link the Arduino IN node to the switch
node. After linking, double-click on the switch node, where we need to specify the switch cases.
60 First Look at the Arduino IoT Cloud
1. Firstly, assign a name to the node and then add the switch cases.
2. In our current exercise, we have two switch statements: the LED is either true or false, which
means on or off. By default, there is only one option – click on the small +add button to insert
a new case. Input the values 1 and 0, and we will then have two flows.
The change nodes (3 and 4) are responsible for sending content to the next node, which is 5. Drag 3
and link it with the switch node, as shown in Figure 2.24. Node 3 represents the True/1/On value.
Double-click on this node. Now, click on the drop-down icon, which is marked by a red box in the
following figure, select the Boolean type, and then select true.
The Arduino IoT Cloud and a Node-RED Hello World example 61
1. Again, insert the change node and link it with the switch node (node 4) shown in Figure 2.24.
This will represent the False/0/Off value. Double-click the change node, select the Boolean
data type, and select the false value.
2. Everything is ready now. We just need to add a node that will send data to a specific Arduino
IoT Cloud Thing variable. To send the data, we need the Arduino OUT node, which is the
second node under the Arduino IoT Cloud tab shown in Figure 2.21. Drag this node, and
connect both change nodes (3 and 4) to the Arduino OUT node (5) as shown in Figure 2.24.
This node has the same configuration as the IN node. Select the connection, then the Thing,
and finally, select the variable where you want to send the data. For the current exercise, we
will select the LEDStatus variable.
Finally, we are done with all the node configurations and linkage. Click on the Deploy button shown
in Figure 2.19 and move back to the device dashboard in the Arduino IoT Cloud. Remember to keep
MKR1010 on and connected to the internet. Now, click on the switch button to turn the LED on/off,
and wait for a few seconds to get an updated value from Node-RED. In the background, Node-RED
will send the value to the LEDStatus Arduino IoT Cloud variable according to the Node-RED LED
variable, and the status widget will be changed accordingly.
In the second part of the chapter, we have explored how to connect non-compatible IoT development
boards with the Arduino IoT Cloud using Node-RED. Next up is Assignment 2, which is specially
designed for you to practice with different experiments.
62 First Look at the Arduino IoT Cloud
Assignment 2
Continue the previous assignment, where you connected three LEDs to MKR Wi-Fi 1010 and the
Arduino IoT Cloud setup:
1. Create three status variables in the Thing, according to the LED name such as Red, Yellow and
Green, to the previously-set-up Thing.
2. Add three status widgets to the previously-set-up dashboard and attach newly created status
variables to them.
3. Set up three different flows for each LED and deploy the flows.
4. Verify the status widgets by turning the LEDs on/off with the Switch button widget.
Summary
This chapter is the first chapter where we explored how to connect devices with the Arduino IoT
Cloud using a basic LED on/off example. In the first part, we used an Arduino IoT Cloud-compatible
development board, which was the MKR Wi-Fi 1010 board, where we learned how to create Things
and cloud variables, how to associate devices, how to configure networks, and how to create sketches.
At the end of that section, there was an assignment for you to practice on.
In the second part of this chapter, we explored how to connect non-compatible development boards,
such as Arduino UNO, Arduino Mega, and Raspberry Pi, with the Arduino IoT Cloud, using Node-
RED and the Arduino API interface. Here we have explored Node-RED, the Node-RED module for
the Arduino IoT Cloud, and generating API keys in the cloud. This part of the chapter helped teach
you how to use non-compatible existing technologies with the Arduino IoT Cloud.
Arduino has a lot of options in the Arduino IoT Cloud, such as Things, devices, dashboards, and a
lot of widgets for dashboards and the Arduino Web Editor. So, in the next chapter, we will explore all
those options in detail before moving on. Chapter 3 is very important for you to better understand
all of the Arduino IoT Cloud options.
3
Insights into the Arduino
IoT Cloud Platform
and Web Editor
Before getting started with any development or cloud platform, it’s important to get a broad idea about
the platform’s functionality, including its functions, controls, widgets, and so on. These platforms are
like a kitchen full of spices, vegetables, meat, and other ingredients. To cook a good meal in a new
kitchen, you need to get an idea about what’s in the kitchen – what types of tools, ingredients, spices,
and other stuff are available. Product development is just like cooking a meal – if you have a good
idea about what the platform provides, then you will be able to develop an awesome project. Another
benefit of getting an overview of a platform is that it will save your time in the long run and give you
confidence in your product design, because you already have a good understanding of the platform
and can combine different things logically to develop something new according to your requirements.
So, in this chapter, we will first cover the main ingredients of the Arduino IoT Cloud in detail, namely
Things, devices, dashboards, integrations, and templates. In the next part, we will take a look at
all the dashboard input/output widgets and will see in detail what their purposes are, where to use
them, and what type of variables they support. We will also have a brief comparison between some
different control widgets that resemble each other.
In the last part, we will cover the complete Arduino Web Editor functionality, learning how to import
new libraries, what the Web Editor storage and memory limits are, how to share your code with others,
and how to debug code with the cloud-based Serial Monitor.
In this chapter, we will cover the following topics:
Technical requirements
For this chapter only, Arduino IoT Cloud access is required to explore the different functionalities
and dashboard control widgets we’ll cover in this chapter.
Things, devices, and dashboards are highly coupled with each other in every project. For example, for
even a small project, we require a Thing and a device to get onboard the cloud platform. Is it enough
to just configure a Thing and a device? No – a dashboard is also mandatory, from which the user can
give input to the Thing and over which the system can show Thing data for user visualization.
However, integrations are a more optional component, with use cases varying from project to project
and only being used by developers when they want to connect any non-compatible device to the
Arduino IoT Cloud, build a custom interface to fetch data from the Arduino IoT Cloud, or integrate
with third-party services such as Zapier and AWS services.
Introducing the Arduino IoT Cloud interface 65
Templates are good for beginners as well as geeks, providing ready-made generic projects, including
documentation, code, cloud templates, and a list of the hardware used in a given project. By using
these templates, you can expose yourself to new things, which is good for learning purposes.
Here, we have discussed the Arduino IoT Cloud’s key interface components. In the following section,
we will discuss all the components in detail step by step. This chapter is very important with respect
to all Arduino IoT Cloud features.
Important note
A device is only attachable to one Thing in a one-to-one relationship. If you want to use a device
associated with any other Thing, then it’s mandatory to detach the device from the previously
associated Thing before associating it with a new Thing.
The concept of a Thing is a bit like a dish containing pieces of steak, veggies, mashed potato, and so on.
A Thing holds cloud variables, network connectivity, and the device, and is it responsible for managing
code and metadata, such as the device time zone and the meta tags for the Thing.
Now, it’s time to explore Things more closely in the Arduino IoT Cloud. The following diagram
summarizes the whole Thing interface:
Let’s start by exploring the Thing main page (shown in Figure 2.4 in Chapter 2) by clicking on Thing
menu, which is very similar to the menu for devices but with a few differences in the Search and Thing
table list. We can see a CREATE button for Thing creation, instead of ADD as there is for devices. The
search functionality for Things has totally different filters compared to those for devices, allowing us
to filter Things by Device, Device Type, and Time Zone.
As the relationship between devices and Things is a one-to-one relationship, it will show you only one
Thing, but Device Type is a good feature to show a whole bunch of Things with a particular device
type. For example, let’s say we have deployed two different projects, and each project contains 25
nodes. One project was developed by MKR Wi-Fi 1010, while the other was developed by ESP32.
The Device Type filter provides you with the option to filter down the Things to just those using the
ESP32 board type. The third filter is Time Zone, which is very beneficial if you have projects deployed
in different regions across the world. To return the devices in specific regions, you can simply use
this Time Zone filter.
Introducing the Arduino IoT Cloud interface 67
By default, the Thing list table provides us with a list of Things with their Device, Variables, and Last
Modified properties. We can rearrange the list by any property in ascending or descending order by
clicking on the property column. The Thing option menu provides us options to delete the Thing.
In the device property, it shows either the associated device or gives you the option to associate a
device. The Last modified property is good for auditing purposes and indicates the last time your
Thing was modified.
Besides all of these properties, we have some hidden properties, Creation Date and Time Zone, that
can be enabled via the Table Settings icon, located on the right side of the page. If we add meta tags
to the Thing, then this will also appear under Table Settings. Meta tags will be covered in more detail
in the following few paragraphs.
It’s time to explore the internal options for Things (Figure 2.5 from Chapter 2). Click on the CREATE
button or click on any Thing from the table. On the page that appears, you will see three different
tabs, Setup, Sketch, and Metadata, along with the Thing name in bold font. You can also modify the
Thing name by clicking on it.
The Setup tab is used for cloud variable creation and associating devices with Things (if not already
linked). The Change/Detach Device option is available for devices associated with the Thing. Finally,
there is the option to configure the Wi-Fi network settings for the development board.
The second tab is Sketch, which provides a mini version of the Arduino Web Editor, from where we
can write/modify code as well as verify and upload it to the associated device. I like the Sketch option
for Things, as it helps us to maintain the code for each device within a separate Thing container, with
no need for local backups or code management. The mini cloud editor also provides the option to
open the full editor. Beside that is the search icon, which opens the web-based Serial Monitor to verify
whether your device is working.
The third tab is for Thing metadata. Normally, people don’t concern themselves with these settings,
but they are used to classify and provide ease of management when you have dozens of Things. Here,
we can add tags to classify our Things. Tags also appear in the Thing table list, as well as in the search
bar as a filter option. So, let’s see how tags work. A tag consists of two parts – one is the key and the
other is a value. The key is used in search filters. For example, if you have dozens of devices for different
organizations and each organization contains multiple devices, then how you can filter the specific
organization devices? The answer is by tag; you create a tag, where the key will be the organization
name and the value will be the type of device. When you type the organization name in the search
bar, you will see all the devices that are associated with these meta tags. The next option is the time
zone, which is the perfect option to get Thing data according to the time zone of its native region. By
default, it shows the time zone according to your location, but you can manually override the time
zone. Resetting it will show some details regarding the Thing, such as Thing ID, Last Modified, Last
Sync, and Created At.
At this point, the following question arises: What is the difference between Last Modified and Last Sync?
I recommend that you have a think and find a solution to it before you proceed.
68 Insights into the Arduino IoT Cloud Platform and Web Editor
Important note
Let’s imagine you have written the code for a Thing and it is associated with an MKR Wi-Fi
1010 device, but you have changed the association of the device to Arduino Nano RP2040
or any other development board. In this scenario, you will get the prewritten code for the
RP2040. You will get this code, as the code belongs to the Thing, not the device. However, it
may require some minor modifications in code, as pins and libraries vary from development
board to development board.
In this section, we discussed the device and Thing pages in detail, regarding search options, creations,
and other options on the pages. Now, we will discuss dashboards, which will help us to create beautiful
graphical user interfaces to control and display device data.
Dashboards
The Arduino IoT Cloud offers very versatile dashboards with lots of options, providing an awesome
experience for users. Dashboards consist of different features, including widgets, which are categorized
into input and output, responsive design options for mobile and web, and lots of other features. The
following figure summarizes all the features of a dashboard, which will be discussed in detail step by
step in the following sections:
The dashboard interface is very similar to Thing and device interfaces, but it’s simpler in terms of
search and tables. Let’s now examine input/output widgets in the context of the IoT Cloud but not in
terms of devices (although devices are relevant, as if we provide input to the IoT cloud, it will, in turn,
provide input to the Thing, and if a device sends output data to the IoT cloud, it will be displayed on
the dashboard).
Introducing the Arduino IoT Cloud interface 69
Arduino IoT dashboards provide a wide variety of widget controls for input/output. We will examine
all of the widgets in detail later, while here, we will discuss some other major features, such as responsive
design and sharing and downloading data.
Dashboards provide a responsive grid design system for both mobile/web. To enter into editing
mode, firstly click on the Edit icon on the Dashboard page (Figure 2.15 in Chapter 2) and then on
the Navigation icon, which is also known as Arrange Widgets. You can modify the design by making
widgets larger or smaller, or by dragging them to any location on the canvas. You should see the Lock
icon on every widget control as well, which lets you fix their locations. After placing the widget at
the appropriate location, click on that lock to fix the position. In the top menu near the Add button,
there is an icon for mobile/desktop mode to align the widgets.
There will come a time when you need to share these dashboards with your stakeholders so that
they can monitor their systems easily. The Arduino IoT Cloud provides a secure way to share your
dashboard with others. Just click on the Sharing icon – from there, we can share our dashboard with
other users (although note that it’s mandatory that all users’ emails need to be registered with the
Arduino IoT Cloud to take part in sharing).
Getting sensor data from the cloud is an essential element of IoT cloud platforms, as researchers use
data in a variety of applications, including training Machine Learning/Artificial Intelligence (ML/
AI) models or visualizing data on different platforms, such as Google Looker and Tableau. Arduino
provides a vast functionality wizard to download all data or the specific data of a given cloud variable.
Click on the Download icon, and you will get a lot of options. From there, you can select the variables
(either single, multiple, or all, according to your requirements) and provide the date range. Arduino
will then process the data according to your query and share it with you in the CSV format at your
registered email.
Here, we have talked about different features of dashboards, such as the alignment of widgets, responsive
design for mobile and web dashboards, and how to download sensor data. In the following section,
we will cover integrations and templates.
First, let’s talk about APIs, as this technique is widely used by developers to interact with different
platforms. In the Arduino IoT Cloud, APIs are used for two purposes – the first purpose is to set up
a non-compatible device with the IoT Cloud, including Raspberry Pi and Beagle Bone, while the
second purpose is to fetch data from the IoT Cloud using different predefined APIs. These APIs will
be discussed in detail in Chapter 8.
Webhooks are used as triggers when a specified event happens in a Thing, such as an update in the
cloud variables. To set up a Webhook, you need to visit the specific Thing’s page, click on Set Webhook
at the bottom, and assign a URL where you want to send the Thing data. Makers and developers mostly
use IFTTT or Zapier to receive data and route it to tons of other applications/platforms. Webhooks
send the data in the JSON format with lots of details, which will be discussed further in Chapter 12.
It’s very important to understand the concepts behind APIs and Webhooks. Third-party applications
use an API’s interface to request data from the cloud, but with Webhooks, the Arduino IoT Cloud
sends the data to a specific platform when any predetermined event happens within the Thing. So,
if you develop an alert system, then Webhooks are the preferred choice, as they send data instantly
when any change is detected within the Thing. Conversely, if you develop an application where you
only need data periodically, then APIs are the best solution. To put it simply, Webhooks work like
push requests and APIs work like pull requests.
The Arduino IoT Cloud team has also released official SDKs for different programming languages,
such as JavaScript (Node.js), Python, and GoLang. SDKs make development easy for developers
by allowing them to use predefined functions to get data from the cloud, instead of playing with raw
APIs. For authentication purposes, SDKs use API keys for access and authentication. The Node.js
SDK will be discussed in detail in Chapter 8.
Exploring input controls 71
In this section, we discussed APIs, SDKs, and Webhooks. Now, we will explore a dashboard’s widget
controls. We have divided Arduino Dashboard widget controls into two categories, input and output. In
the following section, we will first explore the complete range of input controls, and in the subsequent
section, we will explore the complete range of output controls.
Switch and Push Button work on the same binary principle (on/off) and consume the Boolean
type cloud variable. The only difference between these two controls is the UI/UX design. When the
user clicks the switch control, it slides on/off and stays in the same state until clicked again. Push
Button also retains its state but is pressed in or out to change between on/off states.
72 Insights into the Arduino IoT Cloud Platform and Web Editor
Important note
To understand the proper working of Switch and Push Button, just place both controls on
a dashboard and link them to the same cloud variable. Afterward, click on Push Button and
release it, and then try clicking on the switch.
The Slider and Stepper controls both work in the same manner but are totally different in UI/UX
design. The slider uses a simple slide to change values, while the stepper has an input control where
a user can directly insert a specific number, as well as increment and decrement buttons. The Slider
orientation is horizontal by default but can be changed to a vertical orientation. Both controls can
be linked with the integer or float-type cloud variables. These controls are useful to control
stepper motor angles, the speed of motors, and light intensity, or even to set the threshold for an
alert system for temperature and humidity monitoring. For example, say you want to set an alarm
threshold for temperature and humidity values, and also the weather. These controls will help you to
get values from the stakeholder via the dashboard and process them in the Thing, without needing
to modify the Thing code.
Here, we explored four different input widget controls, Switch, Push Button, Slider, and Stepper,
and their uses in detail. Now, we are going to cover input widget controls related to light control.
Here, we have seen all the widget controls regarding light/bulb control; now, we will discuss all the
widgets, step by step, in the upcoming subsections. First, we will start with the Color widget control.
Exploring input controls 73
Color
Our first widget here is the Color widget. This widget works with the Color type cloud variable,
for which we fetch the Red Green Blue (RGB) color values with Arduino code for the final device
input. The color widget provides an RGB slider to adjust the color, or the desired value can be directly
entered in the RGB or hex formats. This widget is very useful to control RGB LED colors, RGB lamps,
and the WS18B20 module.
The following code snippet for the Arduino IDE or the Web Editor shows how to convert the color
type cloud variable into RGB variables:
RGBVariable is a cloud variable of the Color type. We have to use the RGB format to input our
color codes into RGB LEDs, and for that reason, we will declare three integer type variables, red,
green, and blue, and use RGBVariable.getValue().getRGB(red, green, blue);
to convert our single cloud variable value into the RGB format.
Dimmed light
The Dimmed light widget, as shown in Figure 3.6, provides us the ability to turn a light on/off as well
as control the intensity of the light. This widget is useful if you have a single-color bulb/light strip
and want to control its luminous intensity. It consumes the Dimmed Light cloud variable, which
contains the switch status and brightness values.
Before moving to the code, we first need to understand what values are required by the development
board. Two values are required here – the on/off status and the light brightness level. The following
code shows how we get the brightness level and on/off status from the Dimmed Light cloud variable:
To get the brightness, we need to transform the dimmedLightVariable brightness property value
into the 0–255 range, using the map function. Then, we need to get the on/off status by calling the
getSwitch property of that cloud variable. If it’s on, then we will use the analogWrite function
on Pin #5 to adjust the brightness; if the switch is off, the LED/lamp will be turned off.
Colored light
Finally, it’s time to play with colorful strips with the Colored light widget, as shown in Figure 3.6.
This widget provides three functionalities, two of which resemble the Dimmed light widget (an on/
off switch and a luminous intensity control), while the third is a color selection option via a color
palette. This widget works with the Colored Light cloud variable type.
The following code for the Arduino IDE/Web Editor fetches values from the Colored Light variable
type. Before diving into the code, note that we need to get three values from that cloud variable – the
RGB color, brightness level, and on/off status:
Firstly, we fetch the RGB color value in the int format by using the ColoredLightVariable.
getValue().getRGB method. Second, we fetch the brightness using the ColoredLightVariable.
getBrightness() method and transform the values with the map method. Finally, we fetch the
on/off status with the ColoredLightVariable.getSwitch() method. All the values are
stored in three different variables that could be used to control LED/lamp or RGB strip functionality.
Here, we discussed in detail smart light/bulb controls, which contain Color, Dimmed light, and
Colored light widget controls, including their code to fetch and set the values from them. Now, we
will discuss another important input control, time picker, which is used for configuration.
The following screenshot shows the Time Picker widget with the date and time, and you have the
option to set the date, the time, or both. The widget also gives you the ability to change the date and
time format according to your region.
The time picker widget is linked to the Time type cloud variable and stores all date and time data in the
seconds format. The following code takes the local time from Arduino Cloud and stores it in a variable:
CloudTimeVariable = ArduinoCloud.getLocalTime();
After fetching the local time, you can use CloudTimeVariable to sync your Thing operations.
Use the preceding code in the setup method.
In this section, we discussed the time picker widget, including how to set the time for this widget control
by using the Time cloud variable type. Now, we will discuss another configuration widget control, the
Scheduler Widget control, which helps you set the time to automate your operations on IoT devices.
Scheduler (configuration)
Scheduler is another important utility in Arduino IoT Cloud to automate a process. With this widget,
we can automate lots of operations without human intervention, just like a cron job that executes
processes/methods at a specific time.
So, where we can use this Scheduler feature in our IoT solutions? There are many use cases, including
outdoor light automation, watering systems in agriculture, and animal feeders for poultry farms.
76 Insights into the Arduino IoT Cloud Platform and Web Editor
The following screenshot of the Scheduler widget shows the many options to schedule
our processes/methods:
The Scheduler Widget uses the Schedule cloud variable type. When configuring it, we specify at
what time and on which day we want the process to start and end.
The following code snippet is very simple, using a true/false interface to start/stop operations,
respectively, instead of going into complex stuff:
if (scheduleVariable.isActive()) {
digitalWrite(LED, HIGH); // whenever the job is "active", turn on
the LED
}
else{
digitalWrite(LED, LOW); // whenever the job is "not active", turn
off the LED
}
We can get the active/not active status of every Schedule cloud variable by accessing its isActive()
method. Use the aforementioned code in a device loop – if the Schedule cloud variable is active,
then execute the given processes/methods; otherwise, stop them. Why do we need to execute the
preceding code snippet in a loop? Because the loop() method is the main method in Arduino,
which always executes.
Delving into output controls 77
In this section, we discussed Scheduler in detail, what type of cloud variable is used by this widget, and
how to access the Scheduler status to perform a specific job. This is the last control in input widgets.
Now, we will look at the output control widgets. In the following section, all the output controls will
be discussed in detail to give you a better understanding of how to implement these controls in your
professional projects.
Figure 3.9 – The Value, Status, LED, Gauge, and Percentage widgets
78 Insights into the Arduino IoT Cloud Platform and Web Editor
In this section, we will discuss in detail five different output widget controls in separate sections. First,
we will start with the value widget control.
Value
The value widget is a very basic and important widget that is widely used in projects to display sensor/
actuator values, such as temperature or humidity, or to write some numeric values to sensors/actuators.
This widget can be linked with the integer type variables, but I also tested it with the time variable,
and it worked fine, as the time variable stores all information in seconds. You can also use the value
widget control to set thresholds for sensors, automating the process flow.
The following simple code snippet takes the value from analog pin #0 and stores it
in valueCloudVariable:
valueCloudVariable = analogRead(A0);
Here, we discussed the value widget control, which is used for both input and output purposes. Now,
we will explore the status and LED control widgets.
Our next widgets are status and LED, as shown in Figure 3.9. Both widgets work very similarly but
are different in UI/UX. These widgets have only two states to display either true or false. These
widgets only display the state; they don’t provide any option to control them, and they both work with
the bool type cloud variable. Use cases for these widgets include indicating the Thing status (on/
off) – for example, a water pump’s status in smart agriculture, or whether a door is open or closed in
a smart home. Just assign true/false to the bool cloud variable type, which is linked to the status
widget after performing a specific task.
The following example code demonstrates how we can change the value of statusCloudVariable
to change the status/LED widgets’ appearance:
Void loop(){
digitalWrite(1,HIGH);
statusCloudVariable=true; //Assign true to Status Widget
delay(5000);
digitalWrite(1,LOW);
statusCloudVariable=false;//Assign false to Status Widget
delay(500);
}
The preceding code shows how, after performing the digitalWrite operation, we change the
value of statusCloudVariable according to the current condition to update the status widget.
Delving into output controls 79
Finally, we have the gauge and percentage widgets shown in Figure 3.9, which can be used to make
your dashboard spicy and provide a stunning information display experience to your users. Both of
these widgets can be linked to the integer or float cloud variable types. Comparing the gauge
and percentage widgets, we can see a clear difference in UI/UX design – gauge uses a half-circle to
display a sensor reading, while the percentage widget uses a full circle featuring icons, for which you
can specify the color if a value goes below or above a given threshold. However, the working of both
widgets is essentially the same. Gauge can be used to display gas-related readings, such as air quality,
carbon dioxide levels, and temperature, while the percentage widget is best for displaying humidity,
battery level, Light-Dependent Resistor (LDR) values, and so on.
Here, I haven’t provided the sample code for the gauge and percentage widgets, as it’s very similar
to the preceding example – just assign the values of the sensors to the gauge- and percentage-linked
cloud variables.
Important note
As a little exercise, create an integer type variable named MultiDimmVariable, and drop
a gauge, percentage, and slider widget on the dashboard. Link these three widgets with the
same MultiDimmVariable cloud variable you created. Now, you can have a bit of fun; just
change the slider position and see how the gauge and percentage widgets react.
In this section, we discussed all the major output controls, which include value, status, gauge, percentage,
and LED, step by step, and their usage and code. Now, we will look at maps and charts widgets, which
are the most important widgets to display for location and time-series data.
First, we will start with the map widget, where we will discuss how we can display the location, and
then, we will explore the chart widget to display the historical data of a sensor.
Map
There are many use cases where we need to display the current location of an object on a map, which
is much easier to understand visually than simple coordinate values. The Arduino IoT Cloud provides
us with a map widget to display the current location of an object. The map widget works with the
location cloud variable type, which consists of latitude and longitude values. The object could be
anything from a child or animal to a delivery bike, a courier truck, or even food/vegetable parcels.
The following code demonstrates how you can assign the latitude and longitude values to the
location cloud variable:
location=Location(32.045948421308715, 72.72505696868048);
The preceding code is used to assign a location whenever your device receives data from a GPS module.
This map widget is only capable of showing one location at a time. If you have multiple objects for
which you want to display tracking, then each object will need its own map widget.
Chart
So, we can use the gauge or percentage widgets to display the current value of a sensor, but what if we
want to display the current value as well as historical data? For this, chart is your best option, which is
used to display current readings alongside historical readings for better visualization and comparison.
Delving into output controls 81
The Chart widget shown in Figure 3.10 uses the integer or float cloud variable types, which as
discussed previously are appropriate to monitor temperature, humidity, air quality, and so on. Just link
any cloud variable with the chart widget for data visualization. Other use cases include light levels,
energy consumption, and levels of different gases in industry.
Important note
For quick testing, just drop the slider and chart widgets on a dashboard and link both of them
with the same integer cloud variable type. After that, just change the value of the slider, and
you can observe how charts work.
Here, we discussed both the map and chart widget controls in detail. Now, we will explore messenger
and sticky note controls.
In the figure, the first widget is Messenger, and the second widget is sticky notes. Both widgets will
be discussed in the following sections.
82 Insights into the Arduino IoT Cloud Platform and Web Editor
Messenger
The messenger widget works like any traditional messenger app. But the question arises, why would we
need this widget on a dashboard? In my opinion, it’s simply not essential on any dashboard currently,
but in the future, it could become an awesome widget and inspire people to develop products where
you communicate textually with Things, just as we already have the Amazon Echo Dot and Google
Assistant devices that users interact with verbally, where you ask questions to the device and it
responds audibly.
In the future, you may see many messenger applications linked to your Things, where you ask questions
such as, where is my child?, and the Thing connected to your child will respond to you with their exact
location. Alternatively, you could ask a question about the temperature/humidity conditions in your
room, and the Thing would respond with the required answer.
You could also use the messenger widget to create some sort of small search engine for your Thing that
understands some keywords and responds to users’ queries. Remember, the early bird catches the worm.
The messenger widget works with the string cloud variable type. The following simple code snippet
demonstrates how you can write to the messenger widget from the device end:
When you assign a new value to the string variable, messenger will append the new content to the
widget. The following code is used to clear the whole widget at the device end:
stringMessengerVariable = PropertyActions::CLEAR;
You can also integrate the messenger widget with third-party tools such as Slack and Discord, via
either an API or Zapier integration.
Sticky notes
The sticky note widget works just like simple Windows OS Sticky Notes. It helps you to write down
your project progress, or you can write anything on a sticky note to maintain your dashboards. It
helps you in a situation where you have dozens of dashboards and you want to add some comments
about specific dashboards.
For the latest updates and details about dashboard widget controls, please visit https://docs.
arduino.cc/arduino-cloud/getting-started/dashboard-widgets.
In this section, we discussed both the messenger and sticky note widgets. Sticky notes make it easy to
maintain projects and write down comments about project progress or maintenance, while messenger
has a broader use. We also discussed how sensor data is related to AI. We have now completed all of
our input and output widget controls, Now, we will dive deep into the Arduino Web Editor, where we
will explore all the options step by step.
Understanding the Arduino Web Editor 83
The numbers in the preceding screenshot correspond to the following elements of the Web Editor:
1. This is the main menu of the Web Editor, where you will find all the navigation links, such as
Sketchbook, Examples, Libraries, and Monitor.
2. This tab is a sub-menu, displaying options/content according to the current main menu selection.
In the screenshot, this tab shows content related to the sketchbook.
3. This area is the coding/sketch area, where you can find all the options to work with code, such
as code verification/uploads, board selection, and the code editor.
4. This tab is the output terminal, which provides you with information regarding code upload
status, any errors found in your code, and so on.
84 Insights into the Arduino IoT Cloud Platform and Web Editor
Here, we discussed the Arduino Web Editor interface. Now, we will discuss Sketchbook, Examples,
Libraries, Monitor, References, and Help, as well as the Preferences and Features menus in detail.
We will discuss all the options in depth so you will get a broader overview of the Arduino Web Editor,
allowing you to utilize its features fully during your development.
Sketchbook
This menu option is responsible for sketch organization, creation, code download and upload, and so on.
The numbers in the preceding screenshot correspond to the following elements of the sketchbook screen:
1. The NEW SKETCH button is used to initialize a new set of files for a new project. To the right
of this button are two icons – the first is used to create a folder for project organization, and the
second is used to import any existing Arduino IDE code/libraries into the Web Editor if required.
2. Here is where you will find all of your sketches/folders, and you can also search your sketchbooks
with the help of the search bar.
3. The tick icon is used to verify the code, while the arrow icon is used to upload the code to
the development board. From the dropdown to the right of these icons, you can select the
development board and port. Finally, the ellipses button contains a range of options regarding
sketches, such as Save, Save as, Rename Sketch, and Download Sketch.
4. This area is a playground for developers to write code for their devices. Here, you will find two
icons to the right of the screen, the first of which is used to make the code editor full-screen,
while the second is used for code indentation.
Understanding the Arduino Web Editor 85
5. This is the output terminal where you can get all the information about code compilation
progress and any errors found in your code.
Examples
One of the top features of Arduino IDE is Examples, which is a great resource for beginners, who
can benefit from examples provided by library and sensor developers. This is presented as a separate
menu in the Arduino Web Editor. Figure 3.14 shows the Example menu with two different tabs. The
first tab shows the BUILT IN examples, while the second tab shows the FROM LIBRARIES examples.
When you click on the Examples menu, the next tab will be displayed, showing options for examples
either built-in or from libraries. All the examples are organized in different categories, just as in the
Arduino IDE. You can also use the search bar to find examples from a specific library. By default, the
Arduino Web Editor only displays development board-specific examples and libraries. The preceding
screenshot only shows examples compatible with MKR Wi-Fi 1010, but you can click on the MKR
WIFI 1010 link and shift to ALL Boards, and vice versa.
86 Insights into the Arduino IoT Cloud Platform and Web Editor
In the Arduino Web Editor, we have access to a vast collection of pre-installed libraries, and we can
mark libraries as favorites and include them in our code. When we open the Libraries menu option,
we will see the aforementioned three main tabs – DEFAULT, FAVORITES, and CUSTOM. The
DEFAULT tab displays all the libraries developed by the Arduino team and verified partners. The
Understanding the Arduino Web Editor 87
FAVORITES tab contains the libraries that you have favorited in the Library Manager. If you can’t find
a library specific to your work, then you can import your own library into the Arduino Web Editor
by clicking on the CUSTOM tab.
The Library Manager contains a complete list of libraries from all around the world. To add a library
to your project that you can’t find in the DEFAULT tab, just click on LIBRARY MANAGER, and
a new popup will appear, where you can search for a library by its name or company name. When
found, mark it as a favorite by clicking on the star icon.
Clicking on the Monitor link will only activate the Monitor when there is a board connected to the
system. Make sure your Arduino Create Agent is running in the background as well. At the top of
the Monitor screen, you will see the name of the development board and the port name/number to
which it’s connected.
Next, set the baud rate on which a device is configured during a sketch, using the Serial.begin()
method. Developers mostly use 9,600 baud rates for serial communication. The large text area in
the bottom half of the Monitor shows all communication between the device and the developer. By
default, AUTOSCROLL is enabled in this window, so new messages will automatically be shown.
The preceding screenshot displays stats regarding the Web Editor features. Firstly, we can see how
much storage space has been used from the total made available as part of the subscription plan. I have
1,000 MB of storage in total with my Maker Pro plan. The screenshot also shows how many sketches
can be created, and finally, how many compilations are allowed. In my case, I have unlimited, but the
Free plan only had 100 MB of space allowed for sketch storage and limits of 25 compilations per day.
Important note
The Arduino Web Editor features are subject to change over time, so please visit the official
page for up-to-date information: https://cloud.arduino.cc/plans.
Here, we successfully discussed the different options in the new Arduino Web Editor in depth, which
will help you to use the Editor effectively and efficiently in your development projects, helping you to
boost your productivity. The following section, Assignments, cover different questions for you, which
will help to test out what you have learned in this chapter and through internet searches, helping you
to utilize your new skills effectively.
90 Insights into the Arduino IoT Cloud Platform and Web Editor
Assignments
This chapter is longer in length than the previous ones, as we want to give you an in-depth overview
of Arduino IoT Cloud and its main pillars, which include Things, devices, dashboards, integrations
and templates, progressing to further chapters. In this chapter, we have discussed dashboards, input
and output widget controls, as well as the Arduino Web Editor in detail. To consolidate what you
have learned in this chapter, we have created three different assignments for you. These assignments
will help you to understand the core concepts necessary to proceed with the book, as well as in your
professional projects.
Make sure to attempt all the assignments given ahead.
Assignment 1
ASNA Group is a leading ISO-certified salt supplier organization in Pakistan. The organization processes
salt according to international standards, but they are facing issues in warehouse monitoring, where
they want to maintain the temperature/humidity in line with the standards, to avoid issues with the
finished product. Right now, they have five warehouses to monitor. They want multiple views for
data monitoring and analysis. You need to keep the following questions in mind while developing a
solution for ASNA Group:
1. Firstly, identify what type of industrial-grade sensors/development boards are required for
this monitoring scenario.
2. Is there any calibration required for the sensors? If so, how will you calibrate the sensors? If
not, provide a reason why it’s not mandatory.
3. What type of widgets are required to visualize the information on a dashboard?
4. How you could visualize readings from five warehouses on one dashboard?
5. What type of widgets will be used on the dashboard to allow users to analyze readings covering
a long period of time?
6. By what means will you give the company access to the dashboard?
Assignment 2
Imzlab Technologies Private Limited is a leading smart agriculture solution provider. The company
has deployed custom-designed sensors in the field, using ESP32 and the Arduino IoT Cloud, to
measure soil moisture, soil temperature, and outdoor temperature/humidity. On the dashboard, they
have different widgets for data visualization. They now have a new requirement from a customer to
integrate a water pump control and display its status history (on/off). The customer also requires that
on Monday and Thursday, the water pump will run from 5:00 p.m. to 7:00 p.m., and on Sunday, from
4:00 a.m. to 6:00 a.m., in the GMT+5 time zone. On other days, the pump status will be controlled
Summary 91
manually. You need to keep the following questions in mind while developing a solution for Imzlab
Technologies Private Limited:
1. What type of control widgets are required to display and control the water pump status?
2. How can you provide a solution for automatic pump control on specific days and at specific times?
3. Is it possible to visualize the water pump on/off status history using charts? If so, how? If it’s
not possible, provide an alternative solution to meet the customer’s requirements.
Assignment 3
A group of researchers at Imzlab Technologies Private Limited is working on a monitoring system to
monitor carbon dioxide levels. They are using MKR 1010 and the Arduino IoT Cloud, but they are
trying to use a custom sensor developed by Tingstack LLC. In the Arduino Web Editor, there is no
library for this sensor, but Tingstack LLC has developed an in-house library for the Arduino platform.
The researchers also want to share their code with the Tingstack LLC team for review.
Identify the problems from the preceding paragraph, and write down their solutions.
Summary
This chapter was just like understanding the ingredients and kitchen tools we have before we start
cooking. Firstly, we learned about how the Arduino IoT Cloud components work, including Things,
devices, dashboards, integrations, and templates. Then, we studied all the input/output widget controls
to get a proper idea of their potential usage, including some example code and the cloud variable
types. In the following section, we examined what the Arduino Web Editor is and how its different
features work, including examples, libraries, and the Serial Monitor. You should now have a good
understanding of all the different ingredients of the Arduino IoT Cloud and the Web Editor and how
to employ them appropriately.
This chapter was most important before starting the next chapters, as it gives you an in-depth overview
of all the main pillars of the Arduino IoT Cloud and how they work in real time, which will help
you to understand how the Arduino IoT Cloud works. Arduino dashboard widgets are also very
important to us, as we will use different widgets in different projects throughout the book, so giving
you an overview here has prepared you for upcoming chapters, helping you to understand what types
of things are mandatory for professional projects and what type of controls make your project more
robust and professional.
In the following chapter, we will start work on our first project, where we will build an air-quality
monitoring system from scratch to deployment. You will learn why air-quality monitoring is necessary
and what types of development boards/sensors are required. We will also use a Printed Circuit Board
(PCB) for proper deployment, which will be explained in depth. After a section on the necessary
hardware, we will set up Things, cloud variables, devices, and network configurations and coding for
a device, as well as a dashboard for proper data visualization. So, gear up for the upcoming chapter,
which will be fun for all of you.
Part 2:
Getting Hands-On with
Different Communication
Technologies
The second part of the book describes the different communication technologies involved in IoT
projects and provides four different practical projects to demonstrate their usage and how third-party
components can be adopted in combination with the Arduino IoT Cloud.
This part has the following chapters:
Technical requirements
The following hardware components are required to understand this chapter:
• A PCB (a link is available in the PCB design and assembling hardware components section)
• Female headers
• Jumper cables
For coding, we will use the Arduino Web Editor, which includes a large collection of development
boards and sensor libraries, and the Arduino IoT Cloud for Thing and dashboard setup. To develop
hardware and sensor designs, we will need Fritzing desktop software.
The code for this chapter is available at the book’s official GitHub repository, or you can directly download
the code by following this link: https://github.com/PacktPublishing/Arduino-IoT-
Cloud-for-Developers/tree/main/Chapter%234%20Project%231%20Sensing%20
and%20Monitoring%20the%20Air%20for%20Clean%20Environment.
• Regulatory compliance: Many countries have regulations in place to limit the amount of
pollutants that can be released into the air. Air quality monitoring is necessary to ensure that
these regulations are followed and to identify areas where additional regulations may be necessary.
• Economic concerns: Poor air quality can have a negative impact on economic activity, including
reduced productivity, increased healthcare costs, and decreased tourism. Monitoring air quality
can help to identify areas where pollution levels are high and take steps to improve air quality
and support economic growth.
Exploring the hardware requirements 97
Overall, air quality monitoring is an essential tool to protect public health, preserve the environment,
and promote sustainable economic development. Now we’ve had a theoretical review of air quality
monitoring, it’s time to explore the project practically. Firstly, we will start with the hardware, where
we will explore all the required components such as development boards, sensors, design diagrams,
and PCB design for implementation. Later, we will set up the Thing and cloud variables, upload code
to the development board, and set up the dashboard for data visualization.
WeMos provides multiple pins for digital input/output, but there is only one analog pin for input/
output operations. If you want to use multiple analog sensors, then analog-to-digital converters are
available. One of the most famous analog-to-digital converters is the ADS1115/ADS1015 module,
which provides four analog pins that help cater to the requirement of using multiple sensors.
However, for the current project, we need one digital pin for the DHT11/DHT22 sensor and one analog
pin for the MQ-135 air quality sensor. One of the best features of the WeMos D1 Mini development
board is the 5V power pin, which is not available on most ESP8266 series development boards.
Next, we will use the DHT11 sensor to sense temperature and humidity, but you can also use the
DHT22 sensor, depending on your requirements. With regard to features, the DHT22 provides a
broader range of sensing compared to the DHT11, but its cost is higher. The following diagram shows
the pinout layout of both sensors:
Pin #1 is the voltage common collector (VCC) and works with both 3.3V and 5V. Pin #2 is a data
pin that connects with any digital pin of a development board, and Pin #4 is a ground (GND) pin
that connects with the GND pin of a development board. There is another pin in the sensor, Pin #3,
which is Not Connected (NC) – this pin is not used by us during development.
The following table explains all the specification differences between DHT22 and DHT11; the most
notable things are the sensing range and the sensing period:
Finally, we will look at the main sensor for our project. The MQ-135 sensor is used to monitor the air
quality of a specific area. It is a low-cost environment-monitoring sensor, and it monitors a wide range
of parameters, such as smoke, carbon dioxide, ammonia, benzene, nitrogen oxides, and alcohol. The
MQ-135 senses all these parameters and provides the value of air quality in parts per million (ppm).
The following figure shows the MQ-135’s shape and its pin layout diagram as well as indicators for
the LED and regulator:
The MQ-135 sensor module consists of four pins, and each pin is marked with a code: Analog Output
(AO), Digital Output (DO), GND, and VCC. The module provides readings on both analog and digital
modes, but analog mode is best to get values in PPM. The sensor operates better with 5V power, but you
can still use 3.3V, although I recommend the former. The MQ-135 requires 20 seconds of preheating
to provide better readings, so make sure to get readings after an interval of every 20 seconds, or at
least wait 20 seconds for the first-time boot of the development board.
The module also contains a regulator to control the sensitivity of sensors, which could be adjusted
according to the environment. Different indicator Surface Mount Device (SMD) LEDs are available
to verify the module status, which includes Logic Out LED and Power LED.
For better understanding we have developed the schematics diagram shown in Figure 4.4 as well Table
4.2 for easy understanding. The pin configuration will be discussed in detail in proceeding paragraph.
According to the design (Figure 4.4 and Table 4.2), we have a common 5V output and GND from the
development board to both sensors. The MQ-135 sensor is an analog sensor, so we connected its AO
pin to the AO pin of the WeMos development board, while DHT11/DHT22 are digital sensors, and
their Pin 2 is connected to the D1 pin of the development board.
102 Project #1 – a Smarter Setup for Sensing the Environment
design is just a basic footprint and not suitable for direct production, so it’s mandatory to review and
rearrange the design according to professional practices. The following diagram demonstrates the
final PCB design of the project:
It’s easy to develop the PCB; just make sure that the connection line doesn’t intersect with other connection
lines. There are many different tools available for PCB design, such as EasyEDA, CircuitMaker, and
Altium, but it is thanks to Fritzing that I could create that design so easily.
After the PCB design, you have two options. First, you can develop the PCB by yourself using a DIY
method, which is good for learning purposes but not suitable for a large-scale product. The second
method is to choose a professional organization that manufactures the PCB professionally. Many
organizations in China provide PCB manufacturing and fabrication services, such as Seeed Studio,
JLCPCB, and PCBWay. I have tried PCBWay and was impressed with their manufacturing and
shipment delivery time. I have uploaded the PCB design to the PCBWay project repository; from there,
you can select and order it easily: https://www.pcbway.com/project/shareproject/
Low_cost_Outdoor_Air_Quality_Monitoring_System_0157f1af.html.
Setting up the Thing, network credentials, cloud variables, and code 103
After getting the PCB board, it’s time to solder the female headers for the development boards and
sensors. Never solder the development board and sensors directly on the PCB, as if anything stops
working, then it’s easy to detach and replace. So finally, here we have a product ready where the sensors
and development board are soldered on the PCB for final deployment.
After the female headers are soldered onto the PCB, WeMos and the other sensors are plugged into
the headers, as shown in the preceding diagram. In this section and the previous section, we explored
what types of sensors and development boards will be used in our project, and the latter part of this
section discussed design, which demonstrates the wiring system for connectivity between sensors
and the WeMos D1 Mini. Finally, we explored PCB design and assembled all the components of the
PCB. Next, we need to set up the Thing, code, and dashboard in the Arduino IoT Cloud to get ready
for the final product.
Set up a new Thing with the name Sense the Environment. Follow the next steps to create
variables, the associated device, the network configuration, and finally, the code:
1. Firstly, we need to set up three cloud variables regarding air quality, humidity, and temperature.
The complete details regarding cloud variables are available in the next subsection.
2. After that, we need to associate the device with the Thing. In the current project, we will use
the WeMos D1 Mini so the wizard will be different from the Arduino boards. The complete
details are available in the Associating a device subsection.
3. Finally, we need to set up the network configuration for the device, but this time, we need to
provide a security key for ESP series boards to make the connection secure. The Arduino-
compatible boards are configured by the Arduino IoT Cloud automatically during the device
setup wizard.
4. After the setup of cloud variables, device, and network settings, we will go through the code.
Here, we have given an overview of the Thing and we also discussed the required steps that will be
carried out to complete the Thing setup.
Setting up the Thing, network credentials, cloud variables, and code 105
Cloud variables
The following table explains all the properties of the variable that we need to use when we create
the cloud variable. An integer is a very famous data type, but we will use two new variable types for
humidity (CloudRelativeHumidity) and temperature (CloudTemperatureSensor),
which measure data in percentage and Celsius, respectively. Next, make sure to declare the variables
exactly as stated in the given table, including case-sensitive names and variable types. If the example
code does not match your naming, you will need to modify it accordingly.
Here, we made the permission read-only; although we have a read/write option, in our project, we
only want to receive data from the device instead of a dashboard modification. That’s why read-only
mode is used to prevent issues in data consistency. Update policy is set to On change, as the device
will send the data after five minutes, and this option is more appropriate compared to periodic updates.
Associating a device
After creating the variables, it’s time to add a device and associate it with the Thing. Before adding
the device, connect the development board to the computer and open the Arduino Create Agent
application. The following figure shows the different types of third-party boards that are supported
by the Arduino IOT Cloud, and in that step, we will select the ESP8266 series board.
106 Project #1 – a Smarter Setup for Sensing the Environment
Please follow these steps to add the device to the Arduino IoT Cloud:
1. Click on the Select Device button under the Associating a device section on the Thing page.
2. A popup will appear, where you can see all the devices that are already available. If you have
already added your WeMos D1 Mini, select it. Otherwise, click on SET UP NEW DEVICE.
3. Next, click on the Third party device option.
4. Select ESP8266 and LOLIN(WEMOS) D1 R2 mini from the dropdown, and click on the
CONTINUE button.
5. Provide the device name and click on the Next button.
6. In the final wizard, the device ID and secret key will be displayed. Copy the secret key to a safe
place, as it will be used during the network configuration.
After setting up the device and associating it with the Thing, it’s time to configure the device network
settings. The following sections will cover all the steps to configure your device for a Wi-Fi network.
Setting up the Thing, network credentials, cloud variables, and code 107
Network
After associating the device with the Thing, it is time to configure the Wi-Fi settings for device
communication. Fill in the form with Wi-Fi Name and Password:
In Figure 4.9, you will find a new field for Secret Key. Paste the secret key that we received from the
system during the device association process, which is explained in step 6 in the preceding subsection.
Now, we are done with the device association to the Thing as well as with network settings. The next
step is to understand and upload the code. The following section will guide you through the code.
Coding
The chapter’s code is available at the book’s official GitHub repository, or you can directly download
the code by following this link: https://github.com/PacktPublishing/Arduino-
IoT-Cloud-for-Developers/tree/main/Chapter%234%20Project%231%20
Sensing%20and%20Monitoring%20the%20Air%20for%20Clean%20Environment/
Sense_the_Environment_feb24a
108 Project #1 – a Smarter Setup for Sensing the Environment
You can download the code and put it into your Thing by navigating to the Sketch tab. We will not
discuss the code any further, as you will get an idea of how it works after reading it. Instead, we will
explain the main workflow, which involves initializing all the things in the setup method and using
milliseconds to calculate the delay time. Remember to never try using the delay method, as it will
block the ArduinoCloud.update() method and then call the STHAM method every five minutes.
The following code is demonstrating how to fetch Temperature and Humidity values from dht object,
and for airQuality we are simply using analogRead() method.
dht.temperature().getEvent(&event);
if (isnan(event.temperature)) {
temperature=0;
}
else {
//Send Temperature to Cloud
temperature=event.temperature;
}
The preceding code snippet was taken from the STHAM method; here, we just modified the code to
show you how we send values to the Arduino IoT Cloud after taking values from the sensors.
In a previous section, we created the cloud variables. Just recall the cloud variable declaration and
assign the sensor readings to those variables. This cloud variable declaration is available in the
thingProperties.h file. So, when you assign the values to these variables, the ArduinoCloud.
update() method in the loop will automatically send data to the cloud.
Upload the code to the device and verify the connectivity and readings. If you want to change the
reading time, then just modify the interval variable value. Make sure you provide the time in
milliseconds, where 1 second equals 1,000 milliseconds.
Setting up a dashboard for web and mobile 109
Important note
If you used different naming in the variable declaration, then update the code according to your
naming scheme. However, it’s better that you first follow all the steps according to the book and
later change the cloud variable names and modify your code, in that order.
Never try to use delay method, which will create a block for the ArduinoCloud.update()
method. Always use milliseconds to calculate the waiting time. Review the loop() method
to understand how we call the method after 5 minutes.
The Arduino IoT Cloud only updates the value on the dashboard whenever a variable value is
changed. For example, if the temperature is 30 and is still the same after 5 minutes, then the
Arduino IoT Cloud will not record the value, so don’t get confused if values don’t change on
a graph. This is another benefit of the Arduino IoT Cloud: you will not get duplicated data
when you export the content.
We have successfully set up the Thing, which includes cloud variables, device association, network
configuration, and code, and uploaded it to the development board. Now, it’s time to explore the
dashboard and sensor values visualization in the following section.
We have three different readings, Temperature, Humidity, and Air Quality. For each reading, we
use different widget controls to demonstrate how they all work, but for historical data, graphs are the
best widgets.
The Temperature reading is visualized by Gauge, the Humidity reading is connected to the Percentage
widget, and the Air Quality reading is connected to the Value widget. These widgets are only capable
of displaying current readings of sensors. However, we also want to monitor the historical data, and
graphs are the best widgets to display live as well as older data. Here, we have used three graphs, and
each one is connected to a specific cloud variable.
What’s next?
We still have a lot of options available to explore, but now it’s your turn to use different sensors and
development boards to do some more experiments and learn from them. In this chapter, we have only
used two sensors, which only offer three parameters, but there are a lot of sensors on the market that
provide a wide variety of functionalities, such as air pressure and measurements for different gases.
Summary 111
Try out the following sensors to enhance your practical knowledge and compare them with other
sensors in terms of features, range, and cost:
Summary
In this chapter, we explored how to develop a low-cost air quality monitoring system using DHT11,
MQ-135, and the WeMos D1 Mini development board. We set up the Thing, which involved creating
cloud variables, associating the device, configuring the network, and coding the development board.
Later, we created a dashboard to visualize the Thing’s sensor readings with different types of widgets,
displaying the current readings as well as historical data with the help of graphs. Through this project,
you will get the confidence to set up the Thing practically and deploy it in the field using a PCB. You
have learned about new types of cloud variables for sensor readings and storage, as well as dealing
with different types of dashboard widgets.
In the next chapter, we will study GSM technology for IoT. We will learn about different types of global
IoT SIM cards and their usage. This project will also demonstrate a Smart Assets tracing example,
where we will track the asset with a GPS module and send the data to the Arduino IoT Cloud via
global IoT SIM cards. In the end, you will also learn about new widgets in the Arduino IoT Cloud to
visualize the location of your assets on the basis of GPS coordinates.
5
Project #2 – Creating
a Portable Thing Tracker
Using MKR GSM 1400
This chapter is dedicated to smart transportation and smart remote monitoring. It shows how
cellular communication-enabled devices can be integrated with the Arduino IoT Cloud platform,
and it also offers an example of using a global IoT SIM card for communication.
Here, we will practically explore Long-Term Evolution (LTE) technologies, which are very useful in
remote monitoring and control, whether they involve asset tracking or remote operation monitoring.
This project uses the Arduino MKR GSM 1400 development board, which is equipped with the latest
communication bands and was specially designed for Industrial Internet of Things (IIoT) and Internet
of Things (IoT) use cases. This project practically explains how you can develop a tracking solution
based on cellular communications for different use cases. This chapter will help you to understand
cellular communication technology, global IoT SIM cards, and the integration of Arduino IoT Cloud
using cellular technology. By the end of this chapter, you will be able to develop solutions for remote
areas using cellular technology.
In this chapter, we’re going to cover the following main topics:
Technical requirements
The following are the hardware components required to complete this chapter:
For coding, we will use the Arduino Web Editor, which includes a large collection of development
boards and sensor libraries, as well as Arduino IoT Cloud for Thing and dashboard setup. To develop
hardware and sensor designs, we need the Fritzing desktop software, and we need Arduino IDE for
GPS module testing.
In this chapter, we will use the Arduino IoT SIM card for communication instead of local SIM
providers. Arduino provides a wide variety of data plans for global IoT sim cards that can be chosen
according to requirements. The code for this chapter is available at the book’s official GitHub repository
at this link: https://github.com/PacktPublishing/Arduino-IoT-Cloud-for-
Developers.
• Asset tracking: By installing GPS trackers or RFID tags on your assets, you can track their
location and movements in real time. This can be very useful for logistics and supply chain
management, as well as fleet management.
• Condition monitoring: By installing sensors on your assets, you can monitor their condition
and performance in real time. This can help you identify potential problems before they become
serious and take corrective action to prevent downtime and reduce maintenance costs.
Exploring the advantages of GSM/LTE/NB-IoT communication technologies 115
• Predictive maintenance: By analyzing data from your sensors, you can use machine learning
algorithms to predict when maintenance is needed on your assets. This can help you schedule
maintenance at the most convenient time and avoid unplanned downtime.
• Remote control: By connecting your assets to a central network, you can control them remotely
from a central location. This can be very useful for operations that are located in remote areas
or difficult to access.
• Remote monitoring: By installing cameras and other sensors on your assets, you can monitor
their operations remotely in real time. This can help you identify potential problems and take
corrective action quickly.
Overall, IoT technology can be very useful for asset tracking and remote controlling and monitoring
operations. By leveraging the power of sensors, data analytics, and machine learning, you can improve
the efficiency and reliability of your operations while reducing costs and downtime. In this section, we
have discussed IoT for asset tracking and remote monitoring using cellular technology. Next, we will
cover different communication technologies that are available now and coming to market in the future.
• Wide coverage: GSM and LTE networks have extensive coverage and are available in most
parts of the world, making them ideal for global connectivity. NB-IoT, on the other hand, has
been designed specifically for IoT devices and offers greater coverage in hard-to-reach areas.
• High data rates: LTE offers high data rates, making it suitable for applications that require
fast and reliable data transfer. NB-IoT, although slower, still offers better data rates than other
Low-Power Wide-Area Network (LPWAN) technologies.
• Security: GSM and LTE networks offer high levels of security, with features such as encryption
and authentication to protect against eavesdropping and other forms of cyberattacks. NB-IoT
also provides end-to-end encryption for data security.
• Compatibility: GSM and LTE networks are backward compatible with previous generations
of technology, allowing for seamless integration with existing infrastructure. NB-IoT is also
designed to be compatible with LTE networks, making it easy to add IoT capabilities to existing
LTE networks.
116 Project #2 – Creating a Portable Thing Tracker Using MKR GSM 1400
• Battery life: NB-IoT and other LPWAN technologies are designed to consume minimal power,
resulting in longer battery life for connected devices.
Overall, GSM, LTE, and NB-IoT are widely used communication technologies that offer reliable
connectivity, high data rates, security, and compatibility with existing infrastructure. Here, we
have discussed the benefits of GSM/LTE/NB-IoT communication technologies over other wireless
communication technologies. In the next section, we are going to cover global IoT SIM cards, which
is the main pillar of this chapter.
• Multi-network coverage: These SIM cards can connect to multiple cellular networks, including
GSM, LTE, and other emerging technologies, such as NB-IoT and Cat-M, to provide reliable
coverage in different locations.
• Over-the-air (OTA) updates: Many global IoT SIM card providers offer OTA updates, enabling
devices to receive firmware and software updates without the need for physical intervention,
improving efficiency and reducing maintenance costs.
• Data plans: Global IoT SIM card providers offer flexible data plans that can be customized
to suit the specific needs of a device or application. This includes data allowances, data speed,
and the ability to add more data as needed.
• Security: Global IoT SIM cards typically come with security features such as encryption and
authentication to protect data and prevent unauthorized access.
• Management tools: Many global IoT SIM card providers offer web-based portals or mobile
apps that allow users to monitor and manage their SIM cards, including data usage, network
performance, and billing information.
Global IoT SIM cards provide a cost-effective and flexible solution for companies, allowing them to
deploy IoT devices worldwide. They allow seamless connectivity, ensuring that devices are always
connected to the best available network, regardless of location.
Building blocks – sensors and development boards for IoT 117
There are many IoT global SIM service providers. Here is a list of some of them:
• Hologram
• Soracom
• Arduino SIM
• Twilio
• Emnify
• Aeris
• KORE Wireless
• Sierra Wireless
• Teleena
• Thales Group
• Truphone
• UROS
• 1oT
Important note
Before buying an IoT global SIM card from any service provider, please verify whether it works
in your region or not and, if so, what type of services it offers, such as GSM, 3G/4G, or NB-IoT,
as there are many regions where, for example, NB-IoT services are still not available.
Please note that this is not a complete list, and there are many other IoT SIM providers available
in the market. It’s important to research and compare different providers based on your specific
requirements and needs before making a decision.
Here, we have discussed global IoT SIM cards in detail and listed all the top global IoT SIM card
service providers. Next, we are going to cover what types of hardware and sensors are required to
complete the chapter’s project.
Arduino MKR GSM 1400 provides 7 analog pins and 14 digital input/output pins, with built-in battery
charging and a LiPo battery connector for standby power, which helps developers build prototypes
and solutions for remote monitoring/operations without worrying about power backups. For further
details, please visit the official website at https://store-usa.arduino.cc/products/
arduino-mkr-gsm-1400.
Arduino’s latest development board, MKR NB 1500, only supports NB-IoT, LTE-M, and Enhanced
GPRS (EGPRS) for SMS. NB-IoT and LTE-M are specially designed for IoT devices, and their
popularity is spreading very rapidly across different regions. For complete details and specifications,
visit https://store-usa.arduino.cc/products/arduino-mkr-nb-1500. For a
list of updated regions where NB-IoT and LTE-M are deployed, visit https://www.gsma.com/
iot/deployment-map/.
In this chapter, we will track the assets based on GPS location. To get the GPS coordinates, we will
use the GY-GPS6MV2 GPS module, which is based on the NEO-6M u-blox chip. The GPS module
communicates on both software serial and hardware serial ports, but MKR GSM 1400 provides a
built-in hardware serial, so we will use Pins 13 and 14 to communicate with the GPS module.
Building blocks – sensors and development boards for IoT 119
The GPS module provides latitude, longitude, satellite count, altitude feet, and speed per mile data. We
will display these properties on the dashboard for proper asset tracking. This module was developed
in China and is available on the market at affordable prices, but there are many other organizations
that develop GPS modules based on the NEO-6M u-blox chip, such as SparkFun, Seeed Studio, and
Adafruit. Figure 5.2 shows the NEO-6M u-blox GPS module and its pinout diagram:
Figure 5.2 – The NEO-6M u-blox GY-GPS6MV2 GPS module and a pinout diagram
The preceding figure illustrates the pinout layout of the GPS module. Pin #1 is a ground (GND) pin
that connects with the onboard GND, while Pin #2 and Pin #3 are transmit (TX) and receive (RX)
pins, respectively, and connect to Pin #13 and Pin #14 of MKR GSM 1400, respectively. Pin #4 – the
voltage common collector (VCC) – works with both onboard VCC and 5V pins. You can solder the
male headers with the GPS module or directly solder the cables without any header pins.
Important note
The GPS module works optimally in an outdoor environment. Make sure there is no rooftop
during testing and deployment to receive a proper signal from satellites.
If you are using the module in a lab, then there will be a chance that the GPS module will not
work properly. Remember that there is a built-in light in the GPS module that blinks when
you start receiving signals from satellites.
In this section, we discussed the MKR GSM 1400 development board, which is a SIM-enabled board,
and the NEO-6M u-blox GPS module, which will provide the GPS coordinates to the development
board. We also discussed their pin layouts. Next, we will discuss how to connect the GPS module with
the MKR GSM 1400 development board.
120 Project #2 – Creating a Portable Thing Tracker Using MKR GSM 1400
Figure 5.3 – MKR GSM 1400 and the GPS module schematic
Designing the project architecture 121
Figure 5.3 is schematic diagram of project, but for ease I also created Table 5.1, which demonstrates
MKR GSM 1400 to GPS Module pin numbers and names.
Table 5.1 – MKR GSM 1400 and the GPS module pin connections list
The preceding design provides a full overview of how you can connect a module to a development
board. According to our design, we have 5V and GND from the development board to the GPS module.
The GPS module TX is connected to the RX (Pin #13) and the GPS module RX pin is connected to
the TX (Pin #14) of the development board. Table 5.1 shows the pin information. Finally, we have
built our prototype by using a breadboard, which is shown in Figure 5.4:
After soldering the male headers to the GPS module, connect the pins according to the schematic
diagram. There is only one sensor, so there is no requirement for the Veroboard. Next, we are going
to test the GPS module using a serial monitor to verify that our GPS module is working properly and
getting the values from GPS.
122 Project #2 – Creating a Portable Thing Tracker Using MKR GSM 1400
After searching, Library Manager shows a lot of libraries. Select the TinyGPSPlus library and install
its latest version. The library comes with a lot of examples, but all are based on software serial. However,
Arduino SAMD boards provide hardware serial, so I modified the code that uses hardware serial to
communicate with the GPS module.
Download the code from the book’s official GitHub repository in the chapter folder, open the
MKR-1400-NEO-6M-GPS-Module code, and upload it to the development board:
In the setup, we have initialized Serial and Serial1. Serial is used to display the content on
the serial monitor, while Serial1 is the hardware serial that is used to communicate with the GPS
module. The preceding code belongs to the loop() method.
First, the GPS module will read the data from satellites using the Serial1.read() method and
encode the data via the gps.encode() method. Serial1 only reads one character at a time, so
it will take a little bit of time to update the values. Next, we will verify whether there is any update in
location by using the gps.location.isUpdated() method. If there is a change, then data will
be printed on the serial monitor.
Important note
Make sure that your GPS module is placed in an open environment where you have a clear
sky without any obstructions, such as a roof or anything similar, to properly receive signals
from satellites.
The GPS module has an onboard built-in LED that starts blinking when it receives data from GPS.
The same code will work with MKR NB 1500 without any modification.
Figure 5.6 shows the serial monitor with values from the GPS, which includes latitude and longitude,
along with other parameters:
124 Project #2 – Creating a Portable Thing Tracker Using MKR GSM 1400
The preceding figure shows the data that is received by the GPS module from GPS satellites and printed
on the serial monitor. The data includes the satellite count, the latitude and longitude that represent
the location coordinates, the speed in miles per hour (MPH) based on current and previous GPS
coordinates, and the altitude in feet.
In this section, we tested the NEO-6M u-blox GPS module in the Arduino IDE. First, we installed
the TinyGPSPlus library for the module and then we used the preceding code for the development
board, which shows the readings on the serial monitor. In the next section, we are going to start with
the global IoT SIM card activation.
After receiving the SIM card, create an account at hologram.io, where you will be able to activate
and manage all your SIM cards. The Hologram dashboard provides full details regarding the data
utilization of devices, packages, billing, and routes. By setting up routes, you can forward your device
data to a different IoT cloud if you directly send it to the Hologram cloud. However, in our case, we
will just use the Hologram SIM card as a carrier to transfer data from a device directly to the Arduino
IoT Cloud, so there will be no requirements to set up a route. Just activate the SIM card and insert it
into the MKR GSM 1400 development board.
In this section, we discussed how we can proceed with Hologram global IoT SIM card activation as
well as the different types of SIM cards available at hologram.io for researchers as well as industry.
In the next section, we are going to set up the Thing in the Arduino IoT Cloud, which will include
cloud variables creation, device association, network configuration, and code.
Figure 5.7 – A portable Thing tracker using the MKR GSM 1400 Thing setup
126 Project #2 – Creating a Portable Thing Tracker Using MKR GSM 1400
Set up a new Thing with the name A portable thing tracker using MKR GSM1400.
Then, follow these steps to create cloud variables, an associate device, a network configuration, and
finally, the code:
1. Firstly, we need to set up four cloud variables for location, altitude feet, satellite count, and
speed. The complete details regarding these cloud variables are available in the following section.
2. Then, we need to associate the device with the Thing. In the current project, we will use the
MKR GSM 1400, so the wizard will be the same one used for the Arduino boards. The complete
details are available in the Associating a device section.
3. Finally, we need to set up a network configuration for the device, but this time, we need to
provide different settings for the GSM board, which will be covered in the Network subsection.
Here, we have discussed what steps will be involved in the Thing creation. In the following subsections,
we will create cloud variables, associate a device to the Thing, and network settings in separate
subsections step by step.
Cloud variables
The following table explains all the properties that we need to use during cloud variable creation.
For Location, we need two different variables to store latitude and longitude, but thanks to the
Arduino IoT Cloud extended group of variables, we have a Location type variable. Next, make
sure each variable matches the declaration in the table; otherwise, you need to modify the example
code according to your naming.
In Table 5.2, during the cloud variables creation, I made the permission read-only. Although we have
the read/write option, in this project, we only want to receive data from the device instead of modifying
it on the dashboard. That’s why read-only mode is used – to prevent issues with data consistency.
Update Policy is set to On change, as the device will send the data when the GPS module receives
new data from satellites.
In this section, we have discussed what type of cloud variables are required for this project. Here, we
have listed four cloud variables of different types but in read-only mode, as we only want to take the
values from the device. In the next subsection, we are going to associate the MKR GSM 1400 with
the Thing.
Associating a device
After creating the variables, it’s time to add the device and associate it with the Thing. Before adding
the device, connect the development board to the computer and open the Arduino Create Agent
application. Figure 5.8 shows a popup in which we have options to either select the existing device
for association or set up a new device that is not available in the list:
In our case, we already have different devices in the portal, but we want to add a new MKR GSM 1400
device, so just click on SET UP NEW DEVICE to configure the new device in the account.
Then, you will see two options in the popup (Figure 5.9). The first option is to set up an Arduino board,
and the second option is to set up a third party device. Here, you will see a note under both options,
Compatible devices ( ), which means you can only use certain types of Arduino devices as well as
third-party devices in the Arduino IoT Cloud.
We can select any one option from the popup, according to the available device. However, in this
case, click on the option to set up an Arduino device, as, in this chapter, we will use the MKR GSM
1400 board. Before adding the device, make sure that Arduino Create Agent runs on your machine.
In this subsection, we have associated the MKR GSM 1400 development board with the Thing. Next,
we will configure the network settings in the Thing tab.
Configuring the Thing, network credentials, cloud variables, and code 129
Network
After associating the device with the Thing, it is time to configure the network settings for device
communication. These network settings are different from the Wi-Fi network settings. Both the MKR
GSM 1400 and MKR NB 1500 development boards use SIM technology for communication. For that
reason, their network configurations are different and will vary according to the IoT SIM card service
provider. The following figure (Figure 5.10) shows the Configure network popup for the MKR GSM
1400, which is totally different to the Wi-Fi configuration due to cellular communication:
Figure 5.10 – The network configuration for the MKR GSM 1400
Currently, we are using the Hologram global IoT SIM card, and only need to mention hologram
under APN; there is no requirement for the PIN, Username, and Password details. However, if you
use the Arduino SIM, then APN will be prepay.pelion, PIN will be 0000, and Username and
Password will both be arduino. Before using any other global IoT SIM card, first, take its APN
information to set up the network properly.
130 Project #2 – Creating a Portable Thing Tracker Using MKR GSM 1400
Here, we have discussed the network configuration for the Arduino MKR GSM 1400, which
includes the APN, PIN, username, and password. In the next section, we will cover the code for the
development board.
Coding
The chapter’s code is available at the book’s official GitHub repository. Download A_portable_
thing_tracker_using_MKR_GSM1400_apr07a.zip and import it into the Arduino
Web Editor.
You can download the code and put it into your Thing by navigating to the Sketch tab. Here, I
will explain the main workflow instead of all code, we are initializing all the objects and variables
in the setup() method; remember to never try to use the delay method, as it will block the
ArduinoCloud.update() method:
TinyGPSPlus gps;
unsigned long previousMillis = 0;
const long interval = 30000; //milliseconds
In the preceding code snippet, we declare the gps instance and two variables, which will be used to
wait for 30,000 milliseconds (30 seconds) before taking the next readings without blocking the code.
Next, we will move toward the loop method. Here, we call the FetchGPS() method after every
30 minutes, which is carried out by comparing currentMillis and previousMillis without
the use of delay:
In the following snippet, I have just picked a small part of the code from the FetchGPS() method.
Here, I assign the latest values from the GPS module to the Arduino cloud variables, which will be
used to send data to the cloud as well as print it on the serial monitor:
if (gps.location.isUpdated())
{
altitudeFeet = gps.altitude.feet();
satelliteCount = gps.satellites.value();
speed = gps.speed.mph();
location = Location(gps.location.lat(), gps.location.lng());
Location cordinates = location.getValue();
Creating comprehensive web and mobile dashboards 131
.
.
.
}
Upload the code to the device and open up the Arduino Web Editor serial monitor to verify the values.
After successfully uploading the data to the cloud, it’s time to set up a beautiful dashboard for web
and mobile for end users.
Important note
If you used different names in the variable declaration, then update the code according to your
naming scheme. However, it’s better to first follow all the steps according to the book and later
change the cloud variable names, modifying your code respectively.
Never try to use the delay method, which will create a block for the ArduinoCloud.
update() method.
The Arduino IoT Cloud only updates a value on the dashboard whenever a variable value is
changed. For example, if the GPS location of the device is the same after an interval of time,
then it means the device is not moving. Then, the Arduino IoT Cloud will not record the value,
so don’t get confused if values are not changing on the map. Another benefit of this feature is
that you will not get duplicate data when you export the content.
The same code will work with MKR NB 1500 without any modification. However, here, you
need to associate the MKR NB 1500 device with the Thing instead of the MKR GSM 1400.
We have four readings from the GPS module to visualize; here, I have used three widgets, Gauge,
Value, and Map, but Map is used twice as it takes two values (i.e., latitude and longitude). The Gauge
widget shows Speed Per Mile, while two Value widgets have been used to display Altitude Feet and
Satellite Count. The Map widget has been used to display Location based on the latitude and longitude
coordinates, which are stored in a cloud-based location variable. Currently, the Map widget is only
capable of displaying the location of the asset device based on coordinates; if you have multiple assets
to track, then you need to set up multiple Map widgets according to the number of tracking devices.
Well, this was the last section of our chapter. Here, we have created a stunning dashboard for GPS
tracking that shows the location using the Map widget on the dashboard, the speed per mile, and
some other parameters.
What next?
We still have a lot of options available to explore, but now it’s your time to use different sensors and
development boards to do some more experiments and learn from them. In the current chapter, we
only used one GPS module, which gave us only four parameters but, on the market, there are a lot of
GPS modules that provide a wide variety of functionalities; they work under the roof as well as under
clear sky, and have several accuracy features.
Summary 133
While monitoring an asset’s location, there are some other parameters that are very important to
monitor in different industries, such as temperature and humidity, which are very important in food
and medical products. CO2 and LPG gases are very important to monitor during fuel transportation.
Try different sensors with a GPS module to set up different tracking prototypes for different industries.
Summary
In this chapter, we explored how to develop a GPS-based tracking system using a global IoT SIM card
and GPS module. We set up the Thing, which included cloud variable creation, device association,
GSM network configuration, and coding a development board. Later, we created a dashboard to
visualize the Thing readings with different types of widgets to display current readings, with the most
important widget of the chapter being the Map widget. It is a very interesting and important widget
to display the location of IoT devices using GPS coordinates.
GPS tracking is a very important aspect that we covered in this chapter, and it helps us to develop
a device for our asset tracking, which will help us in asset tracking and monitoring. This chapter
demonstrated how we can display the location of a device on the dashboard, which gives you the
confidence to build more solutions regarding asset tracking. In the next chapter, we will explore
another long-range communication technology, called LoRaWAN. We will use this technology to
build a solution for remote monitoring distant areas as well as compare this technology with GSM/4G/
LTE and NB-IoT technology for proper guidance.
6
Project #3 – a Remote Asset
Tracking Application with
LoRaWAN
This chapter is dedicated to smart transportation and smart remote monitoring using low-power
and long-range communication technology. The project in this chapter will take you through the
implementation and deployment of a remote alarming application based on Long Range Wide Area
Network (LoRaWAN), connected to the public, global, and decentralized The Things Network. The
project in this chapter provides localization features by using a GPS module. The Arduino IoT Cloud
will be used for data visualization and remote configuration of the device. The application will be
used in real use cases, showing the benefits offered by LoRaWAN technologies compared to other
wireless technologies.
Here, we will practically explore LoRaWAN technologies, which are very useful in remote monitoring
and control, whether it’s asset tracking or remote operation monitoring. This project uses the Arduino
MKR WAN 1300 development board, which is equipped with the latest communication frequencies,
433/868/915 MHz US/EU. It is specially designed for Internet of Things (IoT) and Industry 4.0 use
cases. This project explains how you can practically develop a tracking solution based on LoRaWAN
communication for different use cases.
In this chapter, we will cover the following main topics:
Technical requirements
The following hardware components are required to complete the exercise in this chapter:
To code, we will use the Arduino Web Editor, which includes a large collection of development
boards and sensor libraries, and the Arduino IoT Cloud for the Thing and dashboard setup. To develop
hardware and sensor designs, we need the Fritzing desktop software, and we need the Arduino IDE
for GPS module testing.
In this chapter, we will use the The Things Indoor Gateway for LoRaWAN communication. The code
used in the chapter is available in the book’s official GitHub repository by following this link: https://
github.com/PacktPublishing/Arduino-IoT-Cloud-for-Developers.
Usage in IoT
LoRaWAN has been widely adopted in various IoT applications due to its unique features. Some
common use cases include the following:
• Smart agriculture: LoRaWAN can be used for soil moisture monitoring, crop health monitoring,
livestock tracking, and precision farming, allowing farmers to optimize their operations and
increase yield
• Smart cities: LoRaWAN can enable smart street lighting, waste management, parking management,
and environmental monitoring, helping cities become more efficient and sustainable
LoRaWAN versus other communication technologies 137
• Industrial monitoring: LoRaWAN can monitor equipment health, track assets, and improve
supply chain management in industrial settings, leading to better maintenance practices and
reduced downtime
• Utilities: LoRaWAN can be used for smart meters and to remotely monitor utility infrastructure,
such as water and gas meters, improving billing accuracy and resource management
• Environmental monitoring: LoRaWAN can support applications such as air quality monitoring,
water quality monitoring, and wildlife tracking, helping researchers and organizations gather
valuable environmental data
• Asset tracking: LoRaWAN enables real-time tracking of assets, such as shipping containers,
vehicles, and valuable equipment, ensuring their security and efficient utilization
Overall, LoRaWAN’s combination of long communication ranges, low power consumption, and
scalability makes it a powerful technology to build IoT networks that cover large areas and connect
a wide range of devices for various applications.
In this section, we have discussed the different use cases of LoRaWAN in the field of IoT, and in the
next section, we will discuss why to choose LoRaWAN over other communication technologies.
• Low data rate applications: LoRaWAN is optimized for applications that transmit small amounts
of data at low data rates. For IoT use cases involving sensor data, meter readings, and periodic
updates, LoRaWAN provides a suitable and efficient communication solution.
• Network flexibility: LoRaWAN supports both public and private network deployments.
Organizations can choose to set up their own private LoRaWAN network or use existing public
networks, giving them flexibility in terms of ownership and control.
• Adaptive data rate: LoRaWAN devices can adjust their data rate based on signal strength
and interference, optimizing communication for the current conditions. This adaptive feature
enhances reliability and ensures the efficient use of available resources.
• Global standard: LoRaWAN is a global standard, and devices designed to work with it can
operate seamlessly across different regions and countries. This standardization simplifies device
development and deployment for international projects.
• Diverse applications: LoRaWAN’s versatility enables its use in various application domains,
from agriculture and industrial monitoring to smart cities and environmental sensing.
While LoRaWAN offers these advantages, it’s important to note that no single communication technology
is universally superior. The choice between LoRaWAN and other technologies (such as cellular, Wi-Fi,
Bluetooth, or Zigbee) depends on the specific requirements of the IoT application, including factors
such as range, power consumption, data rate, cost, and scalability. Each technology has its strengths
and weaknesses, and the selection should be based on a careful analysis of a project’s needs.
In this section, we have discussed the benefits of using LoRaWAN. In the next section, we will explore
the important components of LoRaWAN.
• End nodes/devices: These are the IoT devices that gather data from sensors or perform specific
tasks. They communicate with gateways using the LoRa modulation technique, sending data
packets at low data rates.
• Gateways: Gateways serve as intermediate points that receive data packets from end devices
and transmit them to a centralized network server. They are typically connected to the internet
via wired or wireless connections.
• Network server: The network server manages communication between gateways and end
devices. It handles functions such as authentication, encryption, and the routing of data packets
to their respective application servers.
• Application server: The application server is responsible for processing data received from
the network server and performing specific actions based on the data. It interfaces with an
end user’s application or backend system to present data, trigger alerts, perform analytics, or
control devices. The application server can be hosted on the cloud or on-premises.
In this section, we have discussed LoRaWAN components in detail, and in the next section, we are going
to explore the hardware and sensors that are required to execute the practical exercise of this chapter.
140 Project #3 – a Remote Asset Tracking Application with LoRaWAN
The Arduino MKR WAN 1300 provides seven analog pins, which start with A (A0, A1, and so on), and
eight digital input/output pins, which start with D (D0, D1, and so on), with built-in battery charging
and a lithium polymer (LiPo) battery connector for standby power, which helps developers build
prototypes and solutions for remote monitoring/operations without worrying about power backups. For
further updates and the latest product development news, please visit the official website at https://
store.arduino.cc/products/arduino-mkr-wan-1300-lora-connectivity.
Essential hardware – sensors and development boards 141
Arduino’s latest development board is the MKR WAN 1310, which contains the same processor and
module for LoRa communication as the MKR WAN 1300. However, the MKR WAN 1310 has an
updated in-battery charger, 2 MB of Serial Peripheral Interface (SPI) flash, and enhanced power
consumption. This board is specially designed for IoT devices and is quickly growing in popularity
in different regions. For its complete details and specifications, visit https://store.arduino.
cc/products/arduino-mkr-wan-1310.
In this chapter, we will track the device via GPS coordinates. To get the GPS coordinates, we will
use the GY-GPS6MV2 GPS module, which is based on the NEO-6M u-blox chip. The GPS module
operates on both a software serial and a hardware serial, but the MKR WAN 1300 provides a built-in
hardware serial, so we will use ins 13 and 14 to communicate with the GPS module shown in Figure 6.3.
The GPS module provides latitude, longitude, satellite count, altitude feet, and speed-per-mile
properties. These properties will be displayed on a dashboard for proper asset tracking. This module was
developed in China and is available at affordable prices, but many other organizations are developing
GPS modules that are also based on the NEO-6M u-blox chip, such as SparkFun, Seeed Studio, and
Adafruit. Figure 6.3 shows a NEO-6M u-blox GPS module and its pinout diagram:
Figure 6.3 – The GY-GPS6MV2 NEO6MV2 GPS module and a pinout diagram
142 Project #3 – a Remote Asset Tracking Application with LoRaWAN
The preceding diagram describes the pinout layout of the GPS module. Pin #1 is the GND pin that
connects with the onboard GND pin of the MKR WAN 1300. Pin #2 and Pin #3 are TX and RX,
respectively, and will connect to Pin #13 and Pin #14 of the MKR WAN 1300, respectively. Pin #4,
VCC, works with both an onboard VCC and the 5V pins of the MKR WAN 1300. You can solder the
male headers with the GPS module or directly solder the cables without any header pins.
Important note
The GPS module works best in an outdoor environment. Make sure there are no rooftops above
during testing and deployment to properly receive a signal from satellites.
If you are using the module in the lab, then there will be a chance that the GPS module will not
work properly. Remember that there is a built-in light on the GPS module that starts blinking
when you receive signals from satellites.
In this section, we have discussed the development board and GPS module in detail, including their
pinout diagrams. In the next section, we will start exploring how to connect the GPS module with
the MKR WAN 1300.
Figure 6.4 – The MKR WAN 1300 and GPS module schematic
While Figure 6.4 illustrates the design of the MKR WAN 1300 and GPS module, we have created Table
6.1 for easier understanding, which illustrates (in row format) how to connect pins.
The preceding design provides a full overview of how you can connect a module to a development
board. According to our design, we have 5V and GND pins going from the development board to the
GPS module. The GPS module TX pin is connected to the RX pin (Pin #13), and the GPS module RX
pin is connected to the TX pin (Pin #14) of the development board. Finally, we built our prototype
by using a breadboard, which is shown in Figure 6.5:
Figure 6.5 – The final prototype MKR WAN 1300 and GPS module
After soldering the male headers to the GPS module, connect the pins according to the schematic
diagram. There is only one sensor, so there is no requirement for the Veroboard. Next, we will test
the GPS module using Arduino’s Serial Monitor tool to verify that our GPS module works properly
and gets values from GPS satellites.
1. For module testing, we need the Serial Monitor tool to verify whether the GPS module works
properly or not. Click on the Tools menu and select Serial Monitor. Select the Arduino MKR
WAN 1300 board from Tools | Board | Arduino SAMD | Arduino MKR WAN 1300 in the
Arduino IDE.
2. Select the port of the MKR WAN 1300.
3. Next, we need to install the library for the GPS module in the Arduino IDE. Navigate to Sketch
| Include Library | Manage Libraries. Type tinygps into the search bar.
Designing the project architecture 145
4. After searching, the Library Manager brings up a lot of libraries. Select the TinyGPSPlus library
and install its latest version. The library comes with a lot of examples, and all of them are based
on a software serial. However, Arduino SAMD boards provide a hardware serial. Therefore, I’ve
modified the code to use a hardware serial to communicate with the GPS module.
5. Download the code from the book’s official GitHub repository, and under the chapter#6
folder, open the MKR-WAN-1300-NEO-6M-GPS-Module ZIP folder, extract it, and upload
the code to the development board:
while(Serial1.available()>0)//While there are characters to come
from the GPS
{
gps.encode(Serial1.read());//This feeds the serial NMEA data
into the library one char at a time
}
if(gps.location.isUpdated())//This will pretty much be fired
all the time anyway but will at least reduce it to only after a
package of NMEA data comes in
{
//Get the latest info from the gps object which it derived
from the data sent by the GPS unit
Serial.println("Satellite Count:");
Serial.println(gps.satellites.value());
Serial.println("Latitude:");
146 Project #3 – a Remote Asset Tracking Application with LoRaWAN
Serial.println(gps.location.lat(), 6);
Serial.println("Longitude:");
Serial.println(gps.location.lng(), 6);
Serial.println("Speed MPH:");
Serial.println(gps.speed.mph());
Serial.println("Altitude Feet:");
Serial.println(gps.altitude.feet());
Serial.println("");
}
In the setup, we have initialized Serial and Serial1. Serial is used to display the content to the
Serial Monitor (the magnifier icon in the top right of the Arduino IDE) on screen, while Serial1 is
the hardware serial that is used to communicate with the GPS module. The preceding code belongs
to the loop() method.
First, the GPS module will read data from satellites using the Serial1.read() method and encode
it via the gps.encode() method. Serial1 only reads one character at a time, so it will take a
little bit of time for the updated values. Then, we will verify whether there is any update in Latitude
and Longitude coordinates by using the gps.location.isUpdated() method. If there is a
change, then the data will be printed on the Serial Monitor.
Important note
Make sure your GPS module is placed in an open environment where you have a clear sky,
without any obstruction such as a roof or anything that stops you from receiving proper signals
from satellites.
The GPS module has an onboard built-in LED that starts blinking when it starts receiving data
from GPS satellites.
The same code will work with the MKR WAN 1310 without any modification.
Designing the project architecture 147
Figure 6.7 shows the Serial Monitor with values from the GPS, which includes Latitude, Longitude,
and other parameters:
The preceding figure shows the data that is received by the GPS module from GPS satellites and printed
on the Serial Monitor. The data includes the satellite count, the latitude and longitude that represent
the location coordinates, the speed in MPH based on current and previous GPS coordinates, and the
altitude in feet.
In this section, we tested the NEO-6M u-blox GPS module in the Arduino IDE. First, we installed
the TinyGPSPlus library for the module, and later, we used the aforementioned code for the
development board, which shows the readings on the Serial Monitor. In the next section, we will start
with the Thing setup in the Arduino IoT Cloud.
148 Project #3 – a Remote Asset Tracking Application with LoRaWAN
Figure 6.8 – Remote asset tracking using the LoRaWAN Thing setup
Set up a new Thing with the name A remote asset tracking using LoRaWAN, and then follow the
next steps, which will take you to the next subsections to create variables, an associate device network
configuration, and finally, code. We have marked the preceding figure with red boxes and numbers
according to the following steps.
Firstly, we need to set up four cloud variables – Location, AltitudeFeet, SatelliteCount,
and Speed. The complete details regarding cloud variables are available in the following subsection.
Setting up the Thing, device association, cloud variables, and code 149
After that, we need to associate the device with the Thing. In the current project, we will use the MKR
WAN 1300, so the process will be the same as the one used for Arduino boards, but here, we will
see some different options due to LoRaWAN. The complete details are available in the Associating a
device section.
Cloud variables
The following table explains all the properties of the variables that we need to create. For the location,
we need two different variables to store the latitude and longitude, but thanks to the Arduino IoT
Cloud extended group of variables, we have a Location-type variable. Then, make sure each variable
matches the declaration in the table; otherwise, you will need to modify the example code according
to your naming.
As shown in Table 6.2, when creating the cloud variables, we set the permission to Read-Only. Although
we have the Read/Write option, in this project, we only want to receive data from the device instead
of modifying the data via the dashboard. That’s why read-only mode is used – to avoid issues in data
consistency. Update policy is set to On Change, as the device will send the data when the GPS module
receives new data from satellites.
In this section, we discussed what type of cloud variables are required for this project. Here, we listed
four cloud variables of different types but in read-only mode, as we only want to extract the values
from the device. In the next subsection, we will associate the MKR WAN 1300 with the Thing.
150 Project #3 – a Remote Asset Tracking Application with LoRaWAN
Associating a device
After creating the variables, it’s time to add the device and associate it with the Thing:
1. Before adding the device, connect the development board to the computer and open the Arduino
Create Agent application. Figure 6.9 shows a popup in which we have options to either select
the existing device for association or set up a new device that is not available on the list.
In our case, we already have different devices in the portal, but we want to add a new one, MKR
WAN 1300, so just click on SET UP NEW DEVICE to configure the new device in the account.
Setting up the Thing, device association, cloud variables, and code 151
2. Then, you will see three options in the popup. The first option is Arduino board, the second
option is Third party device, and the third option is Any Device, which is for non-compatible
devices. This means you can now use all types of Arduino devices as well as third-party devices
with the Arduino IoT Cloud, which supports Python, MicroPython, and JavaScript.
3. Click on Arduino board (marked with a red box in Figure 6.10) and the next step will automatically
detect the MKR WAN 1300 board, which we are using in this chapter. Before adding the device,
make sure that Arduino Create Agent is running on your machine. Figure 6.11 shows that the
Arduino IoT Cloud detected the MKR WAN 1300.
152 Project #3 – a Remote Asset Tracking Application with LoRaWAN
When the popup finds the device, click on the CONFIGURE button, which will take you to
the next screen.
4. Figure 6.12 shows a screen that provides some details about the The Things Stack portal link.
You will also see a message saying that you need an active LoRaWAN gateway for the MKR
WAN 1300 to communicate with the Arduino IoT Cloud.
Setting up the Thing, device association, cloud variables, and code 153
If you already have the gateway set up, then that’s fine; otherwise, in the Configuring the The
Things Indoor Gateway section, read up on how to set up the The Things Indoor Gateway, which
will provide connectivity to your MKR WAN 1300 development board.
This message also informs you that the Arduino IoT Cloud will automatically configure your
device in the The Things Stack portal.
5. After associating the device, you will receive an email with a username and password, as well
as a URL for the The Things Stack portal login, which contains all the information about
LoRaWAN nodes. Here, the Arduino IoT Cloud will automatically add the MKR WAN 1300
to the The Things Stack portal after the final steps. Next, Figure 6.13 shows that we need to
select a frequency for our device.
154 Project #3 – a Remote Asset Tracking Application with LoRaWAN
Here, I assigned the name LoRaWanGPSTracker to the device, but you can use any name
related to your project structure. After assigning the name, click on the NEXT button.
7. Then, another popup will appear, as shown in Figure 6.15, which will prepare your device for
the Arduino IoT Cloud.
Here, the Arduino IoT Cloud configures the MKR WAN 1300 via Arduino Create Agent. It
will take one to two minutes to set up the development board with the necessary configuration.
156 Project #3 – a Remote Asset Tracking Application with LoRaWAN
8. When the device has been configured successfully, you will see the following popup. Just click
on the DONE button and your device will be associated with your Thing.
In this section, we have associated the MKR WAN 1300 with our Thing. We have also seen a lot of
new options regarding LoRaWAN such as frequency, gateway, and so on. In the upcoming sections,
we will discuss the network and code.
Network
In previous chapters, after associating the device with the Thing, we configured the network settings
for device communication. However, this time, we don’t need to configure any network settings,
as the device will be configured automatically when we upload the sketch to the MKR WAN 1300
development board. At first, you will see an empty area in the Network configuration, as shown in
Figure 6.8, but after the sketch uploads, you will see the LoRaWAN network configuration parameters.
Setting up the Thing, device association, cloud variables, and code 157
Coding
The code for this chapter is available in the book’s official GitHub repository. Download the A_
remote_asset_tracking_using_LoRaWAN_aug30a.zip file and import it into your
Arduino Web Editor.
You can download the code and put it into your Thing by navigating to the Sketch tab. Here, I
will explain the main workflow in which we are initializing all the variables and serial instances in
the setup() method. Remember to never try to use the delay() method, as it will block the
ArduinoCloud.update() method:
TinyGPSPlus gps;
unsigned long previousMillis = 0;
const long interval = 30000; //milliseconds
In the preceding code snippet, we declare the gps instance and two variables, which wait for 30000
milliseconds (30 seconds) before the next readings are taken without blocking the code.
Now, we will explore the loop() method. Here, we call the FetchGPS() method every 30 minutes,
which will be carried out by comparing currentMillis and previousMillis without the
use of delay():
In the following snippet, I have just picked a small part of the code from the FetchGPS() method.
Here, I assign the latest values from the GPS module to the Arduino cloud variables, which will be
used to send data to the cloud as well as print it on the Serial Monitor:
if (gps.location.isUpdated())
{
altitudeFeet = gps.altitude.feet();
satelliteCount = gps.satellites.value();
speed = gps.speed.mph();
location = Location(gps.location.lat(), gps.location.lng());
Location cordinates = location.getValue();
.
.
.
}
158 Project #3 – a Remote Asset Tracking Application with LoRaWAN
Upload the code to the device, and open up the Arduino Web Editor Serial Monitor to verify the
values. After successfully uploading the data to the cloud, it’s time to set up a beautiful dashboard for
web and mobile for end users.
Important note
If you used different naming when declaring the variables, update the code according to your
naming scheme. However, it’s recommended to first follow all the steps in the book and change
the cloud variable names later, modifying your code respectively.
Never try to use the delay() method, which will create a block for the ArduinoCloud.
update() method.
The Arduino IoT Cloud only updates values on its dashboard whenever the variable value
changes. For example, if the GPS location is the same after some time, then it means an asset
has not moved from its original location. Then, the Arduino IoT Cloud will not record the
value, so don’t get confused if values don’t change on the map. Another benefit of this feature
is you will not get duplicate data when you export the content.
The same code will work with the MKR WAN 1310 without any modification. However, in
this instance, you need to associate the MKR WAN 1310 device with the Thing instead of the
MKR WAN 1300.
In this section, we have explored our code step by step to understand how it works. In the next section,
we will set up the The Things Indoor Gateway. If you already have the gateway in your region/area,
then you can skip this, but if you don’t have any gateway near your location, then you need to set up
the gateway; otherwise, your MKR WAN 1300 will not be able to communicate with the Arduino
IoT Cloud.
1. Open your gateway box, set it up with a power cable, and turn on the gateway. If you are using
a brand-new gateway, then it will be in setup mode; otherwise, you can put the gateway into
setup mode by pressing the SETUP button for a few seconds when the orange and green lights
start blinking. This means the gateway has entered setup mode.
2. Select the Wi-Fi network of your the The Things Indoor Gateway, and connect to it. The Wi-Fi
password is written on the back of the device. Figure 6.17 shows the Setup page for the The
Things Indoor Gateway.
Configuring the The Things Indoor Gateway 159
After connecting to the indoor gateway, open up your browser and type http://192.168.4.1.
This will open up the MiniHub Setup page, as shown in the preceding figure. Click on the plus
icon (+) to select the Wi-Fi network that is connected to the internet, and provide its Wi-Fi
password. Then, click on the SAVE & REBOOT button. It will take some seconds to restart,
and eventually, your LoRaWAN indoor gateway will be connected to the internet via your
selected Wi-Fi network.
160 Project #3 – a Remote Asset Tracking Application with LoRaWAN
3. Now, it’s time to configure the LoRaWAN gateway in the The Things Stack portal, as shown
in Figure 6.18.
When you associate the MKR WAN 1300 to the Thing in the Arduino IoT Cloud, you will
receive an email from the The Things Stack Cloud that contains the portal URL, along with
your username and password details. Log in to the portal, where you will be given a clusters
list to add your gateway to a recommended cluster. In the Associating a device section, I chose
the Europe 863-870 MHZ (SF9 for RX2 - recommended) frequency for the MKR WAN 1300,
so here, I will choose Europe 1 for my gateway. This way, my gateway and MKR WAN 1300
development board both sit under the same cluster.
4. After choosing the cluster, you will be redirected to the main page of the portal. From here, we
will start adding the gateway, as shown in Figure 6.19.
On the main page, we have some menus and two big icons, as shown in the preceding figure.
From there, click on the Go to gateways icon.
5. Then, we will be on the page that shows the complete list of gateways, as well as the option to
register a new gateway, as shown in Figure 6.20.
Firstly, we need to select the owner from the Owner dropdown. Here, you will see two names.
One is your personal username, and the other is arduino-iot-cloud-user. Just select your
personal username, as you are the main person adding the gateway. In the next field, insert
the Gateway EUI details. The EUI will be written on the back of the gateway. After that, click
on the Confirm button.
7. Now, we will verify our gateway and select the frequency plan, as shown in Figure 6.22.
You will see the Claim authentication code field at the top. Here, we need to provide the
gateway with a Wi-Fi password for authentication. You can get the gateway Wi-Fi password
from the back of the gateway, from where you previously took it to connect with the device’s
Wi-Fi network.
Now, we need to select the frequency plan for our gateway. We already selected Europe
863-870 MHZ (SF9 for RX2 - recommended) during the MKR WAN 1300 association, so
we will select the same frequency from the dropdown. After selecting the frequency, click on
the Claim gateway button.
Creating web and mobile dashboards 163
8. After successfully registering the gateway, we will see a page like the one in the following figure,
which provides you with the gateway connectivity status, as well as Live data, Created at, Last
updated at, and lots of other information.
Figure 6.23 – The LoRaWAN gateway successfully registered on The Things Network
In this section, we explored how to set up the The Things Indoor Gateway step by step. In the next
section, we will create a dashboard for our Thing on mobile and web to track our assets.
We have four readings from the GPS module to visualize. Here, I have used four widgets: one gauge,
two values, and one map. The gauge widget shows Speed Per Mile, while the two value widgets have
been used to display Altitude Feet and Satellite Count. The map widget was used to display Location
based on the latitude and longitude coordinates, which are stored in a cloud-based location
variable. Currently, the map widget is only capable of displaying the location of the asset device based
on coordinates; if you have multiple assets to track, then you need to set up multiple map widgets
according to the number of tracking devices.
Well, this is the last section of our chapter. Here, we created a stunning dashboard for GPS tracking that
shows Location using a map widget on the dashboard, Speed Per Mile, and some other parameters.
What next?
We still have a lot of options available to explore, but now it’s your turn to use different sensors and
development boards to do some more experiments and learn from them. In this chapter, we only used
one GPS module, which gave us only four parameters, but there are a lot of GPS modules on the market
that provide a wide variety of functionalities, such as working under a roof and accuracy features.
Summary 165
While monitoring the location of assets, some other parameters are very important to monitor in
different industries, such as temperature and humidity, which are very important in food and medical
products. CO2 and liquefied petroleum gas (LPG) gases are very important to monitor during fuel
transportation. Try using different sensors with a GPS module to set up different tracking prototypes
for different industries.
Summary
In this chapter, we explored how to develop an asset-tracking system using LoRaWAN and a GPS
module. We set up the Thing, which included cloud variable creation, device association, the The
Things Indoor Gateway, and coding a development board. Then, we created a dashboard to visualize
the Thing readings with different types of widgets to display current readings. The most important
widget of the chapter is the map widget, which is very interesting and important for plotting the
current location of the device.
GPS tracking is a very important topic that helps us to develop a device for our assets, assisting us
in asset tracking and monitoring. We can use LoRaWAN for a specific region, as it has a longer
range, but that range only operates in a specific area, unlike other wireless technologies. This chapter
demonstrated how we can display the location of a device on a dashboard, giving you more confidence
to build more asset-tracking solutions.
In the next chapter, Enabling Communication between Different Devices, we will explore how the
Arduino IoT Cloud makes it easy to send data between devices. Using this method, we will sync IoT
nodes with each other for seamless operations.
Part 3:
Exchanging Data
between Nodes
and Cloud Applications
This third part of the book describes how to exchange data between IoT nodes provisioned on the
Arduino IoT Cloud and between the Arduino IoT Cloud and external cloud applications.
These functionalities are required in many real cases to build a distributed and reliable network, to
implement some interdependent visualization and logic on the IoT application, and to expand the
functionalities of the Arduino IoT Cloud with external tools.
This part has the following chapters:
Technical requirements
The following are required to complete this chapter’s exercise:
We will use the Arduino Web Editor for coding, which includes a large collection of development
boards and sensor libraries, and Arduino IoT Cloud for thing and dashboard setup. The chapter code
is available in the official book GitHub repository by following this link: https://github.com/
PacktPublishing/Arduino-IoT-Cloud-for-Developers.
• Direct communication: In traditional IoT architectures, devices send data to a cloud platform,
where it is processed and potentially shared with other devices. D2D communication allows
devices to talk to each other directly, bypassing the cloud when necessary.
• Low latency: D2D communication can reduce latency because data doesn’t have to travel to
a remote server and back. This is crucial in applications where real-time or near-real-time
responses are required, such as in industrial automation or connected vehicles.
• Efficiency: By enabling devices to communicate directly, it can reduce the load on cloud servers
and bandwidth usage, making the IoT system more efficient and cost-effective.
• Offline operation: D2D communication can work even when devices are not connected to the
internet or the cloud. This can be especially useful in scenarios where intermittent connectivity
is common, such as in remote areas or emergency situations.
The benefits of Arduino IoT Cloud thing-to-thing communication 171
In summary, D2D communication in IoT cloud environments allows IoT devices to communicate
directly with each other, which provides benefits such as reduced latency, improved efficiency, and
offline operation. However, it also requires careful planning and security measures to ensure the
reliability and integrity of the communication network.
In this section, we explored the benefits and challenges of D2D communication, which is very
important in IoT infrastructure and solution development. In the next section, we will explore what
type of option Arduino IoT Cloud is providing for TTC.
• Ease of integration: Arduino IoT Cloud provides a user-friendly interface for connecting and
configuring IoT devices, making it easier to establish communication between devices. Users can
quickly set up and manage the connections between their Arduino boards and other IoT devices.
• Remote control: You can use TTC to control one Arduino device from another. For example,
you could use one Arduino device to control a light bulb in another room.
• Scalability: Arduino IoT Cloud allows you to scale your IoT projects easily. You can add new
devices to your network and configure their communication parameters without extensive
programming, making it suitable for both small-scale and large-scale IoT deployments.
172 Enabling Communication between Different Devices
• Reduced latency: Direct communication between IoT devices within the same network can
significantly reduce latency compared to sending data to an external cloud server and back.
This is crucial for real-time applications, where low latency is essential.
• Energy efficiency: Arduino IoT Cloud allows you to optimize the power consumption of your
devices by controlling when and how they communicate with each other. This can extend the
battery life of battery-powered IoT devices.
• Customizable logic: You can program custom logic for TTC to suit your specific project
requirements. This flexibility enables you to implement complex behaviors and automation
in your IoT system.
• Security: Arduino IoT Cloud provides security features to help protect the communication
between your devices, including encryption and authentication mechanisms. This ensures that
data exchanged between devices remains secure.
• Cost efficiency: By reducing the reliance on external cloud services and minimizing data
transfer costs, Arduino IoT Cloud can be a cost-effective solution for IoT projects, especially
when dealing with a large number of devices.
• Compatibility: Arduino IoT Cloud supports a wide range of Arduino boards and compatible
hardware, making it accessible to a broad user base. This compatibility simplifies the process
of implementing TTC for Arduino-based IoT projects.
In summary, Arduino IoT Cloud simplifies TTC in IoT projects, providing features such as ease of
integration, scalability, reduced latency, energy efficiency, offline operation, customization, security,
cost efficiency, and broad hardware compatibility. These features make it a valuable platform for
developing and managing IoT systems that rely on direct communication between devices.
In this section, we have discussed the benefits of Arduino IoT Cloud TTC. In the next section, we will
explore what hardware components we require to do this chapter’s exercise.
As shown in Figure 7.1, we use one WeMos D1 mini development board, which is based on ESP8266,
and the whole project is demonstrated in Chapter 4. The purpose of using different types of boards
in this chapter is to demonstrate how easy it is to sync the cloud variables across different types of
development boards. In the next section, we will talk in detail about project architecture.
Project architecture
In this section, we will discuss how cloud variable synchronization works. As shown in Figure 7.1,
we have taken the project from Chapter 4. In that project, we set up a device that monitors outdoor
temperature, humidity, and air quality. Now, we want to share the outdoor temperature with our indoor
device, which is the MKR Wi-Fi 1010. To make things easier, we just used LEDs with MKR Wi-Fi 1010,
which is shown in Figure 7.2. Our indoor device will turn on the red LED if the temperature exceeds
the specified threshold and turn on the green LED if it comes down below a specified threshold. You
can also use relays instead of LEDs to control the heating and cooling system of your room.
We already have one complete thing in Arduino IoT Cloud that is working, but now we need to create
another thing for MKR Wi-Fi 1010 named Indoor MKR Wi-Fi 1010 with a bunch of cloud variables.
We will then sync the temperature cloud variable of the Indoor MKR Wi-Fi 1010 thing with the Sense
the Environment thing, which was created in Chapter 4.
In the preceding sections, we discussed the module and development board in detail. Now, it’s time to
begin the exercise. In hardware development, before we start working with sensors and development
boards, we need to develop design concepts to get a better understanding of how things will connect.
There is a lot of software available for designing and developing design concepts for an electronics
project, but in this case, we will use Fritzing.
174 Enabling Communication between Different Devices
In the following subsection, we will talk about the schematics of a project while explaining how to
connect pins with a development board.
In Figure 7.2, we have one common ground from MKR Wi-Fi 1010, which is shared with both LEDs
using a yellow line. The red LED is connected to MKR Wi-Fi 1010 by using Pin #6 and the green LED
is using Pin #7 of the MKR Wi-Fi 1010 development board.
In this section, we have discussed how cloud sync works and how we connect the LEDs with MKR
Wi-Fi 1010. In the next section, we will set up the Thing for MKR Wi-Fi 1010 as well as device
association and network configuration; and, most importantly, we will create the cloud variables and
sync them with other things.
Setting up a Thing 175
Setting up a Thing
After setting up the hardware, it’s time to set up a thing in Arduino IoT Cloud. For this project, we
need three cloud variables. Later on, we will associate MKR Wi-Fi 1010 with our thing. Next, we will
perform the Wi-Fi network configuration. Figure 7.3 shows a complete overview of the Thing:
Set up a new thing called Indoor Device MKR Wi-Fi 1010. In Figure 7.3, the following steps
are marked with red boxes. Follow these steps to create variables, associate a device, configure the
network, and, finally, write the code:
1. Firstly, we need to set up three cloud variables for the green LED, the red LED, and temperature
(which will be synced with another thing cloud variable). A more detailed discussion of cloud
variables is in the upcoming section.
2. After that, we need to associate the device with the Thing. In the current project, we are using
MKR Wi-Fi 1010. More details are available in the Associating a device subsection of this chapter.
176 Enabling Communication between Different Devices
3. After attaching the device, we need to make the device network-ready by providing an SSID
and a password for the Wi-Fi network. Just click on the Configure button (if the network is
empty, then you will see the Configure button. Otherwise, you will see the Change button)
and you will see the popup for network settings.
We have discussed the process of setting up a thing, and all these steps will be explained in detail in
the proceeding subsections. We will start with the Cloud variables subsection, where we will create
cloud variables for our thing as well as synchronize them.
Cloud variables
The following table describes all the properties of the cloud variables that we need to configure. For this
project, we need three cloud variables, as listed in Table 7.1. Next, make sure each variable matches the
Declaration in the table; otherwise, you need to modify the example code according to your naming.
When we created the cloud variables, we made the permission read-only for all variables except
Temperature because we need this cloud variable to sync with the Temperature cloud variable
of the Sense the Environment thing in Chapter 4. That’s why this variable’s permissions are set to Read
& Write. Update Policy is set to On change for all variables.
Use Table 7.1 to create the GreenLed and RedLed cloud variables. The creation of the Temperature
cloud variable will be discussed step by step; we are going to sync this cloud variable with the Thing cloud
variable from Chapter 4. Figure 7.4 shows the first step of creating the Temperature cloud variable.
In this step, we will assign a name to the cloud variable, which is shown in Figure 7.4. Next, we will
click on Sync with other Things. This will open a new popup, which is shown in Figure 7.5.
In this popup, you will find a complete list of cloud variables across all the things that are available in
your Arduino IoT Cloud. To prevent complexity and errors, select a specific thing. We selected the
Sense the Environment thing from the dropdown, which is marked by a red box in Figure 7.5. After
selecting the Thing from drop down, you will only see the associated cloud variable of that thing in
popup. Click on the Temperature cloud variable checkbox and then click on the SYNCHRONIZE
VARIABLES button. Figure 7.6 shows the final popup, where you will find the final status of the cloud
variable sync status.
Setting up a Thing 179
In Figure 7.6, you will see the status of the cloud variable sync status, which is marked by a red box.
Remember that for sync variables, you must choose Read & Write permission or it will not work
properly. Then save the cloud variable, and we are good to go. After going through these steps, you
should have an idea of how easy it is to sync cloud variables across multiple things within seconds by
just using a simple interface.
Important note
Remember that for sync variables, you must choose the Read & Write permission or it will
not work properly.
180 Enabling Communication between Different Devices
In this section, we discussed the types of cloud variables that are required for this project. We listed
three cloud variables of different types and also discussed in detail how to sync the cloud variable
from one thing to another thing. Next, we are going to associate the MKR Wi-Fi 1010 with the Thing.
Associating a device
After creating the variables, it’s time to add the device and associate it with the Thing:
1. Before adding the device, connect the development board to the computer and open the Arduino
Create Agent application. Figure 7.7 shows a popup where we have two options: either select
the existing device for association or set up the new device if it is not available in the list:
In our case, we already have different devices in the portal, but we want to add a new MKR
Wi-Fi 1010. Just click on SET UP NEW DEVICE to configure a new device in the account.
Setting up a Thing 181
2. Next, you will see the three options in the popup. The first option is Arduino board and the
second option is Third party device. The third option is Any Device, which is for non-compatible
devices. It means you can use any type of Arduino device, as well as third-party devices with
Arduino IoT Cloud, which supports Python, MicroPython, and JavaScript.
3. Select the right option from the popup for your project. For this example, click on Arduino
board because in this chapter, we are using an MKR Wi-Fi 1010 board. Before adding the
device, make sure Arduino Create Agent is running on your machine. Figure 7.9 shows that
Arduino IoT Cloud detected the MKR Wi-Fi 1010 device.
182 Enabling Communication between Different Devices
When the popup displays that it has found the device, just click on the CONFIGURE button,
which will take you to the next configuration step, where you will provide the name of the
device, and later, another popup will perform some configuration on your development board
and associate the development board with Arduino IoT Cloud. Once this is done, a successful
device association message will be displayed.
4. When the device is configured successfully, you will see a popup saying congratulations. Just
click on the DONE button and your device will be associated with your thing.
In this section, we associated the MKR Wi-Fi 1010 device with our thing, and in the upcoming sections,
we will talk about the network and code.
Network
After attaching the device to the Thing, we can see that the device is offline. To bring it online, we
need to provide Wi-Fi details. The following screenshot shows the network configuration popup,
which only consists of two fields:
Setting up a Thing 183
On the Thing page, shown in Figure 7.10, on the Network tab, click on the CONFIGURE button,
which will take you to the Configure network popup with two fields, Wi-Fi Name and Password.
Type the Wi-Fi SSID and password, and then click on the SAVE button.
In this section, we have configured the network for our device, which is MKR Wi-Fi 1010. In the next
subsection, we will create the cloud variable.
Coding
This chapter’s code is available in the official GitHub repository for the book. Download Indoor_
Device_MKR_Wi-Fi_1010_sep07a.zip and import it into your Arduino Web Editor.
You can download the code and put it into your thing by navigating to the Sketch tab. Here, I will
explain the main workflow. First, we have defined two constants for the red and green LED pins called
RLED and GLED in the following snippet and assigned them pin numbers 6 and 7, respectively:
#define RLED 6
#define GLED 7
184 Enabling Communication between Different Devices
Then, we initialize all the required pins and methods in the setup() method. Specifically, we are
changing the modes of the pins to output by using the pinMode() method:
void setup() {
pinMode(RLED, OUTPUT);
pinMode(GLED, OUTPUT);
setDebugMessageLevel(2);
ArduinoCloud.printDebugInfo();
}
The next important method is onTemperatureChange(). Whenever the value of the Temperature
cloud variable changes on the Sense the Environment thing, it will be automatically synced with the
Temperature cloud variable of the Indoor Device MKR Wi-Fi 1010 thing. Then, when the value
changes, this method will be called:
void onTemperatureChange() {
// Add your code here to act upon Temperature change
if(temperature>30)
{
//if Temperature is more then 30 then turn on the Red LED and
turn off Green LED
redLed=true;
greenLed=false;
}else{
//If Temperature is 30 or less then turn on Green LED and turn
off Red LED
redLed=false;
greenLed=true;
Setting up a Thing 185
}
digitalWrite(RLED,redLed);
digitalWrite(GLED,greenLed);
}
In the preceding code snippet, we have defined the manual threshold for temperature. If the
temperature value is greater than 30 degrees Celsius, then assign redLed the true value and
greenLed the false value; otherwise, assign redLed with false and greenLed with true.
At the end of the method, we are controlling the LEDs according to the redLed and greenLed
values. Here, you can use relays instead of LEDs to control the heating and cooling system of your
indoor environment.
Upload the code to the device and you will see that either the red or green LED will be turned on,
depending on the temperature. After successfully uploading data to the cloud, it’s time to set up a
beautiful dashboard for web and mobile for the users. This time, we will create a dashboard that will
show the values of two things’ cloud variables.
Important note
If you used different naming in the variable declaration, then update the code according to
your naming scheme. But it’s better if you first follow all the steps according to the book and
later change the cloud variable names and modify your code.
Never try to use the delay() method, which will create a block for the ArduinoCloud.
update() method. Also, don’t put the code in an end-of-loop method as it will create a delay in
the pulse sensor readings.
In this section, we have explored the code, and we are using the Temperature cloud variable, which
is synced with the Temperature cloud variable in Chapter 4, and we are turning on and off the
LEDs according to temperature value. In the next section, we will explore how to display the cloud
variables of multiple things on a single dashboard.
186 Enabling Communication between Different Devices
We have three different readings, Temperature, Humidity, and Air Quality, from the Sense the
Environment thing and two readings, RedLED and GreenLED, from the Indoor Device MKR Wi-Fi
1010 thing. As the temperature from the Indoor Device MKR Wi-Fi 1010 thing is synced with the
Sense the Environment thing, we are only displaying one temperature value here. For every reading,
we use different widget controls to demonstrate how they all work. But for the LED status, we used
an LED widget control.
The main thing to note about this dashboard is that we are using values from two different things
but the same dashboard to visualize the values. This example demonstrates that we can display the
values from multiple things on a single dashboard. Figure 7.12 shows how easy it is to link any cloud
variable to a widget control.
Limitations of cloud variable/property synchronization 187
Figure 7.12 shows how to link the RedLed cloud variable from Indoor Device MKR Wi-Fi 1010 to
a widget. But, as you can see, you can select any cloud variable from any thing and link it with the
widget control. So, we can see how the Arduino IoT Cloud dashboard allows us to create a single
dashboard for multiple things easily.
In this section, we discussed how to set up a dashboard that contains widgets attached to multiple
things. In the next section, we will discuss limits and cloud variable synchronization in detail.
• Latency: TTC can introduce latency, which is the delay between when a change is made to a
variable on one device and when it is reflected on the other device. This can be a problem for
applications that require very low latency, such as controlling a robot in real time.
• Offline device challenges: Devices that are temporarily offline may miss important messages
or updates from other devices. Ensuring that devices can catch up on missed communications
when they reconnect to the network can be complex to implement.
188 Enabling Communication between Different Devices
When considering Arduino IoT Cloud for TTC in your IoT project, it’s essential to weigh these
drawbacks against the platform’s benefits and assess whether it aligns with your specific project
requirements and constraints. Additionally, exploring alternative IoT platforms and communication
solutions may be necessary to ensure the best fit for your needs.
In this section, we have discussed in detail the limitations of Arduino IoT Cloud TTC. In the next
section, we will explore how you can use TTC for different types of cloud variables.
What next?
We still have a lot of options available to explore, but now it’s your turn to use different sensors and
development boards to do some more experiments and learn from them. In this chapter, we have
only used one Temperature cloud variable synced between two things, but you can try using this
feature to sync multiple cloud variables with multiple things. Next, create a dashboard for multiple
things to visualize all the values in one place. We configured simple LEDs to turn on and off according
to the temperature, but you can also use relays to control the heating/cooling system of your indoor
home/office and warehouse environment, or you can create an alarm in case of a temperature increase
using this TTC feature.
Summary
In this chapter, we explored D2D communication and the benefits of Arduino IoT Cloud for thing-
to-thing communication. We discussed how to develop a solution for thing-to-thing communication.
We also explored how easy it is to sync the cloud variable with other things just using a GUI. We set
up a dashboard, where we linked the widget controls with multiple thing cloud variables. Finally, we
discussed the limits of Arduino IoT Cloud thing-to-thing communication in detail.
In the next chapter, we are going to explore how to use the Arduino IoT Cloud SDK. This chapter is
for developers who are eager to learn how to use Arduino IoT Cloud programmatically and develop
custom solutions using Arduino IoT Cloud or integrate Arduino IoT Cloud with third-party platforms.
8
Working with the Arduino IoT
Cloud SDK and JavaScript
Every platform provides APIs and SDKs to make their product compatible with other platforms, and
these endpoints are used by developers to create new functionalities to solve real-world issues. Likewise,
the Arduino IoT Cloud comes with its own built-in features and functionalities, but there are also
three different ways to extend the Arduino IoT Cloud platform’s functionality or make it compatible
with other tools and services: namely, REST APIs, SDKs, and webhooks.
In this chapter, we will talk about APIs and SDKs and how they work. Specifically, we will use the
Node.js SDK to illustrate different coding exercises. This chapter will cover Create, Read, Update, and
Delete (CRUD) operations for devices, Things, properties (aka variables), and dashboards. Beyond
that, we will explore some other features such as how to set/get values of properties.
By the end of this chapter, you will understand how to interact with the Arduino IoT Cloud platform
via an API or the Node.js SDK to create custom dashboards, interface with the data using other tools/
apps, and use the SDK for bulk device creation and management.
In this chapter, we’re going to cover the following main topics:
Technical requirements
There are no specific hardware requirements for this chapter as we are focusing on the SDK and will
work through different coding exercises to perform different operations on the Arduino IoT Cloud
platform using the Node.js SDK. To follow along with the coding and testing exercises, the following
software is required:
• Node.js
• The Node.js Arduino IoT Cloud module installed
• The VSCode editor
• Postman
• An Arduino IoT Cloud account
Postman will be used for cURL testing and authentication, which will help other developers when
doing request and response testing. For SDK coding, we will use Node.js and the VSCode editor. The
code for this chapter is available from the book’s official GitHub repository at https://github.
com/PacktPublishing/Arduino-IoT-Cloud-for-Developers.
In this chapter, we are going to focus specifically on the Node.js SDK. However, it’s important first
to give a proper overview of the Arduino IoT Cloud functionalities that can help developers make
better decisions during integration with other platforms. The Arduino team has created REST API
endpoints for different operations such as create, delete, list, update, and so on, and placed them into
different categories according to the main terms used on the Arduino IoT Cloud platform, such as
Thing, device, property, and so on. The developer can send a request to these endpoints via different
methods such as PUT, DELETE, or GET with different parameters, and in return they will get their
desired response from the Arduino IoT Cloud in JSON format that they can then use for further
product development.
REST APIs are like raw material for developers in that they need to process them by writing code in
their preferred language and sending and receiving requests and responses using the cURL library.
On the other hand, the Arduino team offers an SDK, which is basically a programming wrapper for
REST API endpoints. This allows us to save time as we get access to a lot of methods and sample
code to accomplish our tasks just using library methods. At the time of writing, the Arduino team has
developed SDKs for three programming platforms: Node.js, Python, and GoLang.
In this chapter, we will work with the Node.js SDK specifically to create different scripts to perform
CRUD operations on Things, devices, properties, and dashboards. We will also develop scripts that
allow you to fetch/set the latest values of Thing properties and much more. Overall, this chapter will
be fun for developers, as we are going to explore different techniques and methods that will help us
extend IoT operations from small scale to enterprise level.
In this section, we have discussed what type of features the Arduino IoT Cloud API/SDKs provide to
developers. In the next section, we will talk about API keys for authentication.
192 Working with the Arduino IoT Cloud SDK and JavaScript
Copy the Client ID and Client Secret values by clicking on the copy icons – never try to copy by
manual selection as the Client Secret is very long, so clicking the copy icon is the best option. Save
the both Client ID and Client Secret in a secure location and then click the checkbox confirming that
you have saved your keys. Lastly, click on DONE and you will see your API key in the panel – it’s
now ready for use.
Important note
A single API key is used to give access to all the Things and their variables. Having access to
all infrastructure with just one API key is handy, instead of having to create separate API keys
for each Thing, but you must take care of your key! This is a big security risk, as if you were to
lose the key, a hacker could gain access to your whole account.
In this section, we have set up and created API authentication keys consisting of a Client ID and
Client Secret. This section is most important, as without these keys we can’t use any APIs. In the next
section, we are going to try our first API call using the Postman tool.
A new window will be opened: provide a workspace name and description and set the visibility policy
according to your requirements. After creating the new workspace, navigate to File > New… and select
HTTP Request. Before sending any request to the Arduino IoT Cloud, an authentication token is
mandatory. Refer to the following screenshot: click on the Authorization tab and select OAuth 2.0
from the Type dropdown. Scroll down the Authorization page to find the Configure New Token
section and click on the Configuration Options tab under this section.
We need to provide three things under Configuration Options. Firstly, add the https://api2.
arduino.cc/iot/v1/clients/token URL to the Access Token URL field, then insert the
values that we generated previously in the Arduino IoT Cloud API into the Client ID and Client Secret
fields. Lastly, select Send client credentials in body from the Client Authentication dropdown. Now
click on the Advanced Options tab, where we will set the API audience who will receive the requests.
Figure 8.5 shows the Advanced Options where we need to provide the Arduino IoT Cloud authentication
URL with which we can authenticate and authorize requests.
Add the https://api2.arduino.cc/iot URL into the Audience field. After setting up the
configuration, click the Get new Access Token button. It will return either an error or a success
message. If there is any error, then please repeat all the steps one by one, ensuring the configuration
is as described previously. If you are successful, then click on Proceed and you will get your token
for authentication.
196 Working with the Arduino IoT Cloud SDK and JavaScript
After getting the authentication token, it’s time to do some experiments. The Arduino team has
documented all the endpoints with cURL and the Node.js SDK samples in different categories,
available at https://www.arduino.cc/reference/en/iot/api/. So here, we want to
see the list of cloud variables/properties for specific Thing. Open up the preceding API documentation
URL, find the API Methods – PropertiesV2 category, and click on propertiesV2List. Here you will
see cURL and the Node.js SDK. Copy the URL from the cURL sample, which is https://api2.
arduino.cc/iot/v2/things/{id}/properties?show_deleted=. Here we need to
replace {id} in the URL with the specific Thing ID (Figure 8.6). The Thing ID is available under the
Thing’s Metadata tab in the Arduino IoT Cloud. Add true to the end of the URL just after show_
deleted. After adding all the required data to the URL, it will look something like https://
api2.arduino.cc/iot/v2/things/8aee742e-4492-423d-9f19-79fec856b917/
properties?show_deleted=true.
Click on Send and you will receive a response from the Arduino IoT Cloud in JSON format containing
all the cloud variables properties of the Thing, including the property ID, name, type, last value of
the cloud variable, and so on:
The preceding screenshot shows the response in Postman. You can convert the response into plain text
as well as other formats including XHTML, HTML, and so on, but Postman has excellent visualization
functionality for JSON data responses. This way, developers can easily understand and tweak the nature
of the response and prepare the scripts according to their data structure. It also helps developers to
choose specific content from the response more quickly, reducing the time and effort required.
In this section, we used Postman to generate our first request to the Arduino IoT Cloud. We began
by configuring the API authentication keys in Postman and then requested the list of cloud variables/
properties of Thing. The Arduino IoT Cloud successfully returned the response with all the required data
in JSON format. In the following section, we will examine the SDKs available for different platforms.
Type the two preceding commands in the Terminal and wait for the installation to complete.
After a successful installation, open up VSCode and add the folder (where you have installed the
Node.js Arduino IoT Cloud SDK) to the workspace where you installed the Arduino IoT Cloud and
request-promise modules.
Navigate to the book’s official GitHub repository and download all the code from this chapter’s folder.
Copy the files into the VSCode Workspace folder and extract the downloaded .zip file. Navigate
to the start folder and open up the main.js file in VSCode.
Here we have two methods, getToken() and ThingProperty(). The getToken() method
will be same across the coding exercises and will be used to fetch the authentication token from the
Arduino IoT Cloud on the basis of the Client ID and Client Secret:
The preceding code snippet is from the getToken() method. Insert your Client ID in the client_id
variable and your Client Secret in the client_secret variable. Likewise, insert your Thing ID
and Property ID in the following code snippet under the ThingProperty() method. You can
get your Thing ID by navigating to Thing and then the Metadata tab in the Arduino IoT Cloud. The
property ID can be found by clicking on the cloud variable on the Thing page in the Arduino IoT Cloud:
Open the integrated terminal in VSCode and type the following command; Node will execute the
main.js code and provide a response in the console:
node main.js
You will receive the following response in the console if everything works fine:
If you receive a 401 error, it means your Client ID and/or Client Secret are not correct. If a 404
error is returned, it means you are not using the proper method to fetch property data. If you get a
500 error, it means the server is down or there is a network blockage for the Arduino IoT Cloud
from your ISP.
In the First try with Postman section, we discussed how to use Arduino IoT Cloud endpoints with
Postman for request/response tasks as well as installing the Node.js module for the cloud and testing
it with an example where we fetched the last value of the Thing cloud variable/property.
Building on this foundation, we are going to start a new journey where we will play around with the
Arduino IoT Cloud. Firstly, we will start with devices. In the next section, we will create, update,
delete, list, and view a specific device. Later in the chapter, we will do the same for Things, properties
(also known as cloud variables), and dashboards.
Creating a device
Firstly, we will start with device creation. T
h e documentation on device creation can be found at https://
www.arduino.cc/reference/en/iot/api/#api-DevicesV2-devicesV2Create.
Open create-device.js under the device folder in VSCode.
There are two methods in the code: one is getToken(), which is the same method as in all our
coding exercises and helps us to fetch the authentication token for requests. The second method is
CreateDevice(), which is responsible for device creation. Consulting the documentation, we
can see we need to initiate the api variable with the AiotApi.DevicesV2Api() object, which
is related to devices:
var DeviceProperties = {
'name':'Sense Home XIAO Series',
'connection_type':'wifi',
'fqbn':'esp32:esp32:XIAO_ESP32C3',
'type':'login_and_secretkey_wifi'
};
var options = {
};
api.devicesV2Create(DeviceProperties, options).then(function(data)
{
console.log('Device Created successfully. Returned data: ' +
util.inspect(data));
200 Working with the Arduino IoT Cloud SDK and JavaScript
}, function(error) {
console.error(error);
});
api.devicesV2Create is the method responsible for device creation and takes two parameters
as input. DeviceProperties covers things such as the device name, type, and Fully Qualified
Board Name (FQBN). Let’s start with name first – this could be anything you fancy, but avoid using
special characters. Next, we need to provide a choice for connection_type, such as Wi-Fi, GSM,
LoRa WAN, and so on. All available types are provided by the documentation. For fqbn, we need
to provide the details of the development board. Taking the XIAO ESP32C3 board as an example, it
belongs to the ESP32 family, so its FQBN would be esp32:esp32:XIAO_ESP32C3.
options are optional, so I left it blank, but you can provide the X-Organization value according
to your requirements. Both arrays are passed to the api.devicesV2Create method, which will
return the response. The util.inspect method is used to display the JSON response on the console
with proper formatting. Type the following command to execute the create-device.js program:
node create-device.js
After successful execution of the script, it will print a response like the following:
In the response, you will get your device ID, which will be used later in the chapter for Thing creation
when we associate the device with the Thing. The remaining properties are the same as already covered
in the code.
Important note
If you are unable to get the correct FQBN, then add the device manually from the dashboard,
finding and clicking on the device from the dropdown. This will give you the fqbn, type,
and connection_type details. You can use these details later in your Node.js script for
automated creation of devices.
Interacting with devices – hands-on with the Node.js SDK 201
Updating a device
In this section, we are going to explore how we can update a device using the device ID. Let’s suppose
we mistakenly added a device with the wrong FQBN and name. We will update both properties using
the device ID. The documentation on updating devices is available at https://www.arduino.
cc/reference/en/iot/api/#api-DevicesV2-devicesV2Update. Open the update-
device.js file under the device folder in VSCode:
The preceding code is almost the same as the create-device code. Here we have one extra
variable, DeviceID, with which we will update the specific device. The rest of the code has the same
device properties and options as previously. Now, fill in the correct fqbn and name values in the
DeviceProperties variable. Lastly, we call the api.devicesV2Update() method. Execute
the following command in the Terminal:
node update-device.js
After successful execution of the script, it will print a response like the following:
created_at: 2023-04-17T00:47:40.700Z,
fqbn: 'esp8266:esp8266:d1_mini'
}
As we can see, after our update, the response sends back the new content. We provided a change of
name and FQBN and it is reflected successfully in the response.
Deleting a device
In this section, we are going to explore how we can delete a device using the device ID. The documentation
for deleting devices is available at https://www.arduino.cc/reference/en/iot/
api/#api-DevicesV2-devicesV2Delete.
Open the delete-device.js file under the device folder in VSCode:
The preceding code snippet is taken from the DeleteDevice() method. In this method, we need
to supply DeviceID and options variables as parameters. DeviceID is mandatory for the deletion
process while the options variable is not. Execute the following command in the Terminal:
node delete-device.js
After successful execution of the script, it will print a response to the console reporting that the device
has been deleted successfully.
Listing devices
In this section, we will list all the devices. Note that there is a difference between listing devices and
showing devices: listing devices means displaying all the devices with their properties, while showing
a device only returns a specific device’s properties based on the device ID.
Interacting with devices – hands-on with the Node.js SDK 203
Here we need to provide the criteria that will be used to filter out the devices and return the desired
response. In the current code, we only mention one parameter, 'acrossUserIds', which is true
to fetch all types of devices. But if required, you can filter the devices listed on the basis of tags,
serial, and X-Organization. Execute the following command in the Terminal:
node list-device.js
After successful execution of the script, it will print a response in JSON format with the device
properties, which will clog up the Terminal console with extensive output. I modified the code to
only display the device ID and device name on the console:
Device ID:04d8025a-4270-4d7e-aa04-45db87a594f5
Device Name:SmartAgriESP32-Sargodha
Device ID:5aae7e1f-940b-4426-80ac-1c953839cdb2
Device Name:MKR-GSM-1400
Device ID:fae0951d-3169-4d6a-a8e5-739c347eafc1
Device Name:MKR1500
Device ID:ca711f68-6de9-497a-ac45-780219ad2bb8
Device Name:Wemos d1 Mini by API Update
Device ID:64990519-1833-4bba-b035-978fcaa33466
Device Name:MKR1010-Device
Device ID:62e8600b-2733-4f24-9654-1fac549af27f
Device Name:XIAO-ESP32C3-Pulse-Sensor
Device ID:e88b84a7-7ad7-4c2b-b79c-ab426e47dc67
Device Name:Sense Home WeMos D1 Mini Series
Device ID:b9f3ff20-ebf1-4260-ad16-f434466458ac
204 Working with the Arduino IoT Cloud SDK and JavaScript
Device Name:ArduinoNanoRP2040
Device ID:047d8316-dcdb-4bf5-af30-4319bb5a5eb0
Device Name:Delly
In the preceding code, we are displaying two parameters on the console, but you can choose whichever
and however many you want by specifying their names in the for loop. Using this, we can send the
output in JSON format to a web/mobile client, which will display the information either in a list box
or in menus.
Showing a device
This is the second-to-last subsection of the Interacting with devices – hands-on with the Node.js SDK
section. Here we will fetch all the properties of a specific device by providing the device ID. The
documentation on showing devices is available at https://www.arduino.cc/reference/
en/iot/api/#api-DevicesV2-devicesV2Show.
Open the show-device.js file under the device folder in VSCode. The following code snippet
is taken from the ShowDevice() method from the show-device.js file:
The devicesV2Show() method only takes two parameters: the first one is the DeviceID and
the second is options, which includes X-Organization. DeviceID is mandatory to fetch a
proper response while the opts variable is optional, hence we pass this variable as empty. Execute
the following command in the Terminal:
node show-device.js
After successful execution of the script, it will print the response in JSON format with the device
properties as well as the details of any cloud variables if any associated variable is present:
ArduinoDevicev2 {
id: '62e8600b-2733-4f24-9654-1fac549af27f',
label: 'Login and secret key for wifi device',
name: 'XIAO-ESP32C3-Pulse-Sensor',
Interacting with devices – hands-on with the Node.js SDK 205
……………………………………..
thing: ArduinoThing {
id: '6b6cd076-5859-4a6d-9b4e-18879893c6cb',
name: 'Tracking and notifying Your Heart Rate',
……………………………………..
webhook_active: true,
webhook_uri: 'https://hooks.zapier.com/hooks/
catch/14930971/324me7k/'
}
}
The preceding code is the edited response of the script regarding device properties, which includes all
the details of the given device such as last activity, the cloud variables count, the Thing ID associated
with the device, webhook details (if active), sketch ID, and so on.
In this sub-section, we have explored how to get all the devices list from the Arduino IoT Cloud using
the Node.js SDK. Next, let’s explore how to get the list of cloud variables/properties associated with
the device.
Device properties/variables
Here, we will fetch all the cloud variable details for a specific device by providing the device ID. The
documentation on showing devices is available at https://www.arduino.cc/reference/
en/iot/api/#api-DevicesV2-devicesV2GetProperties.
To begin, open the properties-device.js file under the device folder in VSCode. The
following code snippet is taken from the ListPropDevice() method in the properties-
device.js file:
The devicesV2GetProperties() method only takes two parameters: the first one is device ID
and the second is options, which includes showDeleted and X-Organization. DeviceID is
mandatory to fetch a proper response, while the opts variable is optional, so we leave this variable
empty when we pass it. Execute the following command in the Terminal:
node properties-device.js
After successful execution of the script, it will print a response in JSON format containing the cloud
variable details associated with that particular device ID:
Properties: [
ArduinoProperty {
href: '/iot/v1/things/6b6cd076-5859-4a6d-9b4e-18879893c6cb/
properties/b357a513-ad2b-4e1f-a76b-6dac078e36d5',
id: 'b357a513-ad2b-4e1f-a76b-6dac078e36d5',
name: 'BPM',
permission: 'READ_ONLY',
thing_id: '6b6cd076-5859-4a6d-9b4e-18879893c6cb',
type: 'HEART_BEATS',
update_strategy: 'ON_CHANGE',
created_at: 2023-03-31T16:41:33.103Z,
persist: true,
tag: 1,
thing_name: 'Tracking and notifying Your Heart Rate',
update_parameter: 0,
updated_at: 2023-03-31T17:05:19.564Z,
variable_name: 'bPM'
}
]
The preceding response is the edited response of the script regarding the device cloud variables, including
variable_name, type, permission, thing_id, update_strategy, and so on. We have
now seen how to get the cloud variable details, and in the next section we’ll move on to cover Things.
Creating a Thing
Firstly, we will start with Thing creation. The relevant documentation can be found at https://
www.arduino.cc/reference/en/iot/api/#api-ThingsV2-thingsV2Createe.
Open the create-thing.js file under the thing folder in VSCode.
There are two methods in this code: one is getToken(), which is the same method as in all our
coding exercises and helps us to fetch an authentication token for our requests. The second method is
CreateThing(), which is responsible for Thing creation. Referring to the documentation, we can see
that we need to initiate the api variable with the AiotApi.ThingsV2Api() object, which relates
to the Arduino IoT Cloud Thing. This object is responsible for performing operations on the Thing:
api.thingsV2Create is the method responsible for Thing creation and takes two parameters as
input: name and opts. Firstly, we start with name, which can be anything you like, but make sure to
avoid special characters. For now, we provide just the Thing name in the variable, but in the upcoming
update section, we will additionally pass the time zone and device ID parameters.
opts here is optional, hence I left it blank, but you can provide the X-Organization value if
required. Both variables are passed to the api.thingsV2Create method, which will return the
response. The util.inspect method is used to display the JSON response on the console with
proper formatting. Type the following command to execute the create-device.js script:
node create-thing.js
created_at: 2023-04-18T16:46:35.767Z,
properties_count: 0,
updated_at: 2023-04-18T16:46:35.767Z,
webhook_active: false
}
In the response, you will get your Thing ID, which will be used shortly in the following Thing update/
delete operations – so make sure to paste this Thing ID into a Notepad file or something similar. Also
returned are the time zone, properties count, and webhook status.
Updating a Thing
In this section, we are going to explore how to update a Thing using the Thing ID. Let’s suppose we
mistakenly added the Thing without setting the proper time zone and without device association.
In this scenario, we have the option to update the Thing with new properties. The documentation
covering updating devices is available at https://www.arduino.cc/reference/en/iot/
api/#api-ThingsV2-thingsV2Update. Open the update-thing.js file under the
device folder in VSCode:
The preceding code is similar to the create-thing code. Here we have one extra variable, id, which
will help us to update the specific Thing. We also have the timezone, device_id, and name in
the thingupdate variable. Lastly, we call the api.thingsV2Update() method. Execute the
following command in the Terminal:
node update-thing.js
Engaging with Things – Node.js SDK implementation guide 209
After successful execution of the script, it will print a response like the following:
After our update, the response will return the new content. We provided new values for name and
device_id, along with the correct time zone. Everything is updated successfully and reflected in
the response.
api.thingsV2CreateSketch is the method responsible for Thing sketch creation and takes
three parameters as input. The Thing ID is the first parameter; the second is the sketch version. opts
is optional, so I left it blank, but you can provide the X-Organization value according to your
requirements. All variables are passed to the api.thingsV2CreateSketch method, which will
return the response. The util.inspect method is used to display the JSON response on the console
with proper formatting. Type the following command to execute the create-device.js script:
node create-sketch-thing.js
After successful execution of the script, it will print the following response:
In the response, you will see your Thing ID along with some other properties indicating that the sketch
for the given Thing has been created successfully. You can also verify the sketch by navigating to the
given Thing on the Arduino IoT Cloud.
Important note
Before sketch creation, it’s important to associate a device with the Thing.
In this section, we created the Sketch for our Thing as the Arduino IoT Cloud will not do this by
default. As a result, it’s mandatory to create a Sketch after creating a Thing in the Arduino IoT Cloud.
Next we are going to explore how we can delete a Thing using the Arduino IoT Cloud API.
Engaging with Things – Node.js SDK implementation guide 211
Deleting a Thing
In this section, we are going to explore how we can delete a Thing using the Thing ID. The documentation
covering Thing deletion is available at https://www.arduino.cc/reference/en/iot/
api/#api-ThingsV2-thingsV2Delete. Open the delete-thing.js file under the
thing folder in VSCode:
The preceding code snippet is taken from the DeleteThing() method. In the DeleteThing()
method, we need to supply the id (Thing ID) and opts variables as parameters. id (Thing ID) is
mandatory for the deletion process, while the opts variable is not. Execute the following command
in the Terminal:
node delete-thing.js
After successful execution of the script, it will print a response on the console indicating that the
device was deleted successfully.
Listing Things
In this section, we will list all the Things. Note that there is a difference between listing Things and
showing a Thing: listing Things will display all the Things with their properties, while showing a Thing
only shows the specific Thing properties related to a given Thing ID.
The relevant documentation on listing Things is available at https://www.arduino.cc/
reference/en/iot/api/#api-ThingsV2-thingsV2List. Open the list-thing.js file
under the thing folder in VSCode. The following code snippet is taken from the ListThing() method:
api.thingsV2List(opts).then(function(data) {
for(var i=0;i<data.length;i++){
console.log("Thing ID:"+data[i].id+" Thing Name:"+data[i].
name);
}
}, function(error) {
console.error(error);
});
Here we need to provide criteria that will be used to filter out the Things and return the response. In
the current code, we have provided only one parameter, 'acrossUserIds', which is true and so
will fetch all types of Things. But you can also filter Things on the basis of tags, IDs, X-Organization,
and so on. Execute the following command in the Terminal:
node list-thing.js
After successful execution of the script, it will print the response in JSON format with the Thing
properties, which will fill the console with an extensive output. I modified the code to only display
the Thing ID and Thing name on the console:
As can be seen in the preceding output, I am only displaying two parameters on the console but you
can choose whichever parameters you would like to be displayed by specifying their names in the for
loop. This way we can send the output in JSON format to a web/mobile client where the information
will be displayed in either a list box or in menus.
Engaging with Things – Node.js SDK implementation guide 213
Showing a Thing
This is the last subsection of the Engaging with things – Node.js SDK implementation guide section. Here
we will fetch all the properties regarding a specific Thing by providing the Thing ID. The documentation
covering showing Things is available at https://www.arduino.cc/reference/en/iot/
api/#api-ThingsV2-thingsV2Show. Open the show-thing.js file under the thing
folder in VSCode. The following code snippet is taken from the ShowThing() method:
The thingsV2Show() method only takes two parameters: the first one is the thingid and the
second is opts, which include X-Organization. thingid is mandatory to fetch a proper
response, while the opts variable is not compulsory, hence I passed this variable empty. Execute the
following command in the Terminal:
node show-thing.js
After successful execution of the script, it will print the response in JSON format containing the device
properties as well as the details of cloud variables, if any associated variable is present:
created_at: 2023-03-31T16:41:33.103Z,
last_value: 50,
……………………………………..
variable_name: 'bPM'
}
],
properties_count: 1,
sketch_id: 'f490fec5-b62a-41f9-9ff7-2b5c3f2ed7d1',
updated_at: 2023-04-01T16:42:47.152Z,
webhook_active: true,
webhook_uri: 'https://hooks.zapier.com/hooks/
catch/14930971/324me7k/'
}
The preceding code snippet shows an edited section from the output response regarding the Thing
properties, which includes all the details of the Thing, the device properties, cloud variables such as
last value, webhook details (if active), the sketch ID, and so on.
In this section, we explored how we can get the complete details of a specific Arduino IoT Cloud
Thing using the Thing ID in JSON format. Next, we will start playing with cloud variables/properties.
Creating a property
Firstly, we will start with property creation. The property creation documentation can be found
at https://www.arduino.cc/reference/en/iot/api/#api-PropertiesV2-
propertiesV2Create. Open the create-property.js file under the properties folder
in VSCode.
There are two methods in the code: one is getToken(), which is the same method used in all
our coding exercises to fetch the authentication token for our requests. The second method is
CreateProperty(), which handles cloud variable creation. Consulting the documentation, we
can see that we need to initiate the api variable with AiotApi, the PropertiesV2Api() object,
which is related to properties:
'variable_name':'temperature',
'permission':"READ_ONLY",
'persist':true,
'type':'TEMPERATURE_C',
'update_strategy':'ON_CHANGE'
};
api.propertiesV2Create(thing_id, property).then(function(data) {
console.log('Property Created successfully. Returned data: '
+util.inspect(data));
}, function(error) {
console.error(error);
});
api.propertiesV2Create is the method responsible for property creation and takes two parameters
as input. One is the Thing ID and the other variable contains mandatory details regarding the cloud
variable. The Thing ID is simple and easily fetchable from the Thing metadata, but cloud variables
have a variety of different parameters including type, permission, and update_strategy,
available on the official documentation page (the URL was provided at the start of this section). Both
variables are passed to the api.devicesV2Create method, which returns the response. The
util.inspect method is used to display the JSON response with proper formatting on the console.
Type the following command to execute the create-device.js script:
node create-property.js
After successful execution of the script, it will print the following response:
In the response, you will get your cloud variable ID, creation date, and update date, along with other
details already mentioned during our cloud variable creation exercise.
216 Working with the Arduino IoT Cloud SDK and JavaScript
Updating a property
In this section, we are going to explore how we can update a cloud variable using the cloud variable ID.
Suppose we mistakenly added a cloud variable with the wrong data type and some other parameters
– in the event of this scenario, we have the option to update it. The documentation covering updating
properties is available at https://www.arduino.cc/reference/en/iot/api/#api-
PropertiesV2-propertiesV2Update. Open the update-property.js file under the
property folder in VSCode:
};
api.propertiesV2Update(thing_id,property_id, property).
then(function(data) {
console.log('Property Updated successfully. Returned data: '
+util.inspect(data));
}, function(error) {
console.error(error);
});
The preceding code is very similar to the create-property code. Here we have one extra variable,
property_id, used to update the given property. Besides that, we have the same cloud variable
properties with their updated content. Lastly, we call the api.propertiesV2Update() method.
Execute the following command in the Terminal:
node update-property.js
After successful execution of the script, it will print a response something like the following:
type: 'TEMPERATURE_F',
update_strategy: 'ON_CHANGE',
created_at: 2023-04-18T23:49:46.610Z,
persist: true,
updated_at: 2023-04-18T23:58:07.496Z,
variable_name: 'outdoorTemperature'
}
After the update, the response will return the new content. We provided updated information for the
name, type, and variable name and this is reflected successfully in the response.
Deleting a property
In this section, we are going to explore how to delete a property using the Thing ID and property ID.
The documentation covering deleting a property is available at https://www.arduino.cc/
reference/en/iot/api/#api-PropertiesV2-propertiesV2Delete. Open the
delete-property.js file under the property folder in VSCode:
The preceding code snippet is taken from the DeleteProperty() method from delete-
property.js file. In the DeleteProperty() method we need to supply the thing_ID,
property_id, and options variables as parameters. thing_id and property_id are both
mandatory for the deletion process while the options variable is optional. Execute the following
command in the Terminal:
node delete-property.js
After successful execution of the script, it will print a response on the console reading that the property
has been deleted successfully.
218 Working with the Arduino IoT Cloud SDK and JavaScript
Listing properties
In this section, we will list all the properties for a given Thing using the Thing ID. As previously outlined
with devices and Things, there is a difference between listing properties and showing a property. Listing
properties means displaying all the cloud variables of a Thing, while showing a property only shows
the specific cloud variable properties related to the given Thing ID and property ID.
The documentation on listing properties is available at https://www.arduino.cc/reference/
en/iot/api/#api-PropertiesV2-propertiesV2List. Open the list-property.
js file under the property folder in VSCode. The following code snippet is taken from the
ListProperty() method:
Here we only need to provide the Thing ID and options to get a complete list of cloud variables
associated with the Thing. Execute the following command in the Terminal:
node list-property.js
After successful execution of the script, it will print the response in JSON format with the cloud
variable’s properties. I chose a Thing that only has a single cloud variable:
Returned data: [
ArduinoProperty {
href: '/iot/v1/things/6b6cd076-5859-4a6d-9b4e-18879893c6cb/
properties/b357a513-ad2b-4e1f-a76b-6dac078e36d5',
id: 'b357a513-ad2b-4e1f-a76b-6dac078e36d5',
name: 'BPM',
permission: 'READ_ONLY',
thing_id: '6b6cd076-5859-4a6d-9b4e-18879893c6cb',
type: 'HEART_BEATS',
update_strategy: 'ON_CHANGE',
created_at: 2023-03-31T16:41:33.103Z,
last_value: 50,
persist: true,
Crafting dashboards – unleashing potential via the Node.js SDK 219
tag: 1,
thing_name: 'Tracking and notifying Your Heart Rate',
update_parameter: 0,
updated_at: 2023-03-31T17:05:19.564Z,
value_updated_at: 2023-04-01T16:43:12.293Z,
variable_name: 'bPM'
}
]
The preceding response contains all the values related to the cloud variable, such as last value, updated
time, and so on. If you want to fetch the last value of a cloud variable then this method could be used
in your application to do so.
Next, we have another API endpoint related to showing the properties of a single cloud variable. The
code is available in the property folder, and the execution of the code along with checking out how
it works is left to you as an exercise.
In this section, we discussed in depth how to get the complete details of a cloud variable/property in
JSON format using the Arduino IoT Cloud API, which provides lot of data including last_value
and value_update_at. In the next section, we will start working with dashboards and learn how
to perform operations on them using the Node.js SDK.
Creating a dashboard
Let’s start first with dashboard creation. The relevant documentation can be found at https://www.
arduino.cc/reference/en/iot/api/#api-DashboardsV2-dashboardsV2Create.
Open the create-dashboard.js file under the dashboard folder in VSCode.
There are two methods in this code: one is getToken(), which is the same method as in all
our coding exercises to fetch the authentication token for our requests. The second method is
CreateDashboard(), which is responsible for dashboard creation. Referring to the documentation,
we can see we need to initiate the api variable with the AiotApi.DashboardV2Api() object,
which is used to perform operations on dashboard objects:
api.dashboardsV2Create is the method responsible for dashboard creation and takes two
parameters as input: the first is the dashboard properties and the second variable is opts, which is not
mandatory, hence I leave it empty. Both variables are passed to the api.dashboardsV2Create
method, which returns the response. The util.inspect method is used to display the JSON
response on the console with proper formatting. Type the following command to execute the create-
dashboard.js script:
node create-dashboard.js
After successful execution of the script, it will print a response like the following:
In the response you will get your dashboard ID, creation date, update date, and other things we already
covered during dashboard creation.
Updating a dashboard
In this section, we are going to explore how to update a dashboard using the dashboard ID. There is an
option to add widgets to a dashboard via an API but it will make the code significantly more complex
due to the JSON data involved. For this reason, we will just update the dashboard name instead of
adding widgets. The documentation for updating properties is available at https://www.arduino.
cc/reference/en/iot/api/#api-DashboardsV2-dashboardsV2Update. Open the
update-dashboard.js file under the dashboard folder in VSCode:
var dashboardprop = {
'name':'Dashboard Created via API Update'
};
var opts = {
};
api.dashboardsV2Update(dashboard_id,dashboardprop, opts).
then(function(data) {
console.log('Dashboard Updated successfully.'+ util.
inspect(data));
}, function(error) {
console.error(error);
});
The preceding code is almost the same as the create-dashboard code. Here we have one extra
variable, dashboard_id, used to update the specific dashboard. Besides that, we have the same
dashboard properties with their updated content. Lastly, we call the api.dashboardsV2Update()
method. Execute the following command in the Terminal:
node update-dashboard.js
After successful execution of the script, it will print a response like the following:
After our update, the response will return the new content, reflecting the updated data for the name
that we provided.
Deleting a dashboard
In this section, we are going to explore how to delete a dashboard using the dashboard ID. The
relevant documentation on deleting dashboards is available at https://www.arduino.cc/
reference/en/iot/api/#api-DashboardsV2-dashboardsV2Delete. Open the
delete-dashboard.js file under the dashboard folder in VSCode:
};
api.dashboardsV2Delete(dashboard_id, opts).then(function(data) {
console.log('Dashboard Deleted successfully.');
}, function(error) {
console.error(error);
});
The preceding code snippet is taken from the DeleteDashboard() method from delete-
dashboard.js file. In the DeleteDashboard() method we need to supply the dashboard_id
and opts variables as parameters. dashboard_id is mandatory for the deletion process, while the
opts variable is optional. Execute the following command in the Terminal:
node delete-dashboard.js
After successful execution of the script, it will print the response on the console indicating that the
dashboard was deleted successfully.
Listing dashboards
In this section, we will list all the dashboards with complete details and widgets. The difference between
listing dashboards and showing a dashboard is that listing dashboards will display all the dashboards
available in the Arduino IoT Cloud, while showing a dashboard only shows the specific dashboard
properties and widgets related to the given dashboard ID.
The documentation for listing dashboards is available at https://www.arduino.cc/
reference/en/iot/api/#api-DashboardsV2-dashboardsV2List. Open list-
dashboard.js under the dashboard folder in VSCode. The following code snippet is taken
from the ListDashboard() method:
node list-dashboard.js
Crafting dashboards – unleashing potential via the Node.js SDK 223
After successful execution of the script, it will print the response in JSON format containing the
dashboard properties and widgets:
[
ArduinoDashboardv2 {
id: '36287c03-5034-4a64-b40a-102740c998c6',
name: 'SmartAgri-Sargodha',
updated_at: 2023-03-05T11:00:18.395Z,
created_by: ArduinoDashboardowner {
user_id: 'f067c1e9-3ff8-4b9f-a9b4-f8c5c1d0ceb4',
username: 'mafzalattari'
},
widgets: [
]
},
ArduinoDashboardv2 {
id: '28ea7839-7a81-460e-a871-368d45d82cee',
name: 'Tracking and notifying Your Heart Rate Dashboard',
updated_at: 2023-04-19T16:41:36.604Z,
created_by: ArduinoDashboardowner {
user_id: 'f067c1e9-3ff8-4b9f-a9b4-f8c5c1d0ceb4',
username: 'mafzalattari'
},
widgets: [ [ArduinoWidgetv2], [ArduinoWidgetv2] ]
},
]
The preceding response contains all the properties related to dashboards such as widgets, creation
date, update time, and so on. Next, we have another API endpoint related to showing a dashboard,
which is used to display all the information regarding a single dashboard. The code is available in
the dashboard folder; the execution of the code and checking out how it works is left to you as an
independent exercise.
In these sub-sections, we discussed how to work programmatically with dashboards, including actions
such as dashboard creation, updating, deletion, and showing the list of dashboards via the Arduino
IoT Cloud Node.js SDK. In the next section, we will explore how we can use the Node.js SDK to fine-
tune our cloud variables/properties.
224 Working with the Arduino IoT Cloud SDK and JavaScript
The preceding code snippet was taken from the GetProperty() method. We have defined thingid
and propertyid and then passed these variables to the api.propertiesV2Show method later
in the snippet. After getting the response in JSON format, we only use the last_value property
to display its data on the console. Run the following command on the Terminal:
node get-prop.js
After successful execution, you will get the response with the value.
Fine-tuning with the Node.js SDK – property value management 225
The preceding code snippet was taken from the SetProperty() method. Here, we provide three
variables to the api.propertiesV2Publish method. The first is thingid, the second is
propertyid, and the third variable contains the two further properties of device_id and value.
Run the following command on the Terminal to execute the script:
node set-prop.js
After successful execution, you will get a response indicating that the value has been updated successfully.
In the section, we discussed in detail how to get/set the value of a cloud variable programmatically.
This helps developers to fetch values and display them in their custom dashboards, or set the values
of cloud variables to control device operations. Next, you have an assignment of an example project
for practice, which will help you to refine your skills and chapter study.
226 Working with the Arduino IoT Cloud SDK and JavaScript
Assignment
After playing with SDK, it’s now time to do some more experiments so you can apply your learning
in new scenarios and solidify your learning. For this assignment, you will create a script for Thing
automation with the following properties:
1. Set up a method for WeMos D1 Mini device creation. This device belongs to the ESP8266 category.
2. Set up a Thing named Sense Environment and create a sketch for a Thing. Then, associate
the previously created device with the Thing.
3. Create three cloud variables/properties for temperature, humidity, and air quality and attach
these variables to the previously created Thing.
Create the required script in one file containing all the methods, where we just provide the Thing
name and it will automatically set up the device, Thing, and sketch, handle device association with the
Thing, and take care of variable creation. Successfully completing this task will teach you to automate
workflows and processes efficiently and effectively.
Summary
In this chapter, we covered API endpoints, SDKs, and the types of SDK platforms available to us
on the Arduino IoT Cloud. We also learned how to test APIs with Postman. Next, we explored the
Node.js SDK by performing different types of operations, particularly CRUD operations, on devices,
Things, properties, and dashboards. Finally, we saw how to get and set the value of a cloud variable.
This chapter was specially designed for backend developers seeking to use the Arduino IoT Cloud
as a foundation and wanting to develop a custom frontend for their solution, which is possible when
you know how to interact with the Arduino IoT Cloud programmatically using the Node.js SDK.
Likewise, the ability to create custom services allows us to integrate with third party cloud services
and applications.
The next chapter will be more interesting as we are going to dive into smart agriculture, implementation
a project where you will learn how to measure the soil moisture, soil temperature, and outdoor
temperature and humidity. We will design a device that will allow us to monitor four different crops/
plants. You could use this project to monitor your home plants as well as helping your friends working
in the field of agriculture.
9
Project 4 – Collecting Data
from the Soil and Environment
for Smart Farming
This chapter is dedicated to smart agriculture. Our population is growing rapidly and food consumption
is directly proportional to population. Fortunately, we have the latest tools and technologies that help
us to boost our crop yields by using fewer natural resources. In smart agriculture, there are different
parameters to monitor, but we will only focus on soil moisture and soil temperature as both are linked
to water consumption; access to clean water is another issue with the rapid growth of industries
and population.
In this chapter, we will practically explore smart agriculture by monitoring the soil moisture level,
soil temperature, and outdoor temperature and humidity, which will help us to understand how our
soil responds to changes in the outside environment and for how many days the soil retains moisture
after watering the crop. Our smart agriculture device will send all the data to the Arduino IoT Cloud,
where we will monitor it in real time and make decisions that will help us to use controlled watering
for crops, which will save water and improve the soil quality.
In this chapter, we are going to use open source and cost-effective sensors to carry out experiments
in labs as well as in the field. For the development board, we are using the ESP32 and ADS1115
analog-to-digital converter (ADC) modules in combination with four capacitive soil moisture and
four DS18B20 sensors for soil temperature monitoring, as well as a DHT22 module for outdoor
temperature and humidity monitoring. This project will help you optimize your crops with precision
farming, tunnel farming, and drip irrigation, as well as be useful for home gardening.
In this chapter, we will cover the following topics:
Technical requirements
The following hardware components are required to complete this chapter:
For coding, we will use the Arduino Web Editor, which includes a large collection of development
board and sensor libraries, and we will use the Arduino IoT Cloud for Thing and dashboard setup.
To develop hardware and sensor designs, we need the Fritzing desktop software.
The chapter code is available in the book’s official GitHub repository, or you can directly download
the code at https://github.com/PacktPublishing/Arduino-IoT-Cloud-for-
Developers.
• Automated irrigation: IoT sensors can be used to monitor soil moisture levels and weather
conditions to determine when to irrigate crops. Automated irrigation systems can then be
triggered to deliver the right amount of water to crops, which can reduce water wastage and
increase crop yields.
Essential hardware for your agri-tech project 229
• Livestock management: IoT sensors can be used to monitor the health and behavior of livestock,
such as their movement, feeding habits, and sleeping patterns. This data can be used to detect
early signs of illness, track breeding cycles, and ensure optimal conditions for the livestock.
• Crop monitoring: IoT sensors can be used to monitor crop growth, detect pests and diseases,
and identify areas that need attention. This data can be used to make timely interventions and
improve crop yields.
• Precision farming: IoT sensors can be used to gather data on individual plants or crops,
enabling farmers to optimize their use of resources, such as water, fertilizers, and pesticides.
This can help reduce waste, improve yields, and save money.
• Smart harvesting: IoT sensors can be used to monitor crop ripeness and determine the optimal
time for harvesting. This can help reduce waste and improve the quality of harvested crops.
• Weather monitoring: IoT sensors can be used to monitor weather conditions such as temperature,
humidity, and rainfall. This data can be used to make informed decisions about planting,
harvesting, and other farming operations.
Overall, IoT technology is transforming the way that agriculture is practiced. By using real-time data
and analytics, farmers can make better decisions and achieve better outcomes, ultimately leading to
a more sustainable food supply for the world.
In this section, we have discussed smart agriculture and different terms and techniques that are
common in smart agriculture. In the next section, we will discuss the hardware components that we
are going to use in this chapter’s project.
ESP32 provides multiple pins for digital and analog input/output. If you want to use multiple analog
sensors, then ADCs are available. One of the most well-known ADCs is the ADS1115/ADS1015
module, which provides four analog pins and is good when you need to add additional analog pins
to your project. In this project, four analog pins are required to fetch soil moisture sensor values; this
board has enough analog pins but I am using ADS1115 to demonstrate how we can use the ADC
module to add extra analog pins to our projects.
In the current project, we need five digital pins for the DHT22 module and DS18B20 temperature
probe and four analog pins for the capacitive soil moisture sensors. One of the good features of this
development board is that it provides a 5V power pin, which is not available in most ESP32 series
development boards.
Next, we are using the DHT22 module to sense outdoor temperature and humidity, but you can also
use the DHT11 sensor, depending on your requirements. If specifically talking about features, then the
DHT22 provides a broader range of sensors compared to the DHT11, but it costs more. The following
figure shows the DHT22 module, and we have labeled the pins for better understanding.
Essential hardware for your agri-tech project 231
The preceding figure shows the pinout of the DHT22/DHT11 sensor module; the complete pin
connection configuration can be seen in Table 9.3. The first pin (VCC) works with both 3.3V and 5V.
The second pin is the DATA pin, which connects with any digital pin of ESP32-DevKit V1. The third
pin is the GND pin, which connects with the GND pin of the development board.
Before moving on, the following table explains all the specification differences between the DHT22
and DHT11. The most notable things are the sensing range and sensing period:
The main sensor of the project is a capacitive soil moisture sensor and it is used to monitor the soil
moisture of a specific area. It is a low-cost soil moisture monitoring sensor and is rustproof due to its
use of PCB (PCB sheets use plastic and paint, making them rustproof). It senses the soil moisture by
passing a small amount of electric current into the soil moisture sensors, as shown in Figure 9.3, and
determining the soil moisture based on the returned current. If the sensor receives a higher current,
then it means the moisture is high; if it receives a low current, then there is little or no moisture
content in the soil.
The soil moisture sensor consists of three pins: GND, VCC, and AOUT. The sensor provides readings
in analog format. These values will later be converted into percentages using the map() method under
the FetchSoilMoisture() method. The complete code is available on GitHub in the folder for
this chapter. The sensor operates with both 5V power as well as 3.3V, but 5V is recommended.
The other main sensor of this project is the DS18B20 waterproof temperature sensor probe, which is
used to monitor the soil temperature of a specific area, along with soil moisture levels. It is a low-cost
waterproof temperature monitoring sensor and is rustproof due to its steel enclosure. The following
figure shows the DS18B20 waterproof temperature probe and its pinout and connection diagram
with ESP32-DevKit V1.
Architecting your agriculture IoT system 233
The preceding figure shows the sensor and its pinout diagram. DS18B20 contains three colored wires:
the black wire is used for GND, the red wire is used to connect VCC either with 3.3V or 5V, and the
yellow wire is used to connect with any digital pin but with a 4.7k pull resistor, as shown in the figure.
If we’re talking about sensor specifications, then its temperature sensing range is good – it is capable
of measuring a temperature from -55 to 125°C. All the other details are given in the following table
for further exploration:
Feature DS18B20
Power supply 3.3 to 5V
Output signal Digital signal/one wire
Temperature sensing range -55~125°C
Temperature accuracy Temperature ± 0.5°C
Sensing period <750 ms
In this section, we have discussed development boards and sensors in detail, with complete specifications
and pinout diagrams. In the next section, we will talk about how these sensors connect to ESP32-
DevKit V1 as well as the PCB design of the project.
In the following two subsections, we will first talk about the schematics and design of the project and
explain how to connect the pins with the development board. Then, we will talk about PCB design
and its implementation to make the product ready for deployment in the field.
Figure 9.5 depicts the whole project schematic diagram, which also includes the pin numbers. But
to make it easier for you, we have provided the following tables with all the pin numbers. Table 9.3
contains the pin configuration for DHT22 with ESP32:
ESP32 DHT22
D13 Data (I/O)
GND GND
3.3V VCC
Table 9.4 contains the pin configuration for DS18B20 temperature probes with ESP32. Here, we are
using four DS18B20 temperature probes, and in each column of sensors, we have mentioned the ESP32
pin number that will connect with the DS18B20 data pin. GND and VCC pins of ESP32 development
board will be common to all sensors:
Table 9.5 illustrates ESP32 to ADS1115 pin configuration. The rest of the soil moisture sensors will
connect to the system via ADS1115 analog pins, which are explained in Table 9.6:
ESP32 ADS1115
D22 SCL
D21 SDA
3.3V VCC
GND GND
In Table 9.6, you will see how we have attached soil moisture sensors to the system using ADS1115.
The second row of the table states which pin of ADS1115 will be used to connect soil moisture sensors
to the system:
The preceding design provides a full overview showing how you can connect the sensors to the
development board. According to the design, we have only one 5V and one GND from the development
board, which will be used across all the sensors. Soil moisture sensors are analog sensors, so we
connected all the sensors with ADS1115 module pins from the AO pin to the A4 pin, as shown in
Figure 9.5 and Table 9.6, while the DHT22 module and DS18B20 are digital sensors and are connected
to the D12, D32, D33, D25, and D26 pins of ESP32, as shown in Figure 9.5 and in Table 9.3 and Table
9.4, respectively. The ESP32 to ADS1115 pinout is shown in Table 9.5 as well as in Figure 9.5.
The preceding figure shows the final PCB design of the project. (I was able to create this design easily
thanks to Fritzing.) There are many different tools available for PCB design, such as EasyEDA, Circuit
Maker, and Altium. It’s easy to develop a PCB; just make sure that the connection line on the PCB
doesn’t intersect with other connection lines.
After the PCB design, you have two options: either develop the PCB yourself using the DIY method
(which is good for learning purposes but not suitable for large-scale products) or choose a professional
organization that will manufacture the PCB professionally. Many organizations in China provide
PCB manufacturing and fabrication services, such as Seeed Studio, JLCPCB, and PCBWay. We tried
PCBWay and were impressed with their working and delivery time. We have uploaded the PCB
design to the PCBWay project repository, and from there, you can select the PCB design and order
easily: https://www.pcbway.com/project/shareproject/ESP32_Based_Smart_
Agriculture_Node_11223e5a.html.
After getting the PCBs, it’s time to solder the female headers and 2.54 mm three-pin connectors for
development boards and sensors. Never solder the development board and sensors directly on a PCB
so that if anything stops working, then it’s easy to detach and replace. The following figure shows the
final face of the PCB which contains 2.5mm three-pin connectors in white color for soil moisture
sensors, DS18B20 & DHT22 while black female headers are used to insert the ESP32-DevKit V1 and
ADS1115 module.
238 Project 4 – Collecting Data from the Soil and Environment for Smart Farming
The preceding figure shows how the PCB looks after soldering the three-pin 2.54 mm connectors
and female headers. Soil moisture connectors are marked with SM while DS18B20 connectors are
marked with T and resistances are marked with R, as shown in Figure 9.7. Now it’s time to plug all
the connectors to get our smart agriculture node ready for further procedures. But wait – by default,
soil moisture sensors come with a very small length of wire, which is not enough, so here you need to
extend the cable lengths by putting 2.54 mm female connectors on both ends, as soil moisture sensors
also use the same connectors for connectivity. DS18B20 also comes with a naked terminal but we
plugged a 2.54 mm female connector for easy and clean connectivity. The following figure shows the
complete setup with all the sensors and cabling arrangement.
Perfecting sensor calibration 239
Figure 9.8: Smart agriculture system with all sensors and modules
The preceding figure shows all the components stacked on the PCB. We can see that soil moisture sensors
are extended with custom cabling with the help of connectors, while the DS18B20 naked terminal is
connected to female connectors, and the same for the DHT22 module. After hardware assembly, we
need to calibrate the soil moisture and DS18B20 temperature before deploying the node into the field.
Here, we need to install a library for ADS1115/ADS1015 in the Arduino IDE so we can use the ADS
module. Navigate to Sketch | Include Library | Manage Libraries…, type Adafruit ADS1X15,
and install the latest version, which is shown in the preceding figure. After installation of the library,
download the code from the official GitHub book repository and open the code from the Soil-
Moisture-Calibration folder:
int AirValue[]={0,0,0,0};
int WaterValue[]={0,0,0,0};
The preceding code snippet contains two arrays: one for air values and one for sensor values when
they are dipped into the water. For soil sensor calibration, we need to get AirValue and then
WaterValue values only by one time. Upload the code to the development board and make sure
your soil moisture sensors are dry. Open the serial monitor and note down the AirValue value for
each sensor. After that, dip the sensors into a pot of water and note down the WaterValue value
of the sensors.
Let’s look at the AirValues of AIN0, AIN1, AIN2, and AIN3, as shown in Figure 9.10. AIN is short
for Analog Input and the proceeding 0, 1, 2, and 3 are the pin numbers of the ADC1115 module
where soil moisture sensors are connected:
Perfecting sensor calibration 241
Now let’s look at the WaterValues after putting the soil moisture sensors in the water:
Wait for some time and note down the values when they become stable. After fetching the Air and
Water values, put these values into the preceding arrays and upload the code again to the development
board. Verify the values of the soil moisture percentage levels by putting the sensors into the water and
then cleaning them. Here, you will get 100% when sensors are deeply in water and 0% when they are dry.
After the soil moisture levels, it’s time to verify the DS18B20 temperature probe sensor readings.
Firstly, we need to install a library for the DS18B20 temperature sensor. Navigate to Sketch | Include
Library | Manage Libraries…, type Dallas Temperature by Miles Burton, and install
the latest version. After installation of the library, download the code from the official GitHub book
repository and open the code from the DS18B20-Calibration folder:
In the preceding code, we have mentioned digital pin numbers, which are reserved on the PCB to
connect DS18B20 sensors. If you are using different pins on the breadboard, then update the pin number
according to your selection. Upload the code on the development board, then after uploading, open up
the serial monitor and see whether you are getting the values from the sensors or not. The following
figure shows the DS18B20 temperature probe readings on the serial monitor for calibration purposes.
The preceding figure shows that the DS18B20 temperature sensors are working fine and the values
are stabilized. Now, we can move forward with lab calibration.
Important note
A 4.7k pull resistor is mandatory for DS18B20. Without pull-up resistor, you will not get
the values.
After the soil moisture sensors have tested with the Air and Water values, it’s time to calibrate both
sensors in the lab. For moisture testing, we used the hot air oven method to verify the accuracy of the
soil moisture sensor. We added water to soil, sand, and salt at different levels and measured it with
sensors. After that, we inserted these samples into a hot air oven and compared the sensor readings
between the two methods; the results were incredible: only a ±0.5 difference. For DS18B20, we used
a calibrated analog thermometer and observed only a ±0.5 difference. The following figure shows a
photo of the lab where we calibrated the soil moisture and DS18B20 sensors to industry standards.
Figure 9.13: Moisture sensor and temperature sensor calibration in the lab
244 Project 4 – Collecting Data from the Soil and Environment for Smart Farming
The preceding figure shows the calibration of sensors in the lab. Here, we have tested the sensors with
soil, sand, and salt.
In this section, we discussed sensors and their connection to ES32-DevKit V1 using a schematic
diagram, as well as PCB design and its implementation. After that, we discussed soil moisture and
DS18B20 sensor calibration. In the upcoming section, we will set up things, network credentials, and
cloud variables and look into the code.
Set up a new thing with the name AgriStack. Follow these steps to create variables, an associated
device, network configuration, and, finally, the code. We have marked the preceding figure with
different red boxes and assigned numbers. These numbers correspond to the following steps, which
will help you to set up the Thing:
1. Firstly, we need to set up 10 cloud variables, as shown in Figure 9.14. There are two cloud
variables for outdoor temperature and humidity; these values will be taken from DHT22. There
are four cloud variables for soil moisture and four variables for soil temperature. The previous
four will use soil moisture sensor and the latter four will use the DS18B20 temperature probe.
More details about cloud variables are available in the next subsection.
2. After that, we need to associate the device with the Thing. In the current project, we are going
to use ESP32-DevKit V1, so the wizard will be different compared to Arduino boards. Complete
details are available in the Associating a device section.
3. Finally, we need to set up the network configuration for the device, but this time, we need to
provide a security key for ESP series boards to make the connection secure, whereas Arduino-
compatible boards are configured by the Arduino IoT Cloud automatically during the device
setup wizard.
Here, we have discussed the different steps that help us to set up our thing. In the proceeding section,
we will start looking into cloud variables.
Cloud variables
The following table explains all the properties of variables that we need to use during cloud variable
creation. An integer (int) is a very famous data type, but here you will observe two new variable types
regarding humidity and temperature, which take values in percentage and Celsius, respectively. Also,
ensure you have the same variable declaration as per the table; otherwise, you will need to modify the
example code according to your naming.
We have set the permission of all cloud variables to Read Only, but we also have the Read/Write
option. In this project, we only want to receive data from the device instead of sending data from
dashboard, which is why Read Only mode is used, to avoid issues with data consistency. Update
Policy is set to On change, as the device will send the data after five minutes, so this option is more
appropriate compared to Periodically update:
246 Project 4 – Collecting Data from the Soil and Environment for Smart Farming
After the successful creation of cloud variables, we will proceed further with the device association
step, where we will add and associate the ESP32-DevKit V1 with our thing.
Associating a device
After variable creation, it’s time to add a device and associate it with the Thing. Before adding the device,
connect the development board to the computer, and open the Arduino Create Agent application. We
discussed the Arduino Create Agent in Chapter 2, in the What is the Arduino Create Agent? section.
Click on the Select Device button under the Associated Device section on the Thing page. A popup
will appear where you can see all the devices that are already available. If you have already added
your WeMos D1 mini, select it. Otherwise, click on SET UP NEW DEVICE. Next, click on the Set
up a 3rd party device option. Select ESP32 and DOIT ESP32 DEVKIT V1 from the dropdown and
click on the CONTINUE button. Provide the device name and click on the Next button. In the final
wizard, the Device ID and Secret Key details will be displayed. Copy the secret key to a safe place as
it will be used during the network configuration.
Network configuration
After associating the device with the Thing, it is time to configure the Wi-Fi settings for device
communication, as shown in Figure 9.14, in the area marked 3. Under Network, you will find the
option to fill in the form with the Wi-Fi name and password. In the last field, you will find a new
field for the secret key. Paste the secret key that we received from the system during device creation.
After network configuration, we are done with our main task; now, the coding task remains, and in
the next section, we will go through it.
Coding
The project code is available in the book’s official GitHub repository in a ZIP file named AgriStack_
mar05a. Download it and import it to your Arduino Web Editor.
You can download the code and put it into your thing by navigating to the Sketch tab. I am not going
to discuss that code as you will get the idea after reading it. But here, I will explain the main workflow:
we initialize all the things in the setup method and use the timer library to delay calling; remember,
never try to use the delay method as it will block the ArduinoCloud.update() method.
Then, a method called SmartAgri() is called every five minutes. The following is the complete
SmartAgri() method. After this, we will explore what operations are carried out by this method:
return true;
}
Setting up things, networks, and cloud variables 249
In this project, we have divided all the operations into different methods for easiness. So, firstly, we
are calling FetchSoilMoisture(), which is responsible for fetching soil moisture readings from
sensors and storing them in an array. Before storing the data in an array, it maps the value for the
percentage. Next, we have the FetchTemperature() method, which is responsible for fetching
the temperatures from all DS18B20 sensors and saving them into the soil temperature array for further
usage. Finally, we call FetchDHTTempHum() to fetch the outdoor temperature and humidity values
from the DHT22 module, which will be stored in two variables. Now, we will explore how we get the
values from the soil moisture sensors in the following method:
float SoilMoisture=0;
return SoilMoisture;
}
The preceding technique is used in the FetchSoilMoisture() method to fetch the readings for
soil moisture. Here, you will see that the method takes values from the sensor five times with a delay
of one second and adds them to the variable; then later, it divides the sensor readings by 5 to get the
average. The benefit of this technique is that you will get the best possible value from the soil sensor.
The previous three methods have been used to fetch values from different sensors and store them
in global variables and arrays. Now it’s time to send these values to the Arduino IoT Cloud; for that
reason, we have the SendToArduinoIoTCloud() method, which assigns all the values of sensors
to cloud variables, and these values will be updated on the cloud with the help of the ArduinoCloud.
update() method. At the end, we have the PrintTheReadingsSerialPort() method,
which is optional for use at runtime and is used to display all the sensor values on the serial monitor.
250 Project 4 – Collecting Data from the Soil and Environment for Smart Farming
Upload the code to the device and verify the connectivity and readings. If you want to change the
reading time, then just modify the timer.every(600000, SmartAgri); value. Make sure
you are providing the time in milliseconds, where 1 second equals 1,000 milliseconds.
Important note
If you used a different naming scheme in the variable declaration, then update the code according
to your naming scheme. But first, you should follow all the steps according to the book and
then you can later change the cloud variable names and modify your code, respectively.
Never try to use the delay method, as it will block the ArduinoCloud.update() method.
Always use milliseconds to calculate the waiting time. Review the loop() method to call the
other methods after five minutes.
The Arduino IoT Cloud only updates the value on the dashboard whenever the variable value
is changed. For example, if the temperature is 30°C and it’s the same after five minutes, then the
Arduino IoT Cloud will not record the value, so don’t get confused if values are not changing
on the graph. Another benefit of this feature is you will not get duplicated data when you are
exporting the content.
After successfully discussing the different methods in the code and uploading the code to ESP32-
DevKit V1, it’s time to explore how to visualize all the data using awesome Arduino IoT Cloud
dashboard widgets.
We have 10 different readings: Outdoor Temperature, Outdoor Humidity, four Soil Moisture readings,
and four Soil Temperature readings. For every reading, we are using the gauge widget control, and
advanced charts have been used to compare Soil Moisture and Soil Temperature to visualize the
proper correlation between these two attributes. But we also want to monitor historical data; graphs
are the best widgets to display live as well as older data. Here, as seen in the lower part of the preceding
figure, we have used four graphs, and each graph is connected to a specific cloud variable.
In this section, we have successfully created a dashboard for a smart agriculture thing that shows all
the sensor readings in text format, as well as used graphs for comparison purposes.
252 Project 4 – Collecting Data from the Soil and Environment for Smart Farming
What next?
We still have a lot of options available to explore, but now it’s your turn to use different sensors and
development boards to do some more experiments and learn from them. In this chapter, we used 10
sensors but only 3 different types, that is, moisture, temperature, and outdoor temperature and humidity.
However, on the market, there are a lot of sensors that provide a wide variety of functionalities for
soil, such as NPK (which stands for nitrogen, phosphorus, and potassium), EC (which stands for
electrical conductivity), and pH sensors and different gas sensors for outdoor measurement.
Try the following sensors to enhance your practical knowledge and compare them with other sensors
in terms of features, ranges, and cost:
• NPK sensor
• Soil EC sensor
• Soil pH sensor
• MQ series sensors, which are designed to sense specific gases, including MQ-2, MQ-3, MQ-4,
MQ-5, MQ-7, MQ-8, and MQ-9, to find the correlation of gases and their effects on soil and crops
• Seeed Studio SCD30 (temperature, humidity, and CO2) for outdoor monitoring
Summary
In this chapter, we explored how to develop a smart agriculture monitoring system using DHT22,
capacitive soil moisture sensors, a DS18B20 probe for soil temperature, and an ESP32 development
board along with the ADS1115 ADC module. We calibrated soil moisture and temperature sensors in
the lab before using them in the field. We also set up a thing, which included creating cloud variables,
device association, network configuration, and coding of the development board. Then, we created a
dashboard to visualize the Thing’s sensor readings with different types of widgets to display current
readings as well as historical data with the help of graphs.
This project will help you and give you the confidence to collaborate with agriculture researchers and
soil scientists to work on a more advanced level. It will help you to add IoT systems to real fields and
tunnel farms, as well as help you in home gardening.
In the next chapter, we will work on a smart home project where we will develop a smart RGB LED
light that will be connected to the Amazon Alexa Voice assistant and help you to understand and
develop smart home solutions.
10
Project #6 – Making Your Home
Smarter with a Voice Assistant
This chapter is dedicated to smart homes. Smart homes is a wide field that aims to automate everything
in your home to make your life experience better and more comfortable, for example, smart light
systems, smart air conditioning, smart TVs, and so on. But in this chapter, we will explore how we can
build a multi-color smart bulb that is controlled by the Arduino IoT Cloud web and mobile dashboard.
We’ll also add the Amazon Alexa voice assistant to control the smart bulb using voice commands.
Here, we will practically explore smart homes, picking up the WS2812 RGB LED ring and Seeed
Studio’s newest, and very small, development board in the XIAO series, which is based on ESP32 with
a lot of features. With the help of the light module, development board, and the Arduino IoT Cloud,
we will build a smart light system.
By the end of this chapter, you will have the confidence to build smart home solutions with the help of
any open source ESP32/ESP8266 or Arduino series development board using the Arduino IoT Cloud.
In particular, you will learn how easy it is to integrate Amazon Alexa Voice assistant into your smart
home projects to make them more convenient for end users.
In this chapter, we’re going to cover the following main topics:
Technical requirements
The following hardware components are required to complete this chapter’s exercise:
For coding, we will use the Arduino Web Editor, which includes a large collection of development
boards and sensor libraries, and the Arduino IoT Cloud for the Thing and dashboard setup. To
develop hardware and sensor designs, we need the Fritzing desktop software and the Arduino IDE
for testing the WS2812 ring.
Here, we will use the Amazon Echo Dot as a voice assistant for voice commands to control the smart
bulb. If you don’t have an Echo Dot, then you can use the Amazon Alexa app for Android/iOS. The
chapter’s code is available in the official GitHub repository for the book by following this link: https://
github.com/PacktPublishing/Arduino-IoT-Cloud-for-Developers.
• Connectivity: IoT devices in a smart home are connected to the internet, allowing them to
communicate with each other, as well as with the homeowner, remotely. This connectivity
facilitates the control, monitoring, and automation of devices from anywhere, using smartphones,
tablets, or computers.
• Home automation: IoT enables the automation of various tasks within a smart home. For
example, lights can automatically turn on or off based on occupancy or the time of day.
Thermostats can adjust temperature settings based on the homeowner’s preferences or presence
in the house. IoT-powered automation helps optimize energy usage, enhance security, and
simplify routine activities.
Creating smarter homes with IoT 255
• Security and surveillance: IoT devices can enhance the security of a smart home. Smart locks
provide keyless entry and allow remote access control. Video doorbells enable homeowners
to see and communicate with visitors remotely. Surveillance cameras can be accessed and
monitored from anywhere, providing an additional layer of security.
• Energy management: IoT devices help optimize energy consumption within a smart home.
Smart thermostats learn user preferences and adjust temperature settings accordingly, conserving
energy when rooms are unoccupied. Smart plugs and power strips can monitor and control
the energy usage of appliances and electronics, helping identify energy-hungry devices and
promoting efficient usage.
• Voice control: Voice assistants, such as Amazon Alexa or Google Assistant, integrated with
IoT devices enable hands-free control of various functions in a smart home. Homeowners can
use voice commands to control lights, adjust thermostats, play music, check the weather, and
perform other tasks, enhancing convenience and accessibility.
• Health and wellness: IoT devices can contribute to health and wellness within a smart home.
Wearable devices, such as fitness trackers or smartwatches, can integrate with other home
devices, such as smart scales or health monitors, to provide comprehensive health data and
insights. This data can be shared with healthcare professionals or used to automate certain
health-related tasks.
• Appliance control: IoT enables the remote control and monitoring of various appliances in a
smart home. Refrigerators, ovens, washing machines, and other appliances can be connected
to the internet, allowing homeowners to check their status, receive alerts, or control their
operation remotely. This connectivity adds convenience and flexibility to household chores
and management.
• Integration and interoperability: A crucial aspect of IoT for smart homes is the integration
and interoperability of devices from different manufacturers. Standards and protocols, such
as Zigbee or Z-Wave, facilitate the seamless connection and communication between devices,
ensuring that different IoT products can work together in a unified ecosystem.
It’s important to note that while IoT technology brings numerous benefits to smart homes, it also
introduces potential security and privacy risks. Homeowners should take measures to secure their IoT
devices, such as using strong passwords, keeping firmware up to date, and ensuring proper network
security configurations.
Here, we have discussed in detail how IoT is reshaping the lives of human beings in homes and offices.
Next, we are going to talk about the hardware and components that we require to carry on with this
chapter’s project.
256 Project #6 – Making Your Home Smarter with a Voice Assistant
XIAO ESP32C provides multiple pins for digital input/output. In the previous ESP series board, we
found only one analog pin, but on this development board, we have four analog pins, which removes
the biggest hurdle while developing a solution that uses multiple analog pins. With previous ESP
series boards, we used ADS1115/ADS1015 for extra analog pins, so this development board will save
us some bucks as we will get four analog pins by default on the development board.
Besides all those features, XIAO provides a built-in battery charge module and the board is optimized
for power consumption, which helps to use this board as a wearable device. For connectivity, there are
both Wi-Fi and Bluetooth options available. It also supports Bluetooth Low Energy (BLE 5), which
is more specific to IoT use cases. For further details, please visit https://wiki.seeedstudio.
com/XIAO_ESP32C3_Getting_Started/.
In the current project, we need one digital pin for the WS2812 RGB LED ring. One of the good
features of the development board is that we have a 5V power pin, which is not available on most of
the ESP32 series development boards.
Essential components – sensors and development boards 257
We are using the WS2812 16-pixel RGB ring but it comes in different pixels and shapes, such as a
stick, matrix, and strip. For the lamp, we prefer the ring shape, but you guys can choose according to
your preferences. WS2812 also comes in long strip cables for room decoration and computer tables –
especially for gamers, hotels, and so on. There are different vendors who provide the WS2812 module,
but we are using a WS2812 that we purchased from AliExpress and it’s working perfectly. You can buy
it from Amazon, AdaFruit, SparkFun, or from AliExpress.
WS2812 comes with RGB color, and it also allows you to control the brightness of the module, which
varies from 1–100%. It also allows you to control every single pixel of the LED – either on/off, or any
color, which provides a broad range of use cases to develop interesting solutions and prototypes. The
WS2812 RGB LED comes in different sizes and shapes. The following figure shows the RGB LED ring
with both the front and back sides.
The preceding diagram depicts the pinout layout of the WS2812 RGB ring. The complete configuration
of the pin connections of WS2812 with XIAO ESP32C3 is shown in Table 10.1. Pin #1 is a GND pin
that connects with the onboard GND pin of XIAO ESP32C3. Pin #2 is a Power 5V DC pin that works
with both 3.3V and 5V. Pin #3 is Data Input, which connects with any digital pin. Pin #4 is Data
Out, which is only used if you want to extend the WS2812 ring with another ring or stick – this pin
will connect to the other ring’s data input pin as an extension. Here, I am connecting Data Input
with Pin #D3 of the board. You can solder the male headers with WS2812 or directly solder the cables
without any header pins.
Important note
The WS2812 module works perfectly, but still it’s necessary to verify that all pixels of the ring/
strip are working perfectly. In my case, my last pixel is not working.
258 Project #6 – Making Your Home Smarter with a Voice Assistant
In the current section, we have discussed the XIAO ESP32C3 and WS2812 RGH LED ring, as well
as its pins. Next, we are going to discuss the project architecture in detail, which includes the project
schematics and assembly.
Figure 10.3 illustrates the pin diagram of the whole setup, but for easy guidance, we also created Table
10.1, which explains, in a simple way, how to connect the pins of WS2812 to XIAO ESP32C.
The preceding design and table provide a full overview of how you can connect the sensors to the
development board. According to the design, we have common 5V and GND pins from the XIAO
ESP32C3 board to the WS2812 module. WS2812 is a digital module so we connected its Data Input
pin to the D3 pin of the development board. The following figure shows the final prototype of the
smart bulb on the veroboard.
After soldering cables to the module and the male header to the XIAO ESP32C3, connect the pins
according to the schematic diagram. There is only one module, so there is no requirement for a
veroboard. But I am developing a proper prototype this time – that’s why I used a Veroboard. Now
it’s time to verify the colors and pixels of the WS2812 using ESP32C3.
260 Project #6 – Making Your Home Smarter with a Voice Assistant
1. Navigate to File > Preferences and fill Additional Boards Manager URLs with the URL
https://raw.githubusercontent.com/espressif/arduino-esp32/
gh-pages/package_esp32_dev_index.json, as shown in the following figure.
2. Later on, navigate to Tools > Board > Boards Manager..., type the keyword esp32 in the
search box, select the latest version of esp32, and install it, as shown in the following figure.
3. Finally, select the board, navigate to Tools > Board > ESP32 Arduino, and select XIAO_
ESP32C3. The list of boards is a little long and you need to scroll to the bottom, as shown in
the following figure.
It’s time to install the WS2812 library. Navigate to Sketch > Include Library > Manage Libraries.
Type Adafruit neopixel in the search bar. Here, you will get different libraries, but you need
to install the specific library that matches the search query.
Now we are ready to proceed with the testing steps. Download the code from the official GitHub
repository for the book, navigate to the WS2812_Testing folder, and open up the code:
#include <Adafruit_NeoPixel.h>
#define LED_PIN D3
// How many NeoPixels are attached to the Arduino?
#define LED_COUNT 16
// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
void setup() {
strip.begin(); // INITIALIZE NeoPixel strip object
(REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)
}
Change the LED_PIN constant to D3 or D5. Next, assign the number of pixels to the LED_COUNT
constant. Right now, I have 16 pixels in the WS2812 – that’s why I am inserting 16. After making
modifications, upload the code to the board. Later, you will see the color white on the LED and a
moving animation in a circular form. In the setup() method, we initialized NeoPixel strip
and set the brightness to 50%:
strip.show();
}
Later, in the loop() method, there are two loops. The first loop is used to assign the white color to
each pixel and turn on the pixel according to the loop value, with a delay of 200 milliseconds, while
in the second loop, we turn off all the pixels one by one by changing the brightness to 0 and RGB
colors to 0.
In this section, we have assembled the hardware component on the veroboard and used the code to
verify that the WS2812 RGB LED is working. Next, we will set up the Thing and cloud variables in
the Arduino IoT Cloud to make our prototype live.
Set up a new Thing with the name Voice Controlled Smart Lamp and follow these steps to
create variables, associate a device and network configuration, and finally, write the code:
1. Firstly, we need to set up three cloud variables for the WS2812. Complete details regarding
cloud variables are available in the following section.
2. After that, we need to associate the device with the Thing. In the current project, we are using
the XIAO ESP32C3, so the wizard will be different than for Arduino boards. The complete
details are available in the Associating a device section.
3. Finally, we need to set up the network configuration for the device, but this time we need to
provide a security key for ESP series boards to make the connection secure. Arduino-compatible
boards are configured by the Arduino IoT Cloud automatically during the device setup wizard.
Cloud variables
The following table provides all the properties of the variables that we need to use during cloud variable
creation. For the WS2812, we can use the integer and bool data types, which creates a lot of mess, but
thanks to the Arduino IoT Cloud’s extended group of variables, we have the Dimmed light, Color,
and Colored Light type variables. Next, make sure the same variables are declared as shown in Table
10.2, otherwise, you’ll need to modify the example code according to your naming.
Here, I made the permission read and write, as this time we will send commands from the cloud
dashboard or voice assistant, so it’s mandatory to give cloud variables permission to read and write.
Previously, I mentioned that we only need one cloud variable, but I am using three different cloud
variables and will explain their usage. If I start from the Dimmed light type cloud variable, then it
has only two options to control the WS2812 – one is brightness and the second is the on/off switch.
The Color type cloud variable, which is RGBLightColor, has only one option regarding the color
change. But if we come to the Colored Light type cloud variable, then it provides all three options:
brightness, color, and an on/off switch. This cloud variable is also compatible with Amazon Alexa and
that type cloud variable will be represented as a device in the Amazon Alexa Smart Home skills portal,
which is discussed in the Enhancing control – Integrating Arduino IoT Cloud with Amazon Alexa section.
Initial setup – Thing, network credentials, cloud variables, and code 265
Associating a device
After variable creation, it’s time to add a device associated with the Thing. Before adding the device,
connect the development board to the computer and open the Arduino Create Agent application.
The following figure shows how to select the ESP32 and then the XIAO_ESP32C3 development board
in the popup.
1. Click on the Select Device button under the Associated Device section on the Thing page
shown in Figure 10.8.
2. A popup will appear where you can see all the devices that are already available. If you have
already added your XIAO ESP32C3, select it. Otherwise, click on SET UP NEW DEVICE.
3. Next, click on the Third party device option.
4. Select ESP32 and XIAO_ESP32C3 from the dropdown and click on the CONTINUE button
shown in Figure 10.9.
5. Fill in Device Name and click on the Next button.
6. In the final wizard, Device ID and Secret Key will be displayed. Copy the secret key to a safe
place as it will be used during the network configuration.
Network
After associating the device with the Thing, it is time to configure the Wi-Fi settings for device
communication. The following figure shows the network configuration popup with the Wi-Fi Name
and Password fields.
You will find a new field – Secret Key. Paste the secret key that we received from the system during
device creation.
Coding
The chapter’s code is available at the official GitHub repository for the book. Download the Voice_
Controlled_Smart_Lamp_may13a code from the repository and import it to the Arduino
Web Editor.
Initial setup – Thing, network credentials, cloud variables, and code 267
You can download the code and put it into your Thing by navigating to the Sketch tab. I am not going
to discuss that code as you will get the idea after reading it. But here, I will explain the main workflow
that initializes all the things in the setup. Remember, never try to use the delay() method – it will
block the ArduinoCloud.update() method. But before moving forward, at the start of the
code, we need to change the Pin# of the LED_PIN constant to 5 and assign a value to LED_COUNT
according to the number of pixels in the ring/strip. Here, I am assigning the value 16 as I am using
a 16-pixel ring:
#define LED_PIN 5
// How many NeoPixels are attached to the Arduino?
#define LED_COUNT 16
// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
//Sync Variables
bool swi;
float bright;
float sat;
float hue;
If we review the preceding code for the constant, then we will see there is one NeoPixel strip
object and four global variables for the switch (swi), brightness (bright), saturation (sat), and
hue that will be used later to sync the values from one widget control to another widget control to
enable the synchronization between widgets.
After filling the preceding constants with appropriate values, it’s time to explore some other methods.
If we talk about the setup, then there are only a few lines that initiate the NeoPixel strip object
as well as the Arduino IoT Cloud and some other operations. In this project, our loop() method
will include one line regarding an Arduino Cloud update and nothing else. Actually, in this project,
code will be executed where any change happens on the widget side.
In the project, we have four more methods. Three are event-oriented and one is a common
helper method that will be used by three event-oriented methods to perform operations on
WS2812. Here, the onLightBrightnessChange(), onRGBLightColorChange(), and
onTableLightChange() methods are event-oriented and the ControlTheWS2812() method
is a common helper method. Next, we are going to explore all the methods step by step:
void onLightBrightnessChange() {
// Add your code here to act upon LightBrightness change
swi=lightBrightness.getSwitch();
bright=lightBrightness.getBrightness();
void onRGBLightColorChange() {
// Add your code here to act upon RGBLightColor change
hue=rGBLightColor.getValue().hue;
sat=rGBLightColor.getValue().sat;
bright=rGBLightColor.getValue().bri;
The onRGBLightColorChange() method is the second method that will be called when there
is any change in the color widget control. This method fetches hue, saturation, and brightness values
from the Color type cloud variable and later assigns these values to other cloud variables as well as
global variables. The last calling method, ControlTheWS2812(), performs the operation on the
WS2812 ring according to global variable values:
void onTableLightChange() {
// Add your code here to act upon TableLight change
swi=tableLight.getSwitch();
bright=tableLight.getBrightness();
hue=tableLight.getHue();
sat=tableLight.getSaturation();
The onTableLightChange() method is associated with the Colored Light control widget and
it will be called when there is any change to the switch, brightness, or color. This method will fetch
four values from the tablelight cloud variable and assign these values to global variables as well
to two other cloud variables for synchronization. The last calling method, ControlTheWS2812(),
will perform the operation on the WS2812 ring according to global variable values:
void ControlTheWS2812(){
// declare a variable of the Color data type and define it using the
HSB values of the color variable
Color currentColor=Color(hue,sat, bright);
byte RValue;
byte GValue;
byte BValue;
currentColor.getRGB(RValue, GValue, BValue); // the variables will
contain the RGB values after the function returns
if(swi==true){
strip.setBrightness(bright);
for(int i=0; i<LED_COUNT+1; i++){
strip.setPixelColor(i, strip.Color(RValue, GValue, BValue));
// Set pixel's color (in RAM)
strip.show();
}
}else{
for(int i=0; i<LED_COUNT+1; i++){
strip.setBrightness(0);
strip.setPixelColor(i, strip.Color(0, 0, 0)); // Set pixel's
color (in RAM)
strip.show();
}
}
}
Finally, we have our last, common helper method, ControlTheWS2812(). This method will first
generate RGB color from hue, saturation, and brightness. Then it will check the switch value – if it is
true, then the condition will assign the brightness and color to the WS2812 ring and turn on every
pixel of the ring with the help of the for loop. Otherwise, it will set the brightness to 0 and turn off
all the pixels of the WS2812.
270 Project #6 – Making Your Home Smarter with a Voice Assistant
Important note
If you used different naming in the variable declaration, then update the code according to
your naming scheme. But it’s better if you first follow all the steps according to the book and
later change the cloud variable names and modify your code respectively.
The Arduino IoT Cloud only updates the values on the dashboard whenever a variable value
is changed. For example, if the temperature is 30 and after 5 minutes it’s the same, then the
Arduino IoT Cloud will not record the value. So, don’t get confused if values are not changed
on the widget controls. Another benefit of this feature is you will not get duplicated data when
you are exporting the content.
In this section, we set up the Thing, associated the XIAO ESP32C3 with the Thing, and set up cloud
variables of different types to control LED operations. We also discussed the code for the device in detail,
step by step, according to different methods. Now, in the next section, we will set up the dashboard.
We have three core functionalities of WS2812, which include RGB color, brightness, and the on/off
switch. In the previous section, we created three different cloud variables, which provide different
functionalities. That’s why here we have three different widget controls, which only work with these
cloud variables. The first widget is Colored Light, which is linked to the tableLight cloud variable
and capable of performing all of the operations on the WS2812, such as color change, brightness
control, and switching it on and off.
Next, we have two more controls with limited functionalities. The second widget is Dimmed light,
which is linked with the lightBrightness cloud variable and only provides an on/off switch and
brightness control, while our third widget control is Color, which is linked with the rGBLightColor
cloud variable and only provides the option to choose the color. If we compare all three widgets, then
the Colored Light widget is equal to both Dimmed light and the Color widget, as the Colored Light
widget has three functionalities, which include turning it on and off, color selection, and brightness
control, while the Dimmed light widget control has only two options, brightness control and turning
on and off functionality, and the Color widget control only has the option to choose the color.
So, the final conclusion is if you have a multi-color strip with a brightness control feature, then the
Colored Light widget and cloud variable are good to go; otherwise, for a single-color light with brightness
control, the Dimmed light widget and cloud variable are perfect. And if you have only a strip with
the multi-color option without a brightness control, then a simple Color widget and cloud variable
type are enough but remember the Color type cloud variable is not compatible with Amazon Alexa.
In this section, we have set up the dashboard with different types of widget controls, which help you
to control WS2812 in different ways, such as controlling the brightness, color, and turning on and off
the LED ring. Next, we are going to set up the Amazon Alexa Skill with the Arduino IoT Cloud to
control our table lamp with voice commands using Amazon Alexa.
The Arduino IoT Cloud natively developed a skill for Amazon Alexa, which can be found at https://
www.amazon.com/Arduino-LLC/dp/B07ZT2PK2H. Set up your Amazon Alexa and navigate
to the preceding URL to enable a skill, which is shown in the preceding figure. When you link the
account, it will automatically link the Arduino IoT cloud account that is already logged in with this
Skill. So, make sure you are already logged in to the Arduino IoT Cloud. The preceding figure shows
the Arduino Skill for Amazon Alexa.
Finally, turn on your Amazon Echo Dot and WS2812-based smart lamp and try the following voice
commands on Amazon Alexa. Firstly, try these commands, which will help you turn on/off TableLight.
As shown in the preceding figure, TableLight is now acting as a device in the Amazon Alexa smart home:
Now it’s time to change the brightness and colors of the WS2812 using voice commands. Try the
following commands, which will help you to update the brightness and colors. Right now, I have just
written four different colors, but you can choose any color name that you want:
Finally, I am using the Alexa timer functionality to schedule turning on/off the table light after a specific
time interval. But you can also use this function just like an alarm and turn on/off the WS2812 for long
intervals, such as to turn on the light early in the morning, turning off the lamp at 10:00 P.M., and so on:
We have discussed different voice commands for Amazon Alexa, but you can search on the internet
for more commands regarding light controls and colors.
Now it’s time to talk about which Arduino Cloud variables are compatible with Amazon Alexa. You can
get up-to-date information at https://www.amazon.com/Arduino-LLC/dp/B07ZT2PK2H.
At the moment, we have the following list of cloud variables that work perfectly with Amazon Alexa:
• Temperature
• Motion detection
• Light, smart plug, and smart switch
• Dimmed light
• Colored light
According to the preceding list, you can create a thermostat for a room, which will help you to change
the room or kitchen temperature according to outdoor and indoor thermostat temperature, you can
control your heating and cooling system. To turn on/off any device, we have four different types of
cloud variables, which have the same data type Boolean but different names, including light, smart
plug, smart switch, and motion detection. These four variables could be used to control any relay/
magnetic contactors to turn home appliances on/off, such as cooling/heating systems. We have already
discussed Dimmed light and Colored Light in previous sections.
In this section, we have set up the Amazon Alexa with Arduino Cloud skill and tried different voice
commands related to turning lights on and off, as well as how to change the color and brightness of
the WS2812 RGB LED ring.
What next? 275
What next?
We still have lots of options available to explore, but now your assignment is to use different relays,
sensors, and development boards to do some more experiments and learn from them. In the current
chapter, we have only used one WS2812 module for light control, but you can use temperature sensors,
relays, and motion sensors to automate your devices in your home, such as automating room switches
to control fans, exhaust fans, lights, and air conditioning systems according to room temperature.
Important note
Be careful when playing with high-voltage power cables when patching the cables to relays.
Summary
In this chapter, we have explored how to develop a low-cost, multi-color smart table lamp for our
room using the XIAO ESP32C3 and WS2812. We have set up the Thing, which included cloud variable
creation, device association, network configuration, and coding of the development board. Later, we
created a dashboard using different widgets to control the WS2812 RGB ring. Finally, we used the
Amazon Alexa voice assistant to turn our table lamp on/off and control its color and brightness with
voice commands.
This chapter will give you the confidence to build more interesting stuff to make your home and office
smarter. In the next chapter, we will talk about Cloud Scheduler and over-the-air update’ features.
Both features are interesting and specially designed to carry out operations on IoT nodes.
Part 4:
Learning Advanced Features
of the Arduino IoT Cloud and
Looking Ahead
In Part 4, the reader is guided through the advanced features of the Arduino IoT Cloud platform,
how to use them to develop professional applications, and the tools for maintaining solutions during
their life cycle. The book ends with some suggestions for further learning, experimenting, and
sourcing information.
This part has the following chapters:
• Chapter 11, Implementing the Arduino IoT Cloud Scheduler and Over-the-Air Features
• Chapter 12, Project #6 – Tracking and Notifying about Your Heart Rate
• Chapter 13, Scripting the Arduino IoT Cloud with Cloud CLI
• Chapter 14, Moving Ahead in the Arduino IoT Cloud
11
Implementing the Arduino
IoT Cloud Scheduler and
Over-the-Air Features
The world is full of different and interesting use cases that vary according to different circumstances.
In the world of full automation, many use cases require applications to perform a specific operation
at a certain time or frequency, defined by an end user. To handle this situation, the Arduino IoT
Cloud has a Scheduler feature to let end users configure the execution time and frequency through
a dashboard, without any modification to code on end devices. Initially, in this chapter, you will learn
about the Arduino IoT Cloud Scheduler feature and its implementation.
Then, this chapter will cover the Over-the-Air (OTA) feature, which is becoming increasingly popular
in remote devices such as mobile nodes, especially remote IoT nodes. The OTA feature allows you
to broadcast the firmware update to IoT nodes, which will update wirelessly without any physical
connection. This procedure enables the remote maintenance of commercial Arduino-based/ESP-series
IoT nodes during their life cycle, reducing the related service costs when new features and security
fixes become available.
The Arduino IoT Cloud Scheduler provides the ability to schedule operations via a dashboard widget,
which helps to execute the operations on devices without modifying the code, and a user can simply
adjust the time for routine operations. OTA helps you to send the latest code and updates to devices
over the air without any physical connection to a device, which will save operational costs and time.
In this chapter, we will cover the following topics:
Technical requirements
Before we go any further, first of all, you need to have an Arduino IoT Cloud-compatible board. I
recommend Arduino MKR Wi-Fi 1010 with a bunch of 5 mm LEDs, but here is the complete list of
compatible boards: https://store-usa.arduino.cc/pages/cloud-compatible-
boards. You can choose one according to your requirements.
Second, you need to have an Arduino IoT Cloud account. If you don’t already have one, you can sign
up at https://cloud.arduino.cc/ and select a plan according to your requirements.
Third, we need to download and install the Arduino Create Agent. Arduino has created a very beautiful
web-based guide for installation at https://create.arduino.cc/getting-started/
plugin/welcome. The code for this chapter is available in the book’s official GitHub repository
at https://github.com/PacktPublishing/Arduino-IoT-Cloud-for-Developers.
Important note
All the Arduino IoT Cloud plans were discussed in detail in Chapter 1. You can also visit the
following link for updated plan pricing and features: https://cloud.arduino.cc/
plans/. If you are from an educational institute, then there are plenty of good plans for
students and faculties. Arduino also offers customized plans to business organizations according
to their requirements.
• Task coordination: The scheduler facilitates the orchestration of multiple tasks and processes
in an IoT cloud by allowing users to define dependencies and priorities. This ensures that tasks
are executed in the desired sequence, which is particularly crucial in complex IoT systems
involving interconnected devices and services.
• Resource optimization: With the limited computational resources typically found in an IoT
cloud, a scheduler optimizes its utilization by intelligently assigning tasks based on requirements,
available resources, and priorities. This prevents resource overloading or underutilization,
leading to enhanced efficiency and cost-effectiveness.
Using the Arduino IoT Cloud Scheduler – an MKR Wi-Fi 1010 illustration 281
Overall, a scheduler in an IoT cloud environment brings organization, efficiency, and reliability by
coordinating tasks, optimizing resources, synchronizing time, conserving energy, ensuring fault
tolerance, and supporting scalability. Its presence is instrumental in managing the complexities of
IoT systems and maximizing their performance.
In this section, we have discussed in detail what a scheduler is and how we can benefit from it in
product development. In the following section, we will take a look at how the Arduino IoT Cloud
Scheduler benefits us in terms of real-world scenarios, and we will also learn how to implement the
Arduino IoT Cloud Scheduler using MKR Wi-Fi 101.
• Task scheduling: The Arduino IoT Cloud Scheduler allows users to schedule tasks and events
on their Arduino devices. It enables the definition of specific timings, intervals, or triggers for
actions such as data collection, device control, and sensor readings.
282 Implementing the Arduino IoT Cloud Scheduler and Over-the-Air Features
• Remote control: By leveraging the Scheduler, users can remotely trigger actions on their
Arduino devices. This capability enables the control and automation of functions from any
location, without the need for direct physical access to the devices. It enhances flexibility and
enables the efficient remote management of IoT projects.
• Event-based triggers: The Scheduler supports event-based triggers, empowering users to
automate actions based on specific events or conditions. For instance, tasks can be scheduled
to execute when a particular sensor value surpasses a defined threshold or when an external
event is detected.
• Time zone management: The Arduino IoT Cloud Scheduler handles time zone management,
ensuring that tasks are executed according to the desired time zone. This functionality is
particularly useful when operating across different time zones or serving users in diverse regions.
• Integration with IoT cloud services: The Scheduler seamlessly integrates with other features and
services offered by the Arduino IoT Cloud platform. This includes data storage, visualization,
and notification services. Users can combine scheduling with data logging, charting, and alerting
to create comprehensive and cohesive IoT applications.
• Flexibility and customization: The Arduino IoT Cloud Scheduler provides a high degree of
customization, enabling users to define complex schedules and conditions for their tasks. Users
can specify the task frequency, duration, and intervals, and configure advanced parameters to
align with their specific requirements.
By harnessing the power of the Arduino IoT Cloud Scheduler, users can automate tasks, remotely
control devices, and establish time-based or event-driven workflows for their Arduino-based IoT
projects. This feature simplifies the management and coordination of actions across devices, elevating
the functionality and efficiency of IoT applications.
In this section, we discussed how the Arduino IoT Cloud Scheduler provides a benefit to schedule
our tasks. In the next section, we will implement a Scheduler using MKR Wi-Fi 1010.
Here, we will just use three LEDs for three different schedulers/timers. We used Pins 8, 7, and 6 to
attach the LEDs with the MKR Wi-Fi 1010, using a 220-Ohm resistance, which will control the power
from these pins, and one common ground (GND) goes to all the LEDs via the breadboard.
In this section, we discussed the schematic diagram of our project, where we explained which pins
are used to connect the LEDs with the MKR Wi-Fi 1010. In the upcoming section, we will set up a
Thing and device association with the Thing, and cloud variable creation and network configuration
will be discussed step by step, along with code.
Set up a new Thing with the name CloudScheduler. Take the following steps to create cloud
variables, associate a device, set up network configuration, and finally, write the code. In Figure 11.2,
all the steps are marked with a number above red boxes, which relate to the following steps:
1. Firstly, we need to set up three cloud variables for CloudScheduler. The complete details
regarding cloud variables are available in the next section.
2. After that, we need to associate the device with the Thing. In the current project, we are using
Arduino’s MKR Wi-Fi 1010, so the wizard will be the same for Arduino boards. The complete
details are available in the Associating a device section.
3. Finally, we need to set up the network configuration for the device. Arduino-compatible boards
are configured by the Arduino IoT Cloud automatically during the device setup wizard, so you
just need to provide the Wi-Fi service set identifier (SSID) and password.
Cloud variables
The following table explains all the properties of the variables that we need to use during cloud variable
creation. For the Scheduler, we will use a custom data type, Schedule, which we have thanks to
Arduino IoT Cloud’s extended group of variables. Then, make sure you have the same declaration
variable as per the table; otherwise, you will need to modify the example code according to your naming.
Initial configuration – Things, network credentials, cloud variables, and code 285
Here, I set the permission as read and write because we will input the date, time, and interval from the
Arduino dashboard, which will be controlled by the end user, and the device will only perform the
LED on/off operation when the Scheduler is in a state of true. Update Policy is set to On change, as
the dashboard will send data to the device when there is any change in Scheduler values by the user.
Associating a device
After creating the variable, it’s time to add a device and associate it with the Thing:
1. Before adding the device, connect the development board to the computer and open the
Arduino Create Agent application.
2. After assigning a name to the Thing, we need to attach the device to it. When you click on the
Select Device button, you will see a popup that shows you the available devices and an option
to add a new device. In our case, we don’t have a device in the portal, so we can just click on
SET UP NEW DEVICE to configure a new device in the account.
3. Then, you will see two options in the popup. The first option is Set up an Arduino device, and
the second option is Set up a 3rd Party device. Here, you will see a note under both options
that says Compatible devices. This means you cannot use all types of Arduino devices and
third-party devices with the Arduino IoT Cloud.
Select one option from the popup according to the available device. For this example, we will
click on Set up an Arduino device, as in this chapter, we are using an MKR Wi-Fi 1010 board.
Before adding the device, make sure the Arduino Create Agent is running on your machine.
Important note
Here is the link where you can find the Arduino IoT Cloud-compatible boards: https://
store-usa.arduino.cc/pages/cloud-compatible-boards. For third-party
devices, we have three options, which are ESP8266, ESP32, and LoRaWAN devices. For other
devices, we have API access, which was discussed in the second part of Chapter 2.
Initial configuration – Things, network credentials, cloud variables, and code 287
4. Now, you will see the Setup Device popup, which will start searching for your device. Make
sure the device is properly connected to the machine.
The wizard will find and list all the connected boards with their name and port details. Click on
the CONFIGURE button to move forward. If the wizard didn’t show the device after searching,
try to plug it into a different port, and click on the refresh link located at the bottom.
5. In the next configuration wizard, provide the device name. Spaces and special characters are
not allowed in the device name. Then, click on the NEXT button.
288 Implementing the Arduino IoT Cloud Scheduler and Over-the-Air Features
After that, the wizard will start the device configuration process. This will take up to five minutes,
but in most cases, it only takes one minute to configure the device.
6. You will then see the Congratulations! You are all set message in the next popup. Click on
the Done button, and the device will be attached to your Thing.
In this section, we associated the MKR Wi-Fi 1010 development board with our Thing. In the next
section, we will configure the Wi-Fi network configuration for the MKR Wi-Fi 1010.
Network configuration
After the attachment of the device with the Thing, we can see that the device is offline. To get it online,
we need to provide the Wi-Fi details.
Initial configuration – Things, network credentials, cloud variables, and code 289
On the Thing page under the Network tab, click on the CONFIGURE button. You will see the
Configure network pop-up box with two fields – Wi-Fi Name and Password. Type in the Wi-Fi
SSID and password, and click on the SAVE button.
We are done with the device and network configuration; only the coding part is left. In the next section,
we will look at the code for the device.
Coding
The code for this chapter is available in the book’s official GitHub repository. Download the Cloud_
Scheduler_may22a code from the repository, and import it to your Arduino Web Editor.
You can download the code and put it into your Thing by navigating to the Sketch tab. The whole
project code is very small and simple; that’s why I will go through all the code here and discuss it in
detail. Remember, never try to use the delay() method, as it will block the ArduinoCloud.
update() method:
#define LED1 8
#define LED2 7
#define LED3 6
290 Implementing the Arduino IoT Cloud Scheduler and Over-the-Air Features
Here, we have very simple code. Firstly, we will define the pins’ LED1, LED2, and LED3 constants,
which will be initialized in the setup() method as output, using the pinMode() method:
void setup() {
pinMode(LED1,OUTPUT);
pinMode(LED2,OUTPUT);
pinMode(LED3,OUTPUT);
// Initialize serial and wait for port to open:
Serial.begin(9600);
// This delay gives the chance to wait for a Serial Monitor without
blocking if none is found
delay(1500);
setDebugMessageLevel(2);
ArduinoCloud.printDebugInfo();
}
Then, we have all the code regarding Schedulers in the loop() method, which will perform an operation
when a scheduler/timer is in an active state. In the following code, we have a separate if-else
statement for each cloudScheduler cloud variable; here, we check whether cloudScheduler
is active and then turn on the LED; otherwise, we turn off the LED. We have cloudScheduler1,
cloudScheduler2, and cloudScheduler3, plus three if-else statements to check their values:
void loop() {
ArduinoCloud.update();
// Your code here
digitalWrite(LED2,HIGH);
}else{
digitalWrite(LED2,LOW);
}
The Scheduler widget is very complex in configuration with lots of options, but its code is very simple
and straightforward. You just need to verify whether the Scheduler state is true or false, and if it’s
true, then proceed with the task; otherwise, stop the task. So, in the loop() method, we have three
if-else statements, which check different cloud Schedulers’/timers’ states. If a specific Scheduler
is active, then a specific LED will be turned on; otherwise, it will be turned off.
I attached the LED in Pin #8 to cloudScheduler1, the LED in Pin #7 to cloudScheduler2,
and the LED in Pin #6 to cloudScheduler3. Now, set the first widget’s time to 5 seconds for every
minute, the second widget to 10 seconds for every minute, and 15 seconds for every minute for the
third widget. All the LEDs will turn on at the same time, but the first LED will be on for 5 seconds,
the second LED will be on for 10 seconds, and the third will turn off after 15 seconds. In this example
project, we have used three different Schedulers to demonstrate how we can use multiple Schedulers/
timers to automate our tasks on a single development board.
Important note
If you used different naming in the variable declaration, then update the code according to your
naming scheme. However, it’s better at first if you follow all the steps according to the book and
later change the cloud variable names and modify your code, respectively.
Also, don’t put the code at the end of the loop() method, as it will create a delay with pulse
sensor readings.
In this section, we discussed code and how it works with the Arduino IoT Cloud Scheduler to turn
the LEDs on and off. In the following section, we will set up a dashboard, where we will place the
Scheduler widget and attach it to our cloud variables.
292 Implementing the Arduino IoT Cloud Scheduler and Over-the-Air Features
We have three Scheduler variables. To visualize all of them, three Scheduler widgets will be linked
to each cloud variable, respectively. The purpose of the three widgets and variables is to demonstrate
how we can set different types of timers. The first widget demonstrates how to use a timer that will
be executed every minute for 30 seconds, the second widget demonstrates how to use a timer that
will be activated every hour for five minutes, and the third widget demonstrates that we can set the
timer for a long period, such as specific days at a specific time. Here, I have set it to be activated on
Monday, Wednesday, and Friday for five minutes.
We just set the different widgets with different timer settings. One of the example settings of the
Scheduler widget is shown in Figure 11.9, and we will explore in depth how to set these settings. This
control widget has multiple options for configuration, so I think it’s necessary to discuss it in detail
for proper guidance.
Dashboard creation and a deep dive into the Scheduler widget 293
When you click on the Scheduler widget, a popup will appear with options, just like in the preceding
figure. Here, I have divided the screenshot into four different numbered sections. From this popup,
you can adjust your time settings from seconds to years and set the start and end date, or choose to
execute without any date limitation. Let’s look at each section:
1. Here, we have two input controls – one is for the starting date and the other is for the starting
time, as indicated by the control headings.
2. Next, we have the Duration setting, in which we have three drop-down boxes – HOURS,
MINUTES, and SECONDS. This will define how long the timer will be executed on the
machine. For example, if you want to perform an operation for 30 seconds, then just select 30
seconds and leave the other fields, or if you want to perform an operation for 5 minutes, then
select 5 minutes and leave the other fields, and so on.
3. Then, we have the Repeat every setting, which is only applicable for Week, Month, and Year;
there is no predefined setting for minutes and hours. I have selected Week. Under that, the days
are shown (by their first letter), and there, you can select on which day/days you can perform an
operation. There are different options for Month and Year, which will be discussed in a moment.
294 Implementing the Arduino IoT Cloud Scheduler and Over-the-Air Features
4. Finally, we have the End recurrence setting. Here, we have two options – Never and On. When
you click on On, you will need to enter the date and time when your operation will be stopped.
If you want to execute it indefinitely, then just select the Never option.
For Year and Month in the Repeat every section, we have different options in the Scheduler. The
following figures show all the details regarding both options. First, let’s look at Month:
For Month, we have a dropdown that allows us to select the day (such as 1st), while in the case of
Year, we have two dropdowns – one for the day and one for the month (such as 1st January).
In this section, we set up the dashboard with three different Scheduler widgets and assigned them
Boolean-type cloud variables, which will be used in our code to check the Scheduler state and whether
the Scheduler is active or not. In the following section, you have an assignment to use the Scheduler
according to the specified requirements, giving you a proper idea of how you can use the scheduler
functionality in your projects to enhance your product development.
The task at hand – an assignment 295
• Attach three relays to control any electrical/electronic appliance, such as a fan, light, or heater,
using the Scheduler.
• Implement the Scheduler to turn your home’s outside/indoor lights on/off.
• Attach a buzzer instead of LEDs, and create an alarm device for your room/classroom.
• Turn on surprise lighting with the Scheduler for a birthday or anniversary. Use the same light
strip with multiple Schedulers to turn the light strips on/off for different occasions.
• Control the water solenoid valve for your garden/tunnel farm using the Scheduler (this is
optional, and if you have a smart agriculture facility).
In this section, we outlined an assignment that will test your skills with different scenarios and help you
explore the usage of the Scheduler feature in different environments. In the following section, we will
start to explore the benefits of OTA, the Arduino IoT Cloud's OTA features, supported development
boards for OTA, and how to use OTA features in the Arduino IoT Cloud. And, of, course you will
also learn about the pros and cons of the Arduino IoT Cloud OTA.
• Mobile devices: OTA updates are commonly employed to distribute operating system updates,
security patches, and feature enhancements to smartphones and tablets. Users receive notifications,
prompting them to download and install the updates wirelessly.
• Automotive industry: Many modern vehicles are equipped with OTA capabilities, enabling
manufacturers to remotely update the vehicle software, infotainment systems, navigation maps,
and other features. OTA updates can improve vehicle performance, introduce new functionalities,
and address security vulnerabilities.
• IoT devices: IoT devices, such as smart home devices, wearables, and industrial sensors, often
rely on OTA updates to deliver firmware updates, bug fixes, and new features. This enables
manufacturers to enhance device performance, address vulnerabilities, and introduce new
functionalities without the need for physical access to the devices.
296 Implementing the Arduino IoT Cloud Scheduler and Over-the-Air Features
• Set-top boxes and smart TVs: OTA updates are utilized to deliver firmware updates and
software patches to set-top boxes and smart TVs. This ensures that these devices remain up to
date with the latest features, security enhancements, and bug fixes.
OTA updates offer numerous benefits, including convenience, cost-effectiveness, and the ability
to quickly address security vulnerabilities or software issues. However, ensuring the integrity and
security of OTA updates is crucial to prevent unauthorized access or malicious activities that could
compromise the devices or data.
In this section, we explored what OTA is and how it offers benefits in today’s world. In the following
section, we will discuss in detail the Arduino IoT Cloud OTA feature, which includes compatible
devices that are supported by the Arduino IoT Cloud for OTA, and how to use the OTA feature in
the Arduino IoT Cloud to send firmware updates to devices.
• Firmware updates: Users can remotely update the firmware of their Arduino IoT devices as
well as ESP-series devices using Arduino IoT Cloud OTA. This enables the deployment of bug
fixes, security patches, feature enhancements, and new versions of code without the need for
physical access to the devices.
• Code synchronization: The OTA feature ensures that the code running on Arduino/ESP-series
IoT devices remains synchronized with the latest version stored on the cloud. It eliminates
the necessity of manually updating each device individually, thereby maintaining consistency
across the entire fleet of IoT devices.
• OTA configuration: In addition to firmware updates and code synchronization, Arduino IoT
Cloud OTA enables users to remotely configure the parameters or settings of their Arduino/
ESP-series IoT devices. This means device behavior can be modified, thresholds can be adjusted,
and variables can be changed without the need for physical intervention.
• Security and integrity: Arduino IoT Cloud OTA ensures the security and integrity of firmware
updates through authentication and encryption mechanisms. This safeguards against unauthorized
access or tampering during the transmission process, enhancing the security of IoT devices
and preventing potential vulnerabilities.
Leveraging the Arduino IoT Cloud for OTA updates 297
By providing a convenient and secure method to remotely update firmware and configure devices,
the Arduino IoT Cloud OTA simplifies the management and maintenance of Arduino-based IoT
deployments. It enhances efficiency, reduces costs, and enables users to keep their IoT devices up to
date with the latest features, bug fixes, and security enhancements. In the following subsection, we
will discuss the cons of the Arduino IoT Cloud OTA feature.
• Limited bandwidth: OTA updates require data transfer over the internet, which can be costly
or problematic in areas with limited or expensive data bandwidth. Large firmware updates may
consume a significant amount of data.
• Network stability: Reliable internet connectivity is essential for OTA updates. If a device loses
connection during an update, it can result in failed or corrupt firmware, potentially rendering
the device unusable.
• Version control: Managing different versions of firmware across multiple devices can become
challenging. Keeping track of which devices are running which firmware versions and ensuring
compatibility can be time-consuming.
• Compatibility issues: OTA updates may not work seamlessly with all types of devices and
configurations. Ensuring that your hardware supports OTA updates and that you have the
necessary libraries and code in place can be a complex task.
• Latency: Depending on the size of the firmware update and the speed of the internet connection,
OTA updates can introduce latency, causing devices to be temporarily unavailable during the
update process.
• Dependency on the Arduino IoT Cloud: To use the Arduino IoT Cloud OTA feature, you must
rely on the Arduino IoT Cloud platform. If the platform experiences downtime or changes in
its services, it can impact your ability to perform OTA updates.
• Limited rollback options: In some cases, if an OTA update fails or causes issues, rolling back
to a previous firmware version can be challenging, especially if you didn’t plan for rollback
mechanisms in advance.
Despite these cons, OTA updates remain a valuable feature for many IoT projects. However, it’s
essential to carefully assess your project’s specific requirements and constraints before implementing
OTA updates and to address these challenges through proper planning and security measures.
298 Implementing the Arduino IoT Cloud Scheduler and Over-the-Air Features
In this section, we discussed the different benefits of the Arduino IoT Cloud OTA feature as well as its
cons. In the following section, we will take a deeper look into which hardware development boards are
compatible with the Arduino IoT Cloud OTA feature, as it is currently not supported by all hardware
development boards. Therefore, it’s necessary for you to keep this point in mind during the product
development stage if you need an OTA feature for your product.
These are the ESP32-series development boards that are ready for OTA:
• ESP32-S2-DevKitC
• NodeMCU-32-S2
• WeMos LOLIN D32
• ESP32-S3-DevKitC
• ESP32-CAM
• NodeMCU-32S
• Freenove ESP32 WROVER
• ESP32-DevKitC-32E
• DOIT ESP32 DevKit v1
Leveraging the Arduino IoT Cloud for OTA updates 299
The good thing is that Arduino provides the latest features to ESP32-series development boards.
These boards are very popular among students/researchers and professional developers, due to their
cost and availability all around the world. I used the XIAO ESP32-C3 series development board for
various projects and tested the OTA service for that board. From my personal experience, the OTA
service works faster on official Arduino development boards as compared to the ESP32 series, but I
hope in the future that the Arduino Cloud team will optimize the OTA feature for the ESP32 series
board for a faster and better experience.
Important note
The Arduino IoT Cloud offers the OTA feature to Wi-Fi-enabled devices. This means that
LoRaWAN is currently not compatible with the OTA feature.
In this section, we discussed the broad range of compatible boards that support the Arduino IoT
Cloud OTA feature. In the following section, we will take a look at how we can use the OTA feature
in the Arduino IoT Cloud to send firmware updates via the internet, without any device connection
to the host computer.
Figure 11.12 – The physical port connection with the OTA update feature
300 Implementing the Arduino IoT Cloud Scheduler and Over-the-Air Features
My device is connected to my MacBook as well as to the Arduino IoT Cloud via Wi-Fi. That’s why
you can see two options in the preceding figure for sketch uploading. The first one is the Port option,
which is only available when your development board is directly connected to your laptop/computer,
while the second option is Over-the-Air, which is available when your code is configured on your
development board with network settings and successfully connected to the Arduino IoT Cloud over
the internet.
Select the Over-the-Air option, and click on the Sketch Uploading (the green arrow icon) button;
this will start uploading your updated code to the board via the internet without the intervention of a
physical connection. However, how can you confirm that this works via the internet? Just unplug the
development board from your computer and power it with any adapter, but make sure your device
has access to a Wi-Fi router.
After disconnecting from the computer and turning on the device via the power adapter, you will see
only the Over-the-Air update option in your Sketch tab. Just modify your code or add some extra
login details, and click on Sketch Uploading (the green arrow icon), and within a short time, your
code will be on the development board without any hassle.
Based on my experience, I've often thought we should have an option by which we can modify/
update the code of remote devices, such as devices for smart agriculture, warehouse monitoring, and
industrial monitoring, because it’s very difficult to travel to remote places to update/modify the code.
However, the Arduino IoT Cloud OTA feature makes our lives easier overall. With the OTA feature,
we can save time and cost and provide the correct updates on time to our devices without any delay.
Summary 301
Figure 11.14 – The Arduino IoT Cloud OTA behind the scenes
The Arduino IoT Cloud team has simplified the complexity of this process and provides only a single-
click option for developers for OTA. The purpose of this diagram is to give you an overview of how
things work, which will hopefully provide you with new ideas for your future developments.
In this section, we learned how to implement the Arduino IoT Cloud OTA feature to send firmware
OTA. We also discussed how the Arduino IoT Cloud sends firmware updates to devices using the
Amazon S3 service.
Summary
In this chapter, we explored the Scheduler and how we can use the Arduino IoT Cloud to automate
tasks that have different patterns or random patterns of operation. We used simple LEDs with the MKR
Wi-Fi 1010 to demonstrate multiple Scheduler/timer operations, which helped you to understand how
to use this function in real-world projects, such as in smart agriculture and smart industry.
302 Implementing the Arduino IoT Cloud Scheduler and Over-the-Air Features
In the second part of the chapter, we explored OTA. Firstly, we discussed the pros and cons of OTA
and how we can save time and costs with it. Then, we used OTA-enabled development boards to
demonstrate the use of the OTA feature, and finally, we explored how OTA works behind the scenes.
In the following chapter, we will implement a healthcare project. You will learn how to use a heartbeat
sensor as well as the Arduino IoT Cloud webhooks feature, which will send data to a third-party service
(Zapier). We will use Zapier to set up a Zap, which will receive the heartbeat readings and send an
email notification to a designated person if the reading is over or under the threshold.
12
Project #6 – Tracking
and Notifying about
Your Heart Rate
This chapter is dedicated to smart healthcare and wearables. It shows how healthcare devices can be
integrated with the Arduino IoT Cloud platform and offers an example of an interface between the
Arduino IoT Cloud and a third-party service. The notification service sends notifications to recipients
when the measured heart rate exceeds the defined heart rate threshold.
In this chapter, we will embark on a practical exploration of smart health and wearables by working
with a heart rate sensor and Seeed Studio’s newest and very small development board in the XIAO
series, based on ESP32 with a lot of features. With the help of a sensor, a development board, and the
Arduino IoT Cloud, we will build an IoT-enabled wearable healthcare solution. You will also learn
how to set up webhooks for sending the latest heart rate values to Zapier. Finally, you will see how to
set up Zaps in Zapier for email/mobile notifications on heart rate data.
In this chapter, we’re going to cover the following main topics:
Technical requirements
The following hardware components are required to complete this chapter’s exercise:
For coding, we will use the Arduino Web Editor, which includes a large collection of development
boards and sensor libraries, along with Arduino IoT Cloud for Thing and dashboard setup. To develop
hardware and sensor designs, we need the Fritzing desktop software and the Arduino IDE desktop
software for pulse-sensor calibration using the Serial Plotter, which is not available in the Arduino
Web Editor.
We will also use Zapier to send alerts by email when our sensor detects a heart rate above our specified
beats-per-minute (BPM) threshold. You can use a Free/trial account or buy a Zapier Professional
plan according to the requirements of your project as Zapier Professional provides more features
and functions compared to a Free account. The code used in this chapter is available from the book’s
official GitHub repository at https://github.com/PacktPublishing/Arduino-IoT-
Cloud-for-Developers.
• Remote patient monitoring: IoT devices can be used to monitor patients’ health in real time,
even when they are not in the hospital. Wearable devices, sensors, and medical-grade IoT devices
can collect data on vital signs, BPM rates, blood-glucose levels, and medication adherence.
Healthcare providers can use this data to provide personalized care and prevent complications.
• Telemedicine: IoT devices can enable virtual consultations and remote medical services. Patients
can communicate with their healthcare providers using video conferencing, and healthcare
providers can remotely monitor patients’ health through IoT devices. This can improve access
to healthcare services, reduce healthcare costs, and improve patient outcomes.
Knowing the hardware components – sensors and development boards 305
• Smart medication management: IoT devices can help patients manage their medications
more effectively. IoT-enabled pill dispensers can remind patients when it’s time to take their
medication and can track medication usage. Healthcare providers can use this data to provide
personalized care and prevent medication errors.
• Predictive maintenance: IoT devices can be used to monitor medical equipment and predict
when maintenance is required. This can help prevent equipment failures, reduce downtime,
and improve patient outcomes.
• Smart hospital management: IoT devices can be used to manage hospital resources more
efficiently. For example, IoT-enabled asset tracking systems can help healthcare providers locate
medical equipment quickly, reducing waiting times for patients.
In conclusion, IoT can enable smart health solutions that improve patient outcomes and reduce
healthcare costs. Healthcare providers can use IoT data to provide personalized care and make more
informed decisions. As IoT technology continues to evolve, we can expect to see even more innovative
healthcare solutions in the future.
In this section, we have discussed IoT and smart healthcare and how IoT is beneficial to us in the
development of smart healthcare products. Next, we will take a look at what types of hardware and
sensors are required to carry out the exercise in this chapter.
The XIAO ESP32C3 provides multiple pins for digital input/output. In previous ESP-series boards
such as the ESP8266, we only had one analog pin, but we have four on this development board, which
removes the biggest hurdle encountered when developing solutions using multiple analog pins. To get
around this on previous ESP-series boards, we had to use ADS1115/ADS1015 for extra analog pins,
so this development board will save you some bucks with its four analog pins by default.
Besides these features, XIAO provides a built-in battery charge module and the board is optimized
for power consumption, which make this board appropriate for developing wearable devices. For
connectivity, both Wi-Fi and Bluetooth are available, including Bluetooth Low Energy (BLE) 5
support, which is more specific to IoT use cases. For further details, please visit https://wiki.
seeedstudio.com/XIAO_ESP32C3_Getting_Started/.
For our current project, we need one analog pin for the pulse sensor, and a5V pin for power. One
of the good features of our chosen development board is that we have a 5V power pin, which is not
available in most of the ESP32 series development boards.
We use the pulse sensor to measure the BPM but there is a variety of other pulse oximeters on the
market for BPM and pulse measurement. The following pulse sensor (Figure 12.2) is open source,
cheaper, and easier to use than other sensors. You can also use Chinese-made pulse sensors but you
will require controlled conditions while using these sensors.
Knowing the hardware components – sensors and development boards 307
The following is a list of official stores where you can buy the original pulse sensor:
• SparkFun: https://www.sparkfun.com/products/11574
• Adafruit: https://www.adafruit.com/product/1093
• Amazon UK: https://www.amazon.co.uk/dp/B01CPP4QM0
• Amazon USA: https://www.amazon.com/PulseSensor-com-Original-Pulse-
Sensor-project/dp/B01CPP4QM0
The preceding figure shows the pinout layout of the pulse sensor. Pin #1 is the GND pin, which connects
to the onboard GND pin. Pin #2, VCC, works with both 3.3V and 5V. Pin #3 connects to any analog
pin on the board. I connect it to Pin #A1 on the board. You can solder the male headers to the pulse
sensor or directly solder the cables without any header pins.
Measuring a pulse is a very critical and difficult task, but we can benefit from pulsesensor.com,
started by World Famous Electronics LLC as a crowd-funding project. On this site, you can find all the
official details including specifications, how the sensor works, and development board code samples.
Important note
Chinese-made pulse sensors are good for DIY projects, but even sensors from official stores
can’t be deployed in real-world use cases without professional calibration using a real-time
electrocardiogram (ECG), BPM equipment, and a doctor’s verification.
308 Project #6 – Tracking and Notifying about Your Heart Rate
In this section, we discussed the pulse sensor and where you can buy it, as well as examining its pinout
diagram for better understanding. Next, we will examine the project architecture, covering how to
connect the sensors to the XIAO ESP32C3.
The design in the preceding figure provides an overview of how to connect the sensors to the
development board. According to our design, we have 5V and GND from the development board to
the pulse sensor. The pulse sensor is an analog sensor, so we connected its Signal pin to the A1 pin
of the development board.
After soldering the male headers to the pulse sensor and the XIAO ESP32C3, connect the pins
according to the schematic. There is only one sensor, so no veroboard is required. Figure 12.4 shows
the pulse sensor connected to the XIAO ESP32C3 without any breadboard or Veroboard, but rather,
directly connected with jumper wires. Now, it’s time to calibrate the pulse sensor and get an appropriate
threshold value by putting your fingertip on the sensor.
Sensor calibration
For sensor calibration, we need the Serial Plotter to identify the pulse value threshold. Currently, the
Arduino Web Editor does not support the Serial Plotter, so we are going to use the Arduino IDE. To
work with the Arduino IDE, we need to install the Seeed Studio XIAO ESP32C3 series development
board and the pulsesensor.com library.
To install the ESP32 series development board in the Arduino IDE, firstly, add the board’s definition
file in the preferences:
1. Navigate to File > Preferences, and fill the Additional Boards Manager URLs field with the
following URL: https://raw.githubusercontent.com/espressif/arduino-
esp32/gh-pages/package_esp32_dev_index.json.
2. Then, navigate to Tools > Board > Boards Manager..., type esp32 in the search box, select
the latest version of **esp32**, and install it.
3. Finally, select the board by navigating to Tools > Board > ESP32 Arduino and selecting XIAO_
ESP32C3. The list of boards is a little long and you will need to scroll to the bottom to find it.
310 Project #6 – Tracking and Notifying about Your Heart Rate
It’s time to install the pulse sensor library. Navigate to Sketch > Include Library > Manage Libraries.
Type pulsesensor playground into the search bar. Only one library will be returned here –
install it.
Now we are ready to proceed to the calibration step. Navigate to File > Examples > PulseSensor
Playground > Getting Started Project. Here, you will get the template code for calibration, to which
we will make the following changes:
// Variables
int PulseSensorPurplePin = A1; // Pulse Sensor PURPLE WIRE
connected to ANALOG PIN 0
int LED = 10; // The on-board Arduino LED
Set the PulseSensorPurplePin variable to A1. Remember to never use a simple 1 as it will
give you different values. Next, assign 10 to the LED variable. After these modifications, upload the
code to the board. To monitor the recorded values in graph format, navigate to Tools > Serial Plotter.
Figure 12.5 shows the Serial Plotter presenting all the values in the form of a graph. The threshold
values are marked by the red box.
Figure 12.5 – Pulse sensor raw-readings graph using the Serial Plotter
Understanding the project architecture 311
Put a finger on the front side of the pulse sensor, which is marked with a white heart shape. Wait for
some time for the readings to stabilize on the Serial Plotter. After a few seconds, you should see stable
readings as shown in the preceding figure. Mark the lowest level as the threshold. In my case, I take
3500 as the threshold value to avoid noise.
After that, download the PulseSensor_BPM_Alternative code from the GitHub repository
under Chapter 12. This is some code modified by us that we’ll use to display the BPM. But before
uploading the code to the board, modify the values as follows:
Assign A1 to the PULSE_INPUT variable, 10 to PULSE_BLINK, and set the THRESHOLD value
according to your stabilized reading taken from the Serial Plotter. As stated, I am using 3500 from
my graph. Upload the code to the board and observe the BPM readings in the Serial Monitor. Place
a finger on the top of the sensor and you will get different BPM readings. Figure 12.6 demonstrates
what this should look like:
The preceding figure shows random BPM values, and when we put a finger on the sensor, it detects 96
and 100 BPM. You can play with the sensor and verify the readings with any professional smartwatch.
Next, we need to set up a Thing, some code, and a dashboard in the Arduino IoT Cloud to prepare
our IoT project.
Figure 12.7 – Tracking and notifying about your heart rate Thing setup
Setting up a Thing, network credentials, cloud variables, and code 313
Set up a new Thing with the name Tracking and notifying about your heart rate.
Then, proceed to the following sections of this chapter, which will take us through the following steps to
create the variables, associate the device, set up the network configuration, and finally, apply the code:
1. Firstly, we need to set up one cloud variable for BPM. The complete details regarding cloud
variables are available in the following Cloud variables section.
2. After that, we need to associate the device with the Thing. In our current project, we are using
the XIAO ESP32C3, so the wizard will be different from that for Arduino boards. The complete
details are available in the Device association section.
3. Next, we need to set up the network configuration for the device, but this time, we need to
provide a security key for ESP-series boards to make the connection secure (whereas Arduino-
compatible boards are configured by the Arduino IoT Cloud automatically during the device
setup wizard).
4. Lastly, we will set up the webhook toward the end of the chapter, along with the notification
service using Zapier.
Cloud variables
The following table outlines the properties that we need to use during cloud variable creation. For
BPM, we could just use the integer data type, but thanks to the Arduino IoT Cloud extended
group of variables, we can choose the specific Heart rate variable type. Next, make sure you use
the same variable declaration as in the table; otherwise, you will need to modify the example code
according to your own naming.
For Permission, while we do have a Read/Write option, I chose Read Only as we only want to receive
data from the device, as opposed to dashboard modification, so Read Only mode will avoid issues in
data consistency. Update Policy is set to On change as the device will send the data whenever there
is any change detected in the BPM value:
In this section, we have created the cloud variable that receives the heart rate value in BPM from the
sensor device. In the next section, we will associate the device with the Thing.
314 Project #6 – Tracking and Notifying about Your Heart Rate
Device association
After variable creation, it’s time to add the device and associate it with the Thing. Before adding
the device, connect the development board to the computer and open the Arduino Create Agent
application. Figure 12.8 shows the device setup wizard where we have selected ESP32 and then
XIAO_ESP32C3 from the dropdown:
1. Click on the Select Device button under the Associated Devices section on the Thing page. A
popup will appear showing all the devices that are already available. If you have already added
your XIAO ESP32C3, select it. Otherwise, click on SET UP NEW DEVICE.
2. Next, click on the Third Party device option. Select ESP32 and XIAO_ESP32C3 from the
dropdown and click on the CONTINUE button.
3. Fill in the Device Name field and click on the Next button.
4. On the final wizard screen, the Device ID and Secret Key values will be displayed. Copy the
Secret Key value to a safe place as it will be needed later during the network configuration.
In this section, we associated the XIAO ESP32C3 device with the Thing. The device association
process is somewhat different to adding the Arduino MKR1010 to a Thing. Next, let’s complete the
network settings.
Setting up a Thing, network credentials, cloud variables, and code 315
Network
After associating the device with the Thing, it is time to configure the Wi-Fi settings for device
communication. Fill in the form shown in Figure 12.9 with your Wi-Fi Name and Password values.
The last field here is the Secret Key field. Paste the secret key value in here that we received from the
system during device creation.
Figure 12.9 shows how it should look once you’ve entered all the relevant values. In the next subsection,
we will cover the coding for the device.
316 Project #6 – Tracking and Notifying about Your Heart Rate
Coding
The code for this chapter is available in the book’s official GitHub repository. Download the Tracking_
and_notifying_Your_Heart_Rate_mar31a code from the repository and import it to the
Arduino Web Editor.
You can download the code and add it to your Thing by navigating to the Sketch tab. We will not
discuss the code at length as you will get the gist after reading the code yourself, but I will explain the
main workflow with which we initialize all the variables and constants in the setup.
Remember to never use the delay method as it will create blocking in the ArduinoCloud.
update() method. But before moving on to the code, we need to set the PULSE_INPUT variable to
pin A1, PULSE_BLINK to digital pin 10 for the LED, and set THRESHOLD with your calibration value:
After configuring the preceding variables with the appropriate values, it’s time to explore the loop method:
if (pulseSensor.sawNewSample()) {
if (--samplesUntilReport == (byte) 0) {
samplesUntilReport = SAMPLES_PER_SERIAL_SAMPLE;
//pulseSensor.outputSample();
if (pulseSensor.sawStartOfBeat()) {
bPM=pulseSensor.getBeatsPerMinute();
Serial.print(bPM);
Serial.println(" bpm");
}
}
/*******
Here is a good place to add code that could take up
to a millisecond or so to run.
*******/
}
/******
Don't add code here, because it could slow the sampling
from the PulseSensor.
******/
Setting up a dashboard for web and mobile 317
Important note
If you used different naming in the variable declaration, then update the code according to
your naming scheme. It would be better, however, if you followed the steps according to the
book first and then change the cloud variable names later and modify your code respectively.
Never use the delay method, which will create a block for the ArduinoCloud.update()
method, and don’t put code at the end of the loop method, as it will cause a delay in the pulse
sensor readings.
The Arduino IoT Cloud only updates the value on the dashboard whenever the variable value
is changed. For example, if the heart beat is 80 and after 5 minutes it’s still the same, then the
Arduino IoT Cloud will not record the value, so don’t get confused if values do not appear to
change on the graph. Another benefit of this feature is you will not get duplicated data when
you export the content.
In this section, we discussed the code in depth and guided you through the code operation and how
to set the threshold values. In the next section, we are going to set up the dashboard to visualize the
BPM value in different formats for better understanding.
In the preceding figure, we have a BPM reading, and to visualize it, we have used two widgets, Value
and Advanced Chart. The Value widget on the left of the screen shows the real-time BPM values,
while the Advanced Chart widget illustrates the real-time readings as well as historical readings for
proper analysis, just like an ECG machine display. Both widgets are attached to the BPM cloud variable.
The Advanced Chart widget is a new addition to the widgets on offer, and comes with a variety of
features including different chart formats such as line, spline, spline/line area, and bar charts, with
the option to customize the color of the plot. Another big feature is the ability to visualize multiple
cloud variables on the same chart, which is not available in simpler chart widgets. We will use that
feature in upcoming projects for a proper demonstration.
In this section, we briefly discussed some widgets and why these widgets are used in our dashboard.
Next, we will set up the notification service using Zapier, which will send an email/SMS when the
pulse is detected as going above or below our thresholds.
So firstly, we need to understand why we need the Zapier automation platform. In our current project,
we want to send notifications by email/SMS when a specific threshold is met, but the Arduino IoT
Cloud only provides the data visualization, webhooks, and API functionalities. We have two options
to solve this problem. Either we need to develop a custom solution to send notifications by email/SMS
using Arduino webhooks and APIs, or we can use an automation platform such as Zapier or IFTTT,
which will save time and reduce costs compared to the first option.
For this exercise, we will use Zapier, which will receive the data via Arduino webhooks. We will apply
Zapier filters in Zaps to manage the threshold, and when the threshold is crossed, Zapier will send an
email notification about BPM levels. A Zap is a term used in Zapier to describe an automated workflow
that allows you to connect apps and services together, and each Zap can consist of multiple actions.
Before moving onto the main steps, first sign up to zapier.com and use the trial version, as the
Zapier webhooks we are going to use are only available under the Professional plan. The following
screenshot demonstrates the trigger and two actions required to set up our notification functionality:
The steps to create this, which we will work through for the remainder of this section, are as follows:
1. Firstly, we need to set up the webhook trigger, which will provide a URL. This URL should be
inserted into the Thing by clicking on Set Webhook on the Arduino IoT Cloud Thing page.
This trigger will be responsible for receiving the data from the Arduino IoT Cloud.
2. In the second step, we apply the filter on the BPM value, which specifies that if the BPM is
greater than 100 or less than 60, then proceed to the next action; otherwise, the BPM is normal
and there is no need to send a notification.
Finally, we will use the Email by Zapier or Gmail option to send the notification. We add multiple
actions to the Zap. To keep things easy and manageable, we chose to use a simple email notification.
Alternatively, you could also use Twillo to send SMS notifications to recipients.
320 Project #6 – Tracking and Notifying about Your Heart Rate
Previously, we have discussed the different triggers and actions step by step that are required for
notifications to be triggered and sent. The following points will guide you through these steps in Zapier:
1. The preceding screenshot gives a rough idea of how our setup looks in Zapier. To create a new
Zap in Zapier, click the Create button and select New Zap, which will open a new page where
you select the required triggers and actions.
2. Type Webhook in the search bar and select the Webhooks By Zapier option, which is available
under the Professional plan. Click on Event and select Catch Hook, then click Continue. In
the Trigger tab, just leave the empty Pick off a Child Key textbox as is and proceed to the next
step by clicking on the Continue button.
3. In the Test tab, you will get the webhook URL – copy that and navigate to Thing in the Arduino
IoT Cloud, then click on Set Webhook. Insert the URL into the window that pops up, then
hit the Save button.
Come back to Zapier and click the Test Trigger button to verify whether data is arriving or not.
Before you can verify this, the device must be powered on and connected to the internet to send the
values. This might not work on your first try; if not, try again and you should see the data arriving,
which means you are receiving the data successfully from the Arduino Thing. Figure 12.12 shows a
trigger test, demonstrating the values received from the Arduino IoT Cloud pulse monitoring Thing:
The preceding screenshot shows Zapier successfully receiving the data from the Arduino IoT Cloud
Thing. In the red box, we can see bPM and value. The value parameter will be used in the next action.
Click the Continue button and a new Action popup will appear. Here, we need to configure the filter
action where we will set the threshold for our BPM notification, as shown in Figure 12.13:
Type Filter in the search box and select Filter by Zapier. Click on Choose Field… and select
Values Value from the dropdown. Then, click Choose Condition, select Number (Greater than),
and put 100 in the next input field. This sets the upper threshold value to 100 BPM. Next, click OR,
and leave the value field as it is, but in Choose Condition, select Number (Less than) and insert 60
in the next field. Lastly, click on Continue.
Our filter is ready; now, our email notification action is required to finish the setup. We have two
options to send email notifications: either Email by Zapier or Gmail. I opted to use Email by Zapier.
Next, the Action popup window will appear; type Email in the search box and click on Email by
Zapier. Click on Event and select Send Outbound Email. In the next window, set all the parameters
for the email receiver, subject, and body, as shown in the following screenshot:
322 Project #6 – Tracking and Notifying about Your Heart Rate
Only three fields are mandatory here – insert the recipient email in the To field, write a relevant entry
for the Subject field, and insert a message in the Body area. It’s up to you whether you fill the other
fields or leave them blank. If you observe the preceding screenshot, you may notice I added Values
Value to both the Subject and Body fields, which will display the values that triggered the notification
in the email. Click the Continue button at the bottom of the page and test the action – if you receive
the email with the BPM values, then publish the Zap and you are good to go.
In this section, we set up the notification services for our pulse monitor using Zapier. We created a
Zap that consists of three steps. Firstly, we set up the webhook responsible for receiving the data. The
second step deals with the threshold, and the third and final step handles sending the email notification.
What next?
There are many more options available to explore, but these are left to you to work on, using different
health sensors and development boards to do some more experiments and learn from them. In the
current chapter, we only used one sensor that provided only one parameter, but there are many sensors
on the market that provide a wide variety of functionalities including the monitoring of blood sugar,
blood oxygen, blood pressure, body temperature, and more.
Summary 323
Try the following sensors to enhance your practical knowledge and compare this selection with other
sensors in terms of features, ranges, and cost:
Summary
In this chapter, we explored how to develop a low-cost wearable smart heart-rate monitoring system
using the XIAO ESP32C3 and a pulse sensor. One important thing to note was the necessity of
calibrating medical sensors before using them in the field. We set up a Thing, which included cloud
variable creation, device association, network configuration, and coding for our development board.
Later, we created a dashboard to visualize our sensor readings with different widgets to display both
current readings and historical data with the help of graphs. Finally, we used Zapier to set up an
email notification service based on thresholds using webhooks and saw how to employ webhooks to
integrate third-party services with the Arduino IoT Cloud.
In the next chapter, we will learn about scripting in the Arduino IoT Cloud with the Arduino Cloud
CLI (CCLI). This is a command-line tool that provides access to Arduino IoT Cloud services via
terminal commands. We will use the Arduino IoT Cloud CLI to automate bulk operations, including
bulk device creation, which will help us to minimize the time required for operations and maintenance.
13
Scripting the Arduino
IoT Cloud with Cloud CLI
The Arduino Cloud Command-Line Interface (CLI) is an automation tool that is useful for scripting
and creating devices, Things, and dashboards. It also provides the option to perform mass uploads
(OTA), enabling the fleet management of deployed IoT nodes. This chapter will explore the advanced
functionalities of the tool and propose some scenarios for its usage.
The Arduino Cloud CLI is a cross-platform tool that lets you perform bulk management and operations
via the command line, which helps you to increase your productivity, and provides the option to
automate Things via command-line scripts. In this chapter, we will explore all the commands and
observe their context.
By the end of this chapter, you will understand how to interact with the Arduino IoT Cloud platform
via a CLI to create, delete, or extract templates from devices, Things, and dashboards and send OTA
updates to devices via the command line. This chapter will show you how to perform all the operations
via the command line to boost your productivity. The commands you will learn will help you write
custom scripts for use in mass deployments and bulk management operations.
In this chapter, we will cover the following main topics:
Technical requirements
There are no specific hardware requirements for this chapter as we will focus on the Arduino Cloud
CLI and work through different command exercises to perform operations on the Arduino IoT Cloud
platform using a CLI. However, before we proceed, we will need the following software to complete
the different exercises in this chapter:
For the commands, we need the Arduino Cloud CLI and an active Arduino IoT Cloud account. This
chapter only contains commands, so there is no folder for it on GitHub.
Here are some of the benefits of using the Arduino Cloud CLI:
• Automation: The Arduino Cloud CLI can be used to automate tasks that you would otherwise
have to do manually. For example, you could use it to create a script that clones a Thing and
then performs a mass OTA upload to all of the devices that are associated with that Thing.
• Efficient device management: The Arduino Cloud CLI can help you manage a large number of
devices more efficiently. For example, you could use it to list all of the devices that are associated
with a particular tag or to get the status of a particular device.
Securing access – unveiling API keys and authentication 327
• Access to advanced features: The Arduino Cloud CLI can be used to access features of the
Arduino IoT Cloud that are not available in a web interface. For example, you could use it to
create a script that checks the status of a device every minute and then sends an email alert if
the status changes.
• Customization: Being open source, users have the flexibility to customize the Arduino Cloud
CLI to suit their specific needs and integrate it into their workflows.
• Active development and community support: The tool is actively developed, meaning it
continually receives updates, new features, and bug fixes. Additionally, the presence of a large
community can provide assistance and support for users.
• Time and effort savings: The Arduino Cloud CLI can save time and effort in managing IoT
projects, making it a valuable resource for developers working with Arduino devices.
Overall, the Arduino Cloud CLI is a powerful tool that can be used to automate tasks, manage a large
number of devices, and access features of the Arduino IoT Cloud that are not available in a web interface.
In this section, we have discussed what the Arduino Cloud CLI is and what the benefits of the Arduino
Cloud CLI are. In the next section, we will explore how to set up API keys and how to use API keys
to authenticate the Arduino Cloud CLI with the Arduino IoT Cloud.
Copy the Client ID and Client Secret values by clicking on the copy icons – never try to copy by
manual selection, as the client secret is very long, so clicking on the copy icon is the best option.
Save both the Client ID and Client Secret values in a secure location, and then click the checkbox,
confirming that you have saved your keys. Lastly, click on DONE, and you will see your API key in
the panel – it’s now ready for use.
Important note
A single API key is used to give access to all the Things and their variables. Having access to
all the infrastructure with just one API key is handy, instead of having to create separate API
keys for each Thing, but you must take care of your key! This is a big security risk as, if you
were to lose the key, a hacker could gain access to your whole account.
In this section, we created API authentication keys, which consist of a client ID and a client secret.
This section is most important, as without these keys, we can’t execute any command via the Arduino
Cloud CLI. In the following section, we will install the Arduino Cloud CLI.
Installing the Arduino Cloud CLI 329
arduino-cloud-cli
Then, you will see the following output on your terminal (Figure 13.2).
This simply shows you how to use the Arduino Cloud CLI with different parameters, as we didn’t
specify any parameters during the command execution.
330 Scripting the Arduino IoT Cloud with Cloud CLI
Now, it’s time to initiate the Arduino Cloud CLI authentication with Arduino Cloud, using the API
keys that we generated in the previous section. Type the following command into the terminal:
After executing the preceding command, you will be asked for your client ID and client secret,
respectively. Finally, you will be asked for your organization ID, which is not mandatory, and you can
leave this empty, as shown in Figure 13.3.
Figure 13.3 – The Arduino Cloud CLI authentication process with Arduino Cloud
After successful authentication, you will see a success message on the terminal, as shown in Figure 13.3.
Congratulations! You are now ready to execute the commands on the terminal and able to perform
operations on the Arduino IoT Cloud via commands.
In this section, we downloaded the arduino-cloud-cli file and installed it on our operating
system, and we also initialized the authentication process for the arduino-cloud-cli tool with
the Arduino IoT Cloud. In the next section, we will start playing with devices using the command line.
Creating a device
Firstly, we will start by creating a device. The documentation on device creation can be found at
https://docs.arduino.cc/arduino-cloud/getting-started/arduino-cloud-
cli#device. Before you execute the command, connect your development board to your computer
and find out the port number and FQBN for your device from the documentation page. The following
is the syntax of the device create command:
I attached the MKR Wi-Fi 1010 to my computer, which is available on port /dev/cu.usbmodem101,
and its FQBN is arduino:samd:mkrwifi1010. Therefore, the following will be my command:
After executing the preceding command, you will get the following output, which shows the device
has been successfully created (Figure 13.4).
After creating the device, the terminal will show the device name, ID, board, serial number, and FQBN.
Just imagine how easy it would be to attach dozens of development boards to the Arduino IoT Cloud
using the command line, compared to a graphical user interface. The Arduino Cloud CLI is also able
to create LoRaWAN devices as well as ESP32/ESP8266 devices via the CLI.
In this subsection, we created a device in the Arduino IoT Cloud using the command line. In the
following subsection, we will explore how to list the device.
Listing devices
In this section, we will list all the devices. Listing devices means displaying all the devices with their
properties. The documentation on listing devices is available at https://docs.arduino.cc/
arduino-cloud/getting-started/arduino-cloud-cli#list-devices. The
following is a very simple command to list all the devices:
After executing the preceding command, we will see a complete list of devices, as shown in the
following figure.
In the output, we can see the device name, ID, board, FQBN, serial number, and tags. Here, the ID
is very important, as it will be used in the following commands for device deletion, as well as for
tag creation and deletion. In this subsection, we have seen how to list the devices, and in the next
subsection, we will explore how to delete a device using its ID.
Deleting a device
In this section, we will explore how we can delete a device using the device ID. The documentation for
deleting devices is available at https://docs.arduino.cc/arduino-cloud/getting-
started/arduino-cloud-cli#delete-a-device. The following is the command syntax
for device deletion:
According to the preceding command syntax, we need a device ID for deletion. You can retrieve the
device ID by using the device list command:
After successfully deleting the device, you will not see any error message; otherwise, you will see a
401 error on the screen.
Figure 13.6 shows the completed command for device deletion, and there is no error on the screen,
which means the device has been deleted successfully. In this subsection, we discussed the delete
command. In the upcoming subsection, we will tag and untag a device.
Interacting with devices 333
You might ask the question, why do we need a tag for a device? Let’s say you have a generic product
for warehouse monitoring, and you have deployed this product in different organizations and different
rooms. Now, the issue is that it’s very difficult to assign the organization name and location in the
Device Name field. So, an optimal solution is tagging. You can use tags as many times as you want.
A tag has two options – one is a key and the other is a value.
In the following example, we will attach two tags – one for the organization name and another for the
location. Pick a device ID by using the device list command to attach the tags. The following
is the command to attach tags to a device:
According to the following command syntax, we need a device ID to remove the tag from the device.
You can fetch the device ID by using the device list command. The following command is used
to remove the tag from the device:
Here, the command is a little different, as we have used delete-tags and -k to specify the tag
key. If you want to remove multiple tags, then use a comma to separate the keys.
In this and the preceding subsections, we performed various operations on devices using commands,
including ones for device creation, listing devices, device deletion, tagging, and untagging. In the next
section, we will explore how to practically perform operations on Things.
334 Scripting the Arduino IoT Cloud with Cloud CLI
For the Thing ID, either visit the Arduino IoT Cloud to find it or refer to the upcoming subsections,
in which we will show you how to list Things, which provides the Thing name, ID, and so on, so you
can also retrieve the Thing ID from the output. Now, we will assign the format; we want the template
output in JSON format, so I used JSON here:
After executing the command, we will get the template output on the screen in JSON format, as
shown in Figure 13.7.
Interacting with devices 335
Our Thing template shows all the information regarding cloud variables. Copy the text and save it in
a file, which will be used in the following section for Thing creation.
Creating a Thing
After extracting the Thing template, we will now start to create the Thing. The documentation on
Thing creation can be found at https://docs.arduino.cc/arduino-cloud/getting-
started/arduino-cloud-cli#create-things. The following is the syntax of the Thing
creation command, which takes two parameters. Firstly, it will take the name, and secondly, it will
take the template filename for the Thing creation, which contains the Thing template in JSON format
that we saved in the previous section:
Here, I have provided a Thing name, EnvSense101, and in the previous section, I saved the JSON
template in the file named EnvSenseTemplate.json. Then, we provide the name with the -n
parameter and the template file with the -t parameter:
After executing the preceding command, you will get the following output for successful Thing
creation (Figure 13.8).
After creating the Thing, the terminal will show the Thing name, ID, device ID (which is empty right
now, but in the upcoming sections, we will associate the device with this Thing), and variable name.
In this subsection, we created a Thing in the Arduino IoT Cloud using the command line. In the
following section, we will explore how to clone the Thing for bulk creations.
Cloning a Thing
After creating a Thing from a template, we will now explore how we can use the clone operation for
large-scale deployments. The documentation on the Thing clone can be found at https://docs.
arduino.cc/arduino-cloud/getting-started/arduino-cloud-cli#clone-
things. The following is the syntax of the thing clone command, which will take two parameters.
Firstly, it will take a name, and secondly, it will take a Thing ID:
Here, I have provided a Thing name, EnvSense102, and in the previous section, we created the
Thing, so I can get its ID from the terminal, as shown in Figure 13.8 (use your own Thing ID in the
command line). Then, provide the name with an -n parameter and the Thing ID with a -c parameter:
After executing the preceding command, you will get the following output for a successful Thing
clone (Figure 13.9).
This is the output of a successful Thing clone by the Arduino Cloud CLI. After cloning the Thing, the
terminal will show the Thing name, ID, device ID (which is empty right now, but in the upcoming
section, we will associate the device with this Thing), and variable name. You can see how easy it is
to create hundreds of Things with just the clone command. Here, you can just create a batch script,
which will only change the name of the Thing by using the for loop and create hundreds of Things
in just a few minutes.
In this subsection, we learned how to clone a Thing in the Arduino IoT Cloud using the command
line. In the following section, we will explore how to list Things.
Listing Things
In this section, we will list all the Things. The documentation on listing Things is available at https://
docs.arduino.cc/arduino-cloud/getting-started/arduino-cloud-cli#list-
things. The following is a very simple command to list all the Things:
After executing the preceding command, we will see a complete list of Things, as shown in the
following figure.
In the output, we can see the Thing name, ID, device, and tags. Again, the ID is very important, as it
will be used in the following commands for Thing deletion, as well as for tag creation and deletion.
In the preceding sections, we also used the ID for Thing template extraction and creation, as well as
Thing cloning.
338 Scripting the Arduino IoT Cloud with Cloud CLI
The Arduino Cloud CLI also provides different parameters to get more detailed output on the terminal,
such as a variable list along with a list of Things. We can attach the -s parameter to the Thing, and
we can also list a Thing by providing a device ID as well as list a series of Things by providing a Thing
ID. Here, I want to explore how we can get a variable list along with Things. The following is a simple
command to list cloud variables:
After executing the preceding command, you will see the output shown in Figure 13.11.
Here, you can see all the cloud variables along with the Thing names, but it looks a little bit complicated.
Now, we will try to list a single Thing with cloud variables. The following is the command syntax to list
a Thing with cloud variables. It will take two parameters as input – one Thing ID and an -s parameter:
Execute the preceding command, and you will see the complete and readable output shown in
Figure 13.12.
Now, it’s time to explore how we can find a Thing by using a device ID. The following is a simple
command to retrieve a Thing based on a device ID:
After executing the preceding command, we will get specific Thing data using the device ID, as well
as its cloud variables, as we used the -s parameter in the command (as shown in Figure 13.13).
Figure 13.13 – Displaying a single Thing based on a device ID, with cloud variables
In this subsection, we explored how to list Things by using different parameters. In the next subsection,
we will explore how to delete a Thing.
Deleting a Thing
In this section, we will explore how to delete a Thing using a Thing ID. The documentation for deleting
a Thing is available at https://docs.arduino.cc/arduino-cloud/getting-started/
arduino-cloud-cli#delete-things. The following is the command syntax for Thing deletion:
According to the command syntax, we need a Thing ID for deletion. You can fetch the Thing ID by
using the thing list command:
After the successful deletion of the device, you will not see an error message; otherwise, you will get
a 401 error message on the screen.
Figure 13.14 shows the complete command for Thing deletion, and there is no error on the screen,
which means the Thing has been deleted successfully. In this subsection, we discussed the delete
command, and in the upcoming subsection, we will explore how to associate the device with a Thing.
340 Scripting the Arduino IoT Cloud with Cloud CLI
Here, you can get a specific device ID by using the arduino-cloud-cli device list
command and a Thing ID with arduino-cloud-cli thing list:
In the preceding command, we have assigned a Thing ID by using -i and a device ID with the -d
parameter. Execute the preceding command, and you will see the output shown in Figure 13.15.
Figure 13.15 shows a device successfully binding with a Thing. To confirm, we used the thing
list command with the -i parameter to verify the device ID. In both the command as well as in
the thing list output, the device ID is the same.
In this subsection, we explored how to bind/associate a device with a Thing. In the next subsection,
we will discuss how to assign and remove tags from a Thing.
is available at https://docs.arduino.cc/arduino-cloud/getting-started/
arduino-cloud-cli#untag-a-thing. The following is the command syntax to tag a Thing:
You might question the necessity of assigning a tag to a Thing. Consider this scenario. You have a
versatile product designed for monitoring warehouses, and you’ve deployed this product in various
organizations and different rooms within those organizations. The challenge arises when attempting
to incorporate the organization’s name and location directly into the Device Name field, which can
be quite cumbersome. In this context, a more efficient solution presents itself through the use of tags.
Tags can be applied without limitations, much like when we previously established tags for devices.
Each tag consists of two components: a key and a corresponding value.
So, in the following example, we will attach two tags – one for the organization name and another for
the location. Pick the Thing ID by using the thing list command to attach tags. The following
is the command to attach tags to a Thing:
After executing the preceding command, you can verify the tags by using the thing list command,
as shown in Figure 13.16.
Figure 13.16 shows the full command that is used to assign tags to a Thing, and it also clearly shows
the thing list command we used to verify the tags.
Now, it’s time to explore how we can remove a tag from a Thing. Previously, we saw the syntax to
untag a tag from a Thing. The following is the complete command that will remove the location tag
from a specific Thing:
After executing the preceding command, you can verify the tags by using the thing list command,
as shown in Figure 13.17.
Figure 13.17 shows the full command that is used to delete a tag from a Thing, and it also clearly shows
the thing list command we used to verify the tags.
Here, the command is a little different, as we have used delete-tags and -k to specify the tag key.
If you want to remove multiple tags, then use a comma to separate the keys. In the following section,
we will explore how to work with dashboards using the Arduino Cloud CLI.
For the dashboard ID, either visit the Arduino IoT Cloud to find it or refer to the upcoming subsections,
in which we will show you how to list dashboards, which will provide their name, ID, and so on. Now,
we will assign the format; we want the template output in JSON format, so I used JSON here:
After executing the command, we will get the template output on the screen in JSON format, as
shown in Figure 13.18.
Figure 13.18 shows partial output on the screen. We have our dashboard template in JSON format,
which shows all the information regarding widgets and their configuration, including thing_id
and variable_id. Copy the JSON format output and save it in a file, which will be used in the
following section for dashboard creation.
Important note
There is a bug in the Arduino Cloud CLI for dashboard extraction, as it shows the Thing
name instead of the Thing ID in the thing_id value. Therefore, you need to replace the
text with the Thing ID; otherwise, an error will occur during the execution of the dashboard
creation command.
In this subsection, we explored how to extract a template from an existing dashboard. In the following
subsection, we will explore how to list dashboards.
Listing dashboards
In this section, we will list all the dashboards. The documentation on listing dashboards is available at
https://docs.arduino.cc/arduino-cloud/getting-started/arduino-cloud-
cli#list-dashboards. The following is a very simple command to list all the dashboards:
After executing the preceding command, we will see a complete list of dashboards, as shown in the
following figure.
In the output shown in Figure 13.19, we can see the dashboard Name, ID, and UpdatedAt details.
Here, ID is very important, as it will be used in the following commands for dashboard deletion.
It also helps you in dashboard template extraction, as we used the dashboard ID in the preceding
subsection to extract the template.
In this subsection, we explored how to list dashboards by using a very simple command. In the next
subsection, we will explore how to delete a dashboard using the dashboard ID.
Crafting dashboards – unleashing potential via the command line 345
Deleting a dashboard
In this subsection, we will explore how to delete a dashboard using the dashboard ID. The documentation
for deleting dashboards is available at https://docs.arduino.cc/arduino-cloud/
getting-started/arduino-cloud-cli#delete-dashboards. The following is the
command syntax for dashboard deletion:
According to the preceding command syntax, we need to provide a dashboard ID for deletion. You
can fetch the dashboard ID by using the dashboard list command:
After the successful deletion of the device, you will not see an error message; otherwise, you will get
a 401 error message on the screen.
Figure 13.20 shows the complete command for dashboard deletion, and there is no error on the screen,
which means the dashboard has been deleted successfully. In this subsection, we discussed the delete
command. In the upcoming subsection, we will explore how to create a dashboard using a template,
which we extracted in the first subsection of this section.
Creating a dashboard
After extracting a dashboard template, we can start to create a dashboard. The documentation
on dashboard creation can be found at https://docs.arduino.cc/arduino-cloud/
getting-started/arduino-cloud-cli#create-dashboard. The following is the
syntax of the dashboard creation command, which takes two parameters. Firstly, it takes the name of
the dashboard, and secondly, it takes the template filename for dashboard creation, which contains
the dashboard template in JSON format that we saved in the previous section:
Here, I have provided the Thing name, EnvSense101, and in the previous section, I saved the
JSON template in a file named EnvSenseTemplate.json. Then, we provide the name with the
-n parameter and the template file with the -t parameter:
After executing the preceding command, you will get the following output for successful dashboard
creation (Figure 13.21):
Figure 13.21 shows the command and the output of successful dashboard creation by the Arduino
Cloud CLI. After creating the dashboard, the terminal shows the dashboard name, id, updated_at,
and widgets details.
Important note
There is a bug in the Arduino Cloud CLI for dashboard extraction, as it shows the Thing
name instead of the Thing ID in the thing_id value. Therefore, you need to replace the
text with the Thing ID; otherwise, an error will occur during the execution of the dashboard
creation command.
In this subsection, we created a dashboard in the Arduino IoT Cloud using the command line. In the
following section, we will explore how OTA updates work via a CLI.
OTA management
In Chapter 11, we explored what OTA is and how we can easily use this feature to send updates to
remote devices. In that chapter, we used a graphical user interface, which is a good option for a single
device. However, when we have bulk Things to send OTA, then the situation becomes complex, as we
need to go through different things one at a time to send OTA updates, which is very time consuming
and a difficult operation at the enterprise level.
OTA management 347
That’s why the Arduino team created commands for the Arduino Cloud CLI to send OTA updates to
single or multiple devices automatically, to minimize the complexity and operation time. So, firstly,
we will explore how to export the compiled binary by using the Arduino IDE, and then we will send
an OTA update to a device using its ID. For official documentation and updates, visit https://
docs.arduino.cc/arduino-cloud/getting-started/arduino-cloud-cli#ota-
over-the-air.
Clicking on Export Compiled Binary will generate the build directory under your sketch
directory, where you will find lots of files generated by the Arduino compiler. You need to select the
file that ends with the ino.bin extension, as shown in Figure 13.23.
In this section, we explored how to generate the build files of a sketch using the Arduino IDE. In the
next subsection, we will send this build file to a device OTA via the command line.
Here, we need to specify the device ID and the filename, including its path, which is done with the
following command:
After the successful execution of the command, you will see an empty terminal without any errors, as
shown in Figure 13.24. However, if the device is unavailable or any other issue arises, then the details
will be printed on the terminal.
Figure 13.24 shows that our upload has been completed successfully without any errors. It will take
some time on the terminal to upload the file, depending on your internet speed as well as your sketch
size, but you need to wait till the final output. Never interrupt the upload procedure.
Then, we have the mass deployment option in OTA, where you can upload firmware to multiple
devices by using FQBN, as well as tags. The following is a simple command for mass deployment that
uses FQBN, and you can also assign specific device IDs:
However, with this specific command, I will only use fqbn to send the update to all the same device types:
You can also explore the OTA mass upload by adding tags, to send an update to specific groups of
devices. In this section, we explored how to build binaries of a sketch using the Arduino IDE and how
to upload an update using the OTA command.
What next?
After playing around with some commands, it’s now time to do some more experiments so that
you can apply your learning to new scenarios and learn new stuff. We explored the complete list of
commands available on the Arduino Cloud CLI. However, you can check out Arduino’s official page
for the latest updates and news to keep yourself up to date with the latest features. Now, it’s your turn
to create batch scripts using the Arduino Cloud CLI to automate your operations, such as bulk device
addition in the Arduino IoT Cloud, bulk Thing creation using templates, binding devices with Things,
and creating a dashboard for every Thing from dashboard templates.
Summary
In this chapter, we covered all the types of commands that are officially available to us on the Arduino
Cloud CLI. Firstly, we explored device-related commands, which include device creation, listing
devices, deletion, tagging, and untagging. Then, we explored how to work with Things; in that section,
we started with template extraction and then created a Thing using a template. We also explored how
to clone a Thing, how to bind a device with a Thing, and so on. In the penultimate section, we played
around with dashboard commands, and in the last section, we explored how OTA commands can
benefit us by sending updates to devices via the command line in different ways.
This chapter was specially designed for backend developers and administrators who want to use the
Arduino Cloud CLI to optimize their daily tasks, by using terminal commands instead of a graphical
user interface. This chapter will have helped them interact with the Arduino IoT Cloud using a CLI.
It will also have helped them to create custom scripts, automating their daily tasks.
The following chapter is the last chapter of this book, and in this chapter, we will explore different
Arduino IoT Cloud plans for educational and enterprise organizations. We will also explore industrial
IoT hardware devices and different types of Arduino IoT Cloud services that are especially available to
enterprise organizations. This chapter will give you a complete overview of how to scale your product
from a smaller scale to an enterprise level.
14
Moving Ahead in the Arduino
IoT Cloud
The Arduino IoT Cloud offers various plans, with different features for each plan enabled to certain
levels. In the chapter, you will be guided through the different options available at the time of writing,
including the enterprise plans, and a description of the additional functionalities they provide.
Then, you will be invited to put into practice what was learned in previous chapters by implementing
and expanding the examples with further functionalities. The Arduino IoT Cloud is a live product,
always evolving, and this chapter will list official Arduino sources of information, allowing you to
monitor any updates and future releases.
You will also get an insight into the Arduino PRO hardware and software tools, which are specially
designed for industrial IoT solutions. This information will help you to design and build professional
solutions for your industry.
In this chapter, we will cover the following main topics:
The Arduino IoT Cloud team divided the pricing plans according to different categories and users,
and pricing varies from category to category. There are also different pricing plans available in those
categories. For the updated pricing plans and features, visit https://cloud.arduino.cc/
plans/.
We will discuss all the categories step by step in the following subsections, and the business plan will
be discussed in a separate section. Firstly, we will look at plans for individuals in the next subsection.
In Table 14.1, we compare different plans with respect to some important features. Firstly, we will
explore the free plan, which only allows you to create two Things. One-day data retention is available,
and you can create up to five cloud variables for your Thing. However, cloud triggers, API access, a
shareable dashboard, and (OTA) features are not available. The free plan is good from a learning point
of view, and you can even host up to two personal IoT devices.
Then, we have the entry plan, which is perfect for students and hobbyists if they want to expand their
IoT devices on a smaller scale. This plan will cost them USD 23.88 per year and is only available in
yearly billing, not monthly. In this plan, you will get 10 Things and 15-day data retention, with up
to 10 cloud variables for each Thing. Users will also get the benefit of the API and OTA features, but
cloud triggers and shareable dashboard features are still not available.
The maker plan is the third plan in this category, which is good for users who design and develop IoT
solutions and want to taste all the features of the Arduino IoT Cloud. It costs USD 71.88 per year and
can be paid on a monthly basis. With this plan, users are able to create 25 Things, and 90-day data
retention is allowed (which is a very good option for data recording). Also, users are allowed to set
up cloud triggers for 100 notifications per day, and 10 API requests per second are allowed.
Finally, we have the maker plus plan, which is the perfect choice for IoT freelancers or small-scale IoT
start-ups. In this plan, users are allowed to host up to 100 Things with one-year data retention, which
is a perfectly good combination for professional, small-scale deployments, and they only need to pay
USD 239.98 per year or USD 23.99 per month. You can see all the features of the Maker Plus plan, as
well as the aforementioned plans, in Table 4.1 or on the official website.
Machine learning tools are available to all plans equally, so anyone can enjoy the benefit of this feature
and integrate machine learning into their IoT solutions, making them more advanced. This offers the
benefit of powerful machine learning on the cloud side without any hassle.
Let’s explore the maker plus plan with respect to its cost for freelancers and small IoT start-ups. This
plan costs USD 239.98 per year and allows you to host up to 100 IoT Things. If we calculate the cost
per Thing, then it will be around USD 2.40 per Thing for one year, which is very reasonably priced,
and there is also zero cost for infrastructure and security maintenance, as all these requirements are
managed by the Arduino IoT Cloud team.
In this subsection, we discussed the different Arduino Cloud plans that are available for individuals
in detail. In the upcoming subsection, we will explore the plans for educational institutes.
Besides their special pricing plan, the Arduino IoT Cloud also provides a free plan for students,
similar to the free plan for individuals. Therefore, we will not discuss this and focus instead on the
customized school plan. In the school plan category, the pricing changes according to the number of
students, but the features available to them all remain the same. Table 14.2 provides a detailed pricing
plan according to the number of students. For updated pricing for schools, visit https://cloud.
arduino.cc/plans.
Table 14.2 – The pricing plan for schools according to the number of students
Table 14.2 states the pricing according to student numbers and per member. Let’s explore what features
they provide to every school member. In the school plan, every member can create up to 5 Things,
with unlimited cloud variables and six-month data retention, which is very good, especially for PhD
and master’s students, as they may want to collect data from IoT devices for further research and
experiments, or are building a prototype to solve a real-world problem. Also, the plan provides 10
notifications per day for cloud triggers and 10 requests per second for APIs.
The Arduino IoT Cloud school plan can also natively integrate with Google Classroom users. This
makes it easy for faculty members to manage their students, assignments, and lots of other stuff in the
Arduino IoT Cloud via Google Classroom. The Arduino IoT Cloud also provides centralized billing
and user management that is General Data Protection Regulation (GDPR)-compliant.
There is another offer available to students via GitHub Education – the Student Developer Pack.
Students can visit the official GitHub page for further updates and news: https://education.
github.com/pack#offers. According to the current agreement between Arduino and GitHub,
Arduino provides six free months of the Arduino IoT Cloud maker plan, as well as a discount on
selected development boards.
In this subsection, we dived deep into educational pricing plans and their features for each student.
In the following section, we will explore the Enterprise Base Plan in detail, which helps you to scale
your product with enterprise-level features.
The enterprise base plan is specially designed for organizations that are interested in using the Arduino
IoT Cloud as a main infrastructure for their solution deployment and management. In regard to pricing
and devices, the plan starts from USD 42 for 50 devices, increasing in multiples of 50 up to 500. If
you have more than 500 devices, then you would need to directly contact the Arduino Support team
for a customized pricing plan. Fifty devices cost USD 500 per year, and each device costs USD 10 per
year and approximately USD 0.83 per month. This cost per device is very nominal, as you don’t need
to pay any infrastructure or development charges, security costs, and so on. This plan also provides
you with advanced management control, which will make your management and operations easier
compared to other plans.
Data retention in the enterprise plan is one year for all devices, and every device is allowed to send
20 notifications via cloud triggers and 10 requests per second for APIs. Besides all of these features,
organizations will receive technical support via a ticketing system, which is not available in other plans.
In this subsection, we discussed the basic features of the enterprise base plan. Now, we will explore
role-based access control and fleet management in the upcoming subsection.
At the enterprise level, there are several employees in an organization who manage and perform different
operations. It’s mandatory for an organization to assign different access levels to their employees
according to their responsibilities. To aid this, the Arduino IoT Cloud has a role-based access control
system for organizations, where they can easily assign their employees access and manage it according
to their job description.
Role-based access control ensures the safety and security of your devices and protects them from
human mistakes and errors. With the help of role-based access control, you can share access among
teams for project collaboration and assign device access to members at different levels, according to
their management responsibility.
Another feature of the Arduino IoT Cloud enterprise base plan is fleet management. The Arduino
IoT Cloud introduced this feature to manage a large number of devices effectively and easily. Fleet
management contains a device filtering and grouping feature, bulk OTA updates, hierarchies, and
many other features.
In this subsection, we discussed role-based access control and fleet management for devices. In the
following subsection, we will explore machine learning tools and the Portenta X8 Manager.
With the rapid growth of AI and machine learning, it’s now become vital for IoT solutions to integrate
machine learning into their solutions so that customers can benefit from its power to improve their
operations, such as predictive maintenance, anomaly detection, and quality control.
356 Moving Ahead in the Arduino IoT Cloud
The Arduino team collaborated with Edge Impulse to provide machine learning integration in the
Arduino IoT Cloud. In Edge Impulse, you can train models using devices’ data, by importing them
into Edge Impulse or directly connecting the devices, such as Arduino Nano 33 BLE Sense, Arduino
Nicla Vision, Arduino Portenta H7, or any Linux-supported device. This feature helps developers and
solution providers to train a model using a graphical user interface, with the help of a small amount
of code.
Then, you can deploy these models, using TinyML, to Arduino-supported development boards. For
further details, please visit https://cloud.arduino.cc/machine-learning-tools/.
In the enterprise base plan, Arduino charges USD 500 per month for machine learning services, which
include 60 minutes per job and a total of 1,000 minutes per month.
The Portenta X8 Manager is a specialized extension integrated with the Arduino IoT Cloud, designed
to empower users in safeguarding and managing their Portenta X8 Linux distribution. It facilitates
essential functionalities such as secure maintenance, containerized application deployment, and
secure OTA differential updates.
The Portenta X8 Manager is designed for businesses and organizations that need to deploy and manage
large fleets of Portenta X8 devices securely and reliably. It provides a number of features that make it
ideal for enterprise use, including the following:
• Secure OTA updates: The Portenta X8 Manager uses a secure OTA update process to ensure
that devices are always up to date with the latest firmware and security patches.
• Containerized applications: The Portenta X8 Manager allows users to deploy and manage
containerized applications on their devices. This makes it easy to deploy and update complex
applications without having to reprogram the entire device.
• Role-based access control (RBAC): The Portenta X8 Manager supports RBAC so that
organizations can control who has access to their devices and applications.
• Audit logging: The Portenta X8 Manager provides audit logging so that organizations can
track all activity on their devices and applications.
The Portenta X8 Manager is available as a paid add-on to the Arduino IoT Cloud enterprise base
plan, which costs USD 250 per month. For more details, refer to the Enterprise Base Plan tab on the
Arduino IoT Cloud plans page under the For business tab.
In this subsection, we dived deep into machine learning and the Portenta X8 Manager add-on for
the Arduino IoT Cloud enterprise base plan. In the following section, we will cover Arduino PRO
hardware and software tools in detail.
Arduino PRO 357
Arduino PRO
Arduino PRO is a separate line of products that contain professional tools in both the hardware and
software categories. These tools are specially designed to carry out industrial operations, such as those
found in aviation, industry 4.0, healthcare, robotics, smart cities, and smart homes/offices. We will
explore both the hardware and software tools step by step in the following subsections.
The Arduino Portenta family is a series of high-performance industry-rated boards. These boards
are designed to enable simultaneous execution of high-level code, such as protocol stacks, machine
learning, or even interpreted languages such as MicroPython or JavaScript, along with low-level, real-
time tasks. The Portenta family adds two 80-pin high-density connectors at the bottom of the board,
ensuring scalability for a wide range of applications. Figure 14.2 shows all the series of development
boards from the Portenta family. All the details of these boards will be discussed step by step in the
following paragraphs.
A few of the development boards available in the Arduino Portenta family are shown in Figure 14.2,
and the following list details some of these boards:
Note that these are just a few examples from the Arduino Portenta family. You can find more
information about these boards and other related products at https://store.arduino.cc/
collections/portenta-family.
In this subsection, we explored the Portenta Series, which is specially designed for industrial use cases
and also supports different programming languages, including MicroPython and JavaScript. It also
gives you the option to perform concurrent operations in parallel. In the following subsection, we
will explore the Nicla family, which is specially designed for voice and vision.
The Arduino Nicla family is a series of industrial-oriented boards designed for low-power AI, machine
learning, and machine vision applications. These boards are fully equipped with industrial-grade
sensors and are designed to work as autonomous, battery-operated systems. Figure 14.3 shows Nicla
Vision, but you can visit the official website to see other variants from the Nicla family.
Arduino PRO 359
Here are some of the boards available in the Arduino Nicla family:
• Nicla Voice: Arduino PRO’s smallest form factor board to date. It can be used to upgrade or
retrofit existing machines and systems. It is particularly suitable for wearable products, such
as helmets and smart bands, due to its long battery-powered autonomy.
• Nicla Vision: A square-shaped board, with a 2 Mega Pixel color camera sensor and other
built-in devices to collect various environmental data. It is suitable for machine-vision-based
applications at the edge.
Note that these are just a few examples from the Arduino Nicla family. You can find more information
about these boards and other related products at https://www.arduino.cc/pro/hardware-
nicla-family.
In this subsection, we discussed Nicla Voice and Nicla Vision, and both these development boards
are specially designed for industrial use cases where voice and vision are mandatory requirements
to control the machine process, such as logistics and loading and unloading robots. In the following
subsection, we will discuss the latest product from Arduino, which is Opta PLC.
360 Moving Ahead in the Arduino IoT Cloud
Opta PLC
The Arduino Opta is a secure, easy-to-use micro PLC with industrial IoT capabilities, designed in
partnership with Finder. It allows professionals to scale up automation projects while leveraging the open
and widely known Arduino ecosystem. The Opta board is equipped with a powerful STM32H747XI
dual-core Cortex®-M7 + M4 MCU, enabling real-time control, monitoring, and predictive maintenance
applications. It supports secure OTA firmware updates and establishes data security from the hardware
to the cloud, through its onboard security element and X.509 standard compliance. The Opta board
also offers various connectivity options, such as Ethernet, Wi-Fi, and Bluetooth Low Energy. Figure 14.4
shows Opta PLC; other variants have the same shape but differ in communication features.
The Arduino Opta family includes the following variants and shown in Figure 14.4 (all variants look
are same in shape but different in connectivity so here I just added one picture):
• Opta Lite: This variant features Ethernet onboard and USB-C programming ports
• Opta RS485: In addition to Ethernet, this variant also provides an RS485 half-duplex
connectivity interface
• Opta Wi-Fi: The most versatile variant, this offers Wi-Fi/Bluetooth Low Energy connectivity
Arduino PRO 361
To program the Arduino Opta board, you can use the Arduino PLC IDE, which supports the five
programming languages defined by the IEC 61131-3 standard – Ladder, Functional Block Diagram,
Structured Text, Sequential Function Chart, and Instruction List. This makes PLC programming easy
and allows you to quickly code PLC applications, or port existing ones, to Arduino Opta or Portenta
Machine Control.
For more information about the Arduino Opta family and its features, visit https://www.arduino.
cc/pro/hardware-arduino-opta.
In these subsections, we have explored the three main top-of-the-line Arduino PRO hardware products.
In the following section, we will explore the Arduino PRO software tools.
The Arduino PLC IDE is an integrated development environment that allows you to program Portenta
Machine Control and Arduino Opta, using the five programming languages defined by the IEC 61131-3
standard. These languages are as follows:
• Ladder Diagram
• Functional Block Diagram
• Structured Text
• Sequential Function Chart
• Instruction List
The Arduino PLC IDE interface is shown in Figure 14.5. which is totally different from the Arduino
IDE. It supports various programming interfaces, as mentioned in the previous bullet points but one
of the famous programming interfaces for PLC is the Ladder Diagram, which is specially used by
PLC engineers to program the PLC.
362 Moving Ahead in the Arduino IoT Cloud
The Arduino PLC IDE offers an intuitive user interface (shown in Figure 14.5), complete with a suite
of debugging tools, including watch windows, breakpoints with step-by-step execution, triggers,
oscilloscope functionality, and live debug mode. It further extends its capabilities with rapid porting
solutions and enables the integration of PLC programming alongside Arduino sketches, through an
integrated sketch editor. This synergy permits the effortless exchange of variables between these two
environments, facilitating the inclusion of deterministic cyclic tasks and multitasking within your
software application.
The Arduino PLC IDE supports various industrial fieldbus protocols, including Modbus RTU, Modbus
TCP, and CANOpen. It offers a wide set of pre-installed libraries and function blocks, as well as the
option to create custom libraries. To program with IEC 61131-3, you will need to unlock the hardware
with a lifetime license key, available at the Arduino Official Store.
For more information about the Arduino PLC IDE and its features, please visit the official page
at https://www.arduino.cc/pro/software-plc-ide/.
In this subsection, we discussed the Arduino PLC IDE, which is specially designed for Arduino Opta
PLC to program it. The Arduino PLC supports five different languages to program in. In the following
subsection, we will explore the Speech Recognition Engine library.
Further resources and insights 363
The Arduino Speech Recognition Engine is a powerful software library that enables you to develop
projects based on speech recognition. It allows you to interact with machines using voice commands,
without the need for vocal training or an internet connection. The library was developed by Cyberon, a
worldwide leader in speech recognition, and is designed to be easy to use and compatible with multiple
Arduino boards and the Arduino IDE. It supports voice commands in over 40 languages, regardless of
the speaker’s voice, tone, or accent. You can configure multiple wake-up words and sequences without
retraining for different users.
The Speech Recognition Engine is ideal for various applications, such as smart buildings and home
automation, information kiosks, vending machines, smart beds in hospitals, and emergency alert
systems. It can listen to anyone speaking to it while ignoring background noise.
To get started with the Arduino Speech Recognition Engine, you can visit the official Arduino website:
https://www.arduino.cc/pro/software-speech-recognition-engine/. It offers
a robust library featuring an integrated AI/ML engine that excels in phoneme-based modeling. This
advanced library enables the recognition of multiple wake-up words and sequences of commands
without the need for vocal training. The library is compatible with multiple Arduino boards and
requires no additional hardware, software, or internet connectivity.
Note that there is also another Arduino board called Nicla Voice, which was discussed in the Arduino
PRO hardware section. This board implements always-on speech and motion recognition at the edge.
It integrates a neural decision processor from Syntiant (NDP120) to run multiple AI algorithms.
In the Arduino PRO section and subsections, we explored the main Arduino PRO top-of-the-line
development boards, including the Portenta series, the Nicla series, and the OPTA PLC series. We
also explored Arduino PRO software, including the Arduino PLC IDE and the Speech Recognition
Engine library. In the following section, we will cover some further resources for your learning.
Along with the Arduino community, you can also be part of some other globally famous maker
communities, such as https://Hackster.io and https://instructables.com/. On
these platforms, you will find the latest projects along with complete descriptions, and they are a good
way to keep yourself updated. After learning from these communities, it’s your turn to submit your
DIY projects to them to educate other community members. The two aforementioned communities
also host contests in different categories; try to participate in them.
Here is a list of other Arduino resources that will help you to further your learning:
In this section, we explored the different online resources that will help you to keep yourself updated
with new developments, as well as become part of the online maker communities, keeping yourself
engaged for further learning.
Summary
In this chapter, we explored different pricing plans for individuals, educational institutes, and enterprise
organizations. All the plans were discussed in depth, and we also compared the plans to explore further
differences. The Arduino IoT Cloud provides features with different thresholds for different plans,
according to users’ needs. Then, we explored the Arduino PRO software and hardware tools in depth,
allowing you to make informed decisions when developing industrial solutions. Finally, we explored
further resources that can provide you with the latest news and updates about product developments,
and we also shared different community resources that a user can benefit from by becoming a member.
Summary 365
So, after reading this chapter, you will be able to identify which pricing plan you need for your usage and
also guide your organization or customers, according to their needs, on which Arduino Cloud plan is
suitable for them. You also now know the Arduino PRO hardware development boards, including the
Portenta, Nicla, and Opta series, as well as Arduino PRO software, including the Arduino PLC IDE and
the Speech Recognition Engine. This Pro line will help you to identify and choose specific hardware
and software tools for your professional and industrial-grade solutions. Finally, you now know how
to keep yourself updated by following the links provided in the Further resources and insights section.
As we reach the end of Arduino IoT Cloud for Developers, I hope this journey has been as enlightening
and rewarding for you as it has been for me. The world of IoT is a realm of limitless possibilities, where
the things around us become more intelligent, responsive, and interconnected.
Through these pages, we explored the fundamentals of IoT, delved deep into the capabilities of the
Arduino IoT Cloud, and brought our knowledge to life through hands-on projects. We embraced
the power of data exchange, advanced scripting, and practical applications that enhance our lives.
Remember that IoT development is a continuous adventure, with countless opportunities waiting
for you. As you move forward, keep experimenting, creating, and innovating. The world needs your
ideas, your solutions, and your vision for a smarter, more connected future.
Whether you’re a novice or an experienced developer, I encourage you to stay curious, keep learning,
and never stop exploring. The intersection of IoT and Arduino is a place where innovation thrives,
and it’s now your playground.
Thank you for embarking on this journey with me. Here’s to the endless possibilities that IoT and the
Arduino IoT Cloud bring to our lives. The future is yours to create.
Index
A project architecture 100
schematics and design 100, 101
access Thing setup 103, 104
securing 327, 328 Altium 237
acid rain 96 Amazon Alexa 255
Adafruit 119 URL 271
ADS module library 239 used, for integrating Arduino
agriculture IoT system IoT Cloud 271-274
architecting 233 Amazon Echo Dot 82
assembly of hardware components 236-239 Analog Electrochemical Carbon
PCB design 236-239 Dioxide Sensor 111
schematics and design 234-236 Analog Input (AIN) 240
agri-tech project Analog Output (AO) 100
hardware components 229-233 analog-to-digital converters 98
air quality monitoring 96 Apache License 25
significance, reasons 96, 97 API authentication keys
air quality monitoring system creating 192, 193
assembly of hardware components 102, 103 setting up 193
associated device 105, 106 API keys
cloud variables 105 setting up 327, 328
code 107, 108 using, to authenticate Arduino
dashboard setup, for web and Cloud CLI 327, 328
mobile 109, 110 Application Programming
hardware requirements 97-100 Interface (APIs) 69
network configuration, for Thing 107 Arduino 97
PCB design 102, 103 Arduino Cloud
URL 192
368 Index
F I
field-to-device path 19 IFTTT 70, 190, 318
fleet management 355 inadequate access controls 21
Fourth Industrial Revolution 11 Indoor MKR Wi-Fi 1010 173
Free Software 25 Industrial Internet of Things (IIoT) 3, 10-12
Fritzing 96, 102, 173, 233 Industry 4.0 3, 11, 12, 135
Fully Qualified Board Name (FQBN) 65, 200 input controls 71
Colored light widget 72, 74
P
O parts per million (ppm) 99
on-the-cloud approach pay-per-usage model 15
versus intelligence at the edge 5, 6 PCBWay 102
open source licenses Peer-to-Peer (P2P) communication 170
benefits 25, 26 pilot SIM card 124
obligations 25, 26 pin layout (pinout) 229
open source software 24 Portenta family 357, 358
protection, of intellectual property 26, 27 Portenta H7 Lite 358
Opta PLC 360 Portenta H7 Lite Connected 358
Opta Lite 360 Portenta Machine Control 358
Opta RS485 360 Portenta Max Carrier 358
Opta Wi-Fi 360 Portenta X8 358
reference link 361 reference link 358
OTA management 346, 347 Portenta series 7
OTA update Portenta X8 Manager 355, 356
implementing, on MKR Wi-Fi 1010 299, 300 Postman 193
outcome-based model 15 download link 193
output controls 77, 78 used, for testing API call 194-197
chart widget 79, 80 workspace 193, 194
gauge widget 79 Power LED 100
map widget 79, 80 precision farming 229
374 Index
Printed Circuit Board (PCB) 95, 258 mobile dashboard, creating 163, 164
project architecture network configuration 156
designing 120 project architecture, designing 142
GPS module, assembling 120, 121 schematics design 142-144
GPS module data, testing 122-124 sensors 140-142
schematic design 120, 121 Thing, setting up 148, 149
properties/cloud variables 214 web dashboard, creating 163, 164
properties/cloud variables, with Node.js SDK remote operation monitoring 135
creating 214, 215 Representational State Transfer
deleting 217 (REST) API 32
listing 218, 219 role-based access control 355
updating 216, 217
property value, with Node.js SDK 224
obtaining 224
S
setting 225 Scheduler 279, 280
PRO series employing, advantages in IoT cloud
reference link 7 environment 280, 281
protocols 18-20 implementing, with MKR Wi-Fi
pull requests 70 1010 example 282
pull resistor 243 Scheduler Widget 75-77
pulse sensor 306 SDKs, for programming platforms 197
push button 71 GoLang 197
push requests 70 Node.js 197
Python 70, 197 Python 197
Secure Element 24
Why subscribe?
• Spend less time learning and more time coding with practical eBooks and Videos from over
4,000 industry professionals
• Improve your learning with Skill Plans built especially for you
• Get a free eBook or video every month
• Fully searchable for easy access to vital information
• Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files
available? You can upgrade to the eBook version at Packtpub.com and as a print book customer, you
are entitled to a discount on the eBook copy. Get in touch with us at customercare@packtpub.
com for more details.
At www.packtpub.com, you can also read a collection of free technical articles, sign up for a range
of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Other Books You May Enjoy
If you enjoyed this book, you may be interested in these other books by Packt:
• Get to grips with the essentials of different architectural patterns and anti-patterns
• Discover the underlying commonalities in diverse IoT applications
• Combine patterns from physical and virtual realms to develop innovative applications
• Choose the right set of sensors and actuators for your solution
• Explore analytics-related tools and techniques such as TinyML and sensor fusion
• Overcome the challenges faced in securing IoT systems
• Leverage use cases based on edge computing and emerging technologies such as 3D printing,
5G, generative AI, and LLMs
Other Books You May Enjoy 379
https://packt.link/free-ebook/9781837637171