Internet of Things Using Single Board Computers 2022
Internet of Things Using Single Board Computers 2022
I N N O VAT I O N S
SERIES
Internet
of Things Using
Single Board
Computers
Principles of IoT and
Python Programming
—
G. R. Kanagachidambaresan
Internet of Things
Using Single Board
Computers
Principles of IoT and Python
Programming
G. R. Kanagachidambaresan
Internet of Things Using Single Board Computers: Principles of IoT and
Python Programming
G. R. Kanagachidambaresan
Chennai, India
ISBN-13 (pbk): 978-1-4842-8107-9 ISBN-13 (electronic): 978-1-4842-8108-6
https://doi.org/10.1007/978-1-4842-8108-6
v
Table of Contents
Smart Devices�����������������������������������������������������������������������������������������������������16
Human-Computer Interaction������������������������������������������������������������������������16
Context Awareness���������������������������������������������������������������������������������������������17
Actuators�������������������������������������������������������������������������������������������������������������18
IoT and Smart City Applications��������������������������������������������������������������������������22
Automobile Sensors��������������������������������������������������������������������������������������22
Smart Home Sensors�������������������������������������������������������������������������������������23
Smart Transportation Sensors�����������������������������������������������������������������������25
Summary������������������������������������������������������������������������������������������������������������28
References����������������������������������������������������������������������������������������������������������28
vi
Table of Contents
vii
Table of Contents
viii
Table of Contents
ix
Table of Contents
x
Table of Contents
Index�������������������������������������������������������������������������������������������������281
xi
About the Author
G. R. Kanagachidambaresan completed
his PhD in Information and Communication
Engineering from Anna University, Chennai,
in 2017. He is currently an associate professor
in the CSE Department at Vel Tech Rangarajan
Dr. Sagunthala R&D Institute of Science and
Technology. He is also a visiting professor at
the University of Johannesburg.
His main research interest includes the
Internet of Things, Industry 4.0, body sensor
network, and fault-tolerant wireless sensor
network. He has published several reputed articles and undertaken several
consultancy activities for leading MNC companies. He has guest-edited
several special issue volumes and books and served as an editorial review
board member for peer-reviewed journals. He is TEC committee member
in DBT, GOI, India.
He is presently working on several government-sponsored research
projects like ISRO, DBT, and DST. He is Wiley’s editor-in-chief of the Next
Generation Computer and Communication Engineering Series. He is also
the managing director for Eazythings Technology Private Limited.
xiii
About the Technical Reviewer
Massimo Nardone has more than 22 years
of experience in security, web/mobile
development, cloud, and IT architecture. His
true IT passions are security and Android.
He has been programming and teaching
how to program with Android, Perl, PHP, Java,
VB, Python, C/C++, and MySQL for more than
20 years.
He has a master of science degree in
computing science from the University of
Salerno, Italy.
He has worked as a project manager, software engineer, research
engineer, chief security architect, information security manager,
PCI/SCADA auditor, and senior lead IT security/cloud/SCADA architect
for many years.
xv
Acknowledgments
My heartfelt thanks to Apress, especially Jessica Vakili and Susan
McDermott, for helping me throughout this project.
I sincerely thank the Department of BioTechnology (DBT-India) for
their funding (BT/PR38273/AAQ/3/980/2020) on the smart aquaculture
project.
I would also like to extend thanks to my JRFs: Ms. Meenakshi KV, Mr.
M. Akash, Ms. A. V. Anandhalekshmi, and Ms. V. Sowmiya.
I give special thanks to my son Mr. Ananthajith K, my wife, Dr. Mahima
V, my parents, Mr. G. S. Ramasubramanian and Mrs. Lalitha, and
Mrs. Chandra, Mr. Venkatraman, Mrs. V. Chitra, and Mr. V. Bharath for their
timely support.
xvii
Preface
The rapid growth of technology and new smart, sustainable development
initiatives has made the Internet of Things (IoT) and edge analytics
an inevitable platform for all engineering domains. The need for a
sophisticated and ambient environment has resulted in an exponential
growth in automation and artificial intelligence. The right sensor or
actuator, a specific processor, and the correct transmission unit can offer
the best solution to any IoT problem. Lightweight machine learning
or mathematical logic can bring a good solution to existing smart-city
problems.
This book provides detailed information on sensors, their interfacing
connections, programming with single-board computers, and creating
integrated projects with a combination of sensors, processors, and
actuators. A detailed introduction to Python and Arduino-based
programming is also discussed to kindle interest in IoT programming. IoT
products’ wired and wireless connections are discussed, and programming
examples are provided.
This is a completely new textbook that reflects recent developments
while providing a comprehensive introduction to the fields of IoT, single-
board computers, and Python programming. It is aimed at advanced
undergraduates as well as researchers and practitioners. This book deals more
with electronics and programming than simple text. It best suits outcome-
based education systems and can aid industry-ready IoT engineers.
Funding Information
The part of this book is supported by the Department of Biotechnology
funding information (BT/PR38273/AAQ/3/980/2020).
xix
CHAPTER 1
An Overview of the
Internet of Things
(IoT) and Sensors
Recent advancements in single-board computers (SBCs) [16] and boards
have made the Internet of Things (IoT) more accessible and easier to use.
The complete automation, information analysis from sensor data, and
integration of individual components with IoT systems helps to build new
Smart environment solutions. The scope of the areas is broadened with
IoT components and sensors.
IoT uses existing and emerging technology for event detection and
automation. IoT has the advantages of recent software advancements,
reducing hardware prices and available technology options. It created a
great change in product delivery and services and a major revolution in
Industry 4.0. Figure 1-1 illustrates the key features of IoT.
© G. R. Kanagachidambaresan 2022 1
G. R. Kanagachidambaresan, Internet of Things Using Single Board Computers,
https://doi.org/10.1007/978-1-4842-8108-6_1
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
Sensors
Sensors are the main data acquisition and detection system, which
converts any physical quantity (i.e., event) into a signal. In some sensors,
direct conversion takes place; in others, multiple conversions take place
to attain accuracy and quantification. Some of the sensors used in IoT and
prototyping are shown in Figure 1-2. Sensors are collectively connected
with an A/D converter to convert their signals to digital forms so that a
processor understands and can program effectively. Figure 1-2 illustrates
sensor classification (mode of operation, signal output, and energy-based).
2
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
Energy-based
Generator
Energy generation–based sensors provides conversion energy conversion,
like voltage and current, on any physical event. For example, a
piezoelectric sensor converts vibration energy to a proportional voltage.
The seebeck metal junction converts the change in temperature to
proportional energy conversion.
3
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
Conversion
Sensors convert one mode of physical quantity to another; for example,
an anemometer converts air velocity to rotational motion, which is further
converted to electrical voltage for measurement. These sensors are
operated in a proportional zone for calibration and stable operation. Most
sensors provide linear data conversion.
Signal Output
Analog
Sensors such as anemometers provide analog conversion of data. Analog
signal from annemometer is converted to digital data with the help of an
analog-to-digital converter. The sensor’s frequency of operation should
be far greater than the frequency of the physical quantity to get clear
information after digital conversion.
Discrete
Cameras and tile-based sensors provide discrete and digital information
directly to the processor. This makes the sensor easy to integrate with any
digital processor.
Mode of Operation
Sensors are deflection- or comparison-based. Deflection happens when
sensing a physical event. This is normally an angular-based movement
between two points. Comparison-based meters normally work with
standard available data. GPS sensors provide comparison-based sensing.
• Deflection (e.g., voltage meters and current meters)
4
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
Electronic Sensors
Figure 1-3 illustrates sensor classification based on the field of operation,
such as mechanical, optical, electrical, acoustic, thermal, chemical,
radiation, biological, and magnetic.
Mechanical
• Linear and angular position
• Acceleration
5
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
• Force
• Strain
Optical
• Wave velocity
• Wave amplitude
Electrical
• Conductivity
• Potential difference
• Field
Thermal
• Heat flux
• Thermal conductivity
Chemical
• States and identifies
• Color change
• Change in voltage
6
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
Radiation
• Energy
• Intensity
Biological
• Mass
• Concentration
• States
• Magnetic
• Magnetic field
• Magnetic flux
• Permeability
Connectivity
Figure 1-4 illustrates the connectivity features of IoT communication.
7
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
Bluetooth Low Energy, Zigbee, LoRa, and Wi-Fi are the most common
types of connectivity in an IoT environment. I2C, SPI, and Rx-Tx serial
communication protocols are examples of wired connectivity.
Bluetooth
Bluetooth network technology creates a personal area network (PAN) by
wirelessly connecting mobile devices over a short distance. The Bluetooth
architecture has its own independent model with a stack of protocols; it
does not follow the standard OSI or TCP/IP models.
Zigbee
The Zigbee 3.0 protocol [1] is an IEEE 802.15.4 specification that supports
a 2.4 GHz frequency band. The following are some of the features of
Zigbee 3.0.
8
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
Wi-Fi
Wi-Fi [2] is a technology that transfers data through radio waves that can
make small gadgets exchange data connected within a small router. Wi-Fi
uses the Institute of Electrical and Electronics Engineers’ (IEEE) 802.11
standards for effective data transmission.
IEEE 802.11 devices have the primary benefit of making it easier to
deploy local area networks (LANs) at a lower cost. They can host wireless
LANs in outdoor areas and airports, where running cables to every device
isn’t practical.
9
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
LoRa
LoRa [3] is a long-range wireless communication technology derived from
the CSS chirp-based spread spectrum. The chirp pulses communicate
information, similar to BATS communication.
Wired Communication
I 2C
I2C (Inter-Integrated Circuit) [4] is a two-wired communication protocol
(see Figure 1-5). It is a bus interface, serial communication protocol built
into devices. It has recently become a popular protocol for short-distance
communication.
Only two bidirectional open-drain lines—SDA (Serial Data) and SCL
(Serial Clock)—are used for data communication. Both lines are cranked
up. The SDA pin sends and receives data. SCL carries the clock signal.
I2C has two modes of operation: master and slave. Master mode is the
most advanced mode.
Slave mode obeys the command from the master and transmits or
receives data accordingly.
Each clock’s high to low pulse on the SCL line synchronizes each data
bit transferred on the SDA line. Figure 1-5 shows I2C communication
protocols.
10
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
SPI
The data communication module uses SDA and SCL dual connection
lines. SDA receives and transmits data. Serial Peripheral Interface (SPI)
communication is mainly used by components such as RTC, A-to-D
converters, and other computer peripherals. SPI [5] communication uses
a full duplex synchronous communication protocol that works in serial
mode between the master and slave devices. Figure 1-6 illustrates SPI
communication protocols.
Serial Communication
Serial communication is a straightforward and dependable way to send
data over long distances. RS-232 is a widely used serial communication
protocol. The data in this standard is sent in serial format at a preset
speed (called a baud rate/number) of bits communicated between
the sender and receiver. Common baud rates are 4800, 9600, 19200,
and 38400. Figure 1-7 shows the connection diagram for the UART
communication scheme.
11
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
Machine Intelligence
Machine intelligence [14] attempts to program a computer to perform
previously human-only tasks. In general, the learning process in intelligent
machines entails gathering information about their environment,
deploying that information to build knowledge about it, and then
generalizing that knowledge base to deal with environmental uncertainty.
Two machine intelligence techniques—imitation learning and
reinforcement learning—have been developed to help machines learn.
The learning algorithms are opted based on consideration of tasks and
their characteristics. Intelligent systems are an option to collect data
from the agents and acquire knowledge about its surrounding, and the
computation is adapted for the environment. To maintain control over
a society of autonomous agents, the agents’ learning process requires a
self-organizing mechanism. It should be noted that imbuing intelligent
machines with the capacity to learn is a difficult task; however, the capacity
to learn is what defines a machine as intelligent. Figure 1-8 illustrates
machine learning classification based on input data.
12
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
13
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
Active Management
The main components and operation of a closed-loop sensor management
system are depicted in Figure 1-9. The raw sensor data is processed for
information relevant to the sensing objective when the sensor is chosen,
and a measurement is taken. This usually requires the fusion of data from
several sensing modalities (e.g., optical and acoustic) and other properties,
as well as the addition of information from earlier measurements and
possibly other sources. Auxiliary information, such as target tracks or
choices about non-sensor manager-related concerns, may be generated by
the loop’s fusion and signal processing. For sensor management reasons,
they must generate a state of information that allows quantification
of the benefits of each feasible sensor selection in the following time
epoch. Currently, accessible quantification methodologies range from
statistical (e.g., mean risk or knowledge gain) to entirely heuristic. The
sensor management must then optimize which sensor to use for the next
measurement.
14
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
Sensor Fusion
Sensor fusion is a technique for reducing the amount of uncertainty in a
robot’s navigation or task performance by combining data from multiple
sensors, as shown in Figure 1-10. Sensor fusion helps the robot create a
more accurate world model, which allows it to navigate and behave better.
There are three main methods for combining sensor data.
15
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
Smart Devices
Human-Computer Interaction
Human-computer interaction (HCI) [6] is a subfield of computer science
that investigates how people (users) interact with computers, as well
as the design, evaluation, and implementation of user interfaces for
16
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
computer systems that are responsive to the user’s needs and habits.
This multidisciplinary field incorporates computer science, behavioral
sciences, and design. One of the primary goals of HCI is to make
computer systems more accessible and useable. A user interface consists
of hardware and software that allows users to modify the system while
allowing the system to communicate with the user. HCI focuses on the
design, implementation, and evaluation of user interfaces. In its broadest
sense, HCI occurs when a human user and a computer system collaborate
to achieve a goal. Usability is the part of human-computer interaction
concerned with making it, among other things, successful, efficient, and
enjoyable for the user. Usability entails usability, productivity, efficiency,
effectiveness, learnability, retention, and user interest.
Context Awareness
Figure 1-11 depicts sensor data context awareness [7]. The sensor data and
context awareness provide better infrastructure and ambiance.
17
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
Actuators
The applications in a smart city [10]—such as health care, smart
agriculture, and other industrial applications—use actuators [8], such
as drives, motors, and other physical signal converters. A wireless sensor
and actuator network (WSAN) [9] comprises automated actuators.
Microcomputers normally link directly to tiny actuators; however, heavy-
load actuators are coupled via driver circuits. Linear and rotational moving
actuators are the two types of actuators that move. A huge number of our
daily demands, such as fans and escalators, are met by these actuators.
Electric, pneumatic, and hydraulic power sources are also used to
classify them. Electric actuators are the most frequent, and PWM signals
are generated by the system control actuators like servo and stepper
motors. The significant change in the pulse width, time, and change in
frequency is reflected in the actuator’s velocity, rotational direction, and
amount of torque exerted. Most actuators in the industry are actuated
through PLC boards. This chapter showcases building prototypes with
small servos and steppers, which are often accomplished using SBCs like
Arduino and Raspberry Pi.
Table 1-1 describes the actuator types mentioned in this book,
including micro steppers, SG90, and infrared. To keep things simple,
these actuators are primarily programmed using Arduino and Raspberry
Pi ideas.
18
Table 1-1. Actuator Types
S.No Actuator type Output Operating Power Number External Connectivity type
range required of wire battery source Analog/i2c/spi, digital/
connection required driver requirement
2 Stepper motor Angular 2.55 v-2.8 v 1.68 Amps 4 Yes Drivers or DPDT relay
position
3 Oled display Digital 3.3V-5V 3.3v 12C pins yes IIC & SPI
display 20mA max
(continued)
19
An Overview of the Internet of Things (IoT) and Sensors
20
Table 1-1. (continued)
S.No Actuator type Output Operating Power Number External Connectivity type
Chapter 1
5 Solenoid Mechanical 5-10ms 9-65W 2 terminals External Both digital and analog
energy 15-150ms each regulator or
angular separate power
motion supply
6 IR led Light 760-1nm 1.2-3.4V 2 pins for no Both digital and analog
Max = 780- each
50nm
An Overview of the Internet of Things (IoT) and Sensors
7 Heat Thermal 1000°C and Not Wires not Acid batteries Tube box
exchanger 1000 bars needed needed
21
An Overview of the Internet of Things (IoT) and Sensors
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
22
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
23
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
24
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
25
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
and service transportation can be done through ICT tools. The platform
used by intelligent transport systems (ITS) to access, gather and assess
precise environmental data is crucial to its operation.
There are typically two types of sensor platforms. The first is an intra-
vehicle sensing platform that collects data about a vehicle’s condition.
The two approaches of sensing are used in ITS. An intra-vehicle sensing
platform collects data about a vehicle’s working conditions. An urban
sensing platform gathers information about traffic conditions. Sensing
technology has become essential for vehicle-to-vehicle (V2V) [15] and
vehicle-to-infrastructure (V2I) communication. The data is further
communicated to a transportation management system (TMS) for further
data analysis and prognostics. The data can offer prognostics that can be
used for decision-making, reducing pollution, emission traffic congestion,
and road reconstruction.
Non-intrusive sensors offer information like the location of the signal
acquired through GPS devices, traffic queue density through LIDAR and
traffic conditions through combined GPS information, and road and
weather conditions. Sensors, such as high traffic lights, are typically placed
in higher positions to monitor the region of interest. These sensors are also
mounted under bridges and directly beneath a surveillance zone. Some
sensors are positioned at the ground level to detect pedestrians. These
are mostly used for single lanes and unidirectional traffic due to their
vulnerability to interference from neighboring objects. Figure 1-14 shows
sensors utilized in intelligent transportation.
26
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
27
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
Summary
This chapter overviewed sensors, actuators, and other communication
protocols. Various sensor usage with different applications was also
addressed in this chapter. Sensor classification and interfacing with boards
are discussed in the next chapter.
References
[1] S. Long and F. Miao, “Research on Zigbee wireless communication
technology and its application,” 2019 IEEE 4th Advanced Information
Technology, Electronic and Automation Control Conference (IAEAC),
pp. 1830–1834. doi: 10.1109/IAEAC47372.2019.8997928.
[4] Dawoud Shenouda Dawoud and Peter Dawoud, “Design of I2C Bus
and Operation,” in Microcontroller and Smart Home Networks, River
Publishers, 2020, pp. 55–112.
28
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
[6] Erin T. Solovey and Felix Putze, Improving HCI with Brain Input:
Review, Trends, and Outlook, Now Publishers, 2021.
[8] Jeffrey Wishart, Yan Chen, Steven Como, Narayanan Kidambi, Duo
Lu, Yezhou Yang, “Sensor and Actuator Hardware,” in Fundamentals of
Connected and Automated Vehicles, SAE, 2022, pp.70–89.
29
Chapter 1 An Overview of the Internet of Things (IoT) and Sensors
[13] Saravjeet Singh and Jaiteg Singh, “Location Driven Edge Assisted
Device and Solutions for Intelligent Transportation,” in Fog, Edge, and
Pervasive Computing in Intelligent IoT Driven Applications, IEEE, 2021,
pp.123–147. doi: 10.1002/9781119670087.ch7.
30
CHAPTER 2
© G. R. Kanagachidambaresan 2022 31
G. R. Kanagachidambaresan, Internet of Things Using Single Board Computers,
https://doi.org/10.1007/978-1-4842-8108-6_2
Chapter 2 IoT Sensors and Their Interfacing Protocols
32
Chapter 2 IoT Sensors and Their Interfacing Protocols
Light Rings
Sometimes, additional lighting is used. Lights can be white, red, blue,
or green, depending on the imaging task. Under green light, facial
abnormalities can sometimes be noticed more clearly. Backlighting
can bring attention to features in a complex shape that might otherwise
be overlooked in front lighting. There is also infrared and ultraviolet
lighting. A variety of wide-angle and telephoto photos can be created by
changing lenses. In most cases, imaging sensors are fast enough to capture
photographs of products as they pass by. Other image sensing methods are
used for high-speed lines like printing, such as the ones described next [9].
34
Chapter 2 IoT Sensors and Their Interfacing Protocols
Using vision sensors to check discrete parts is not the same as using
them to check fast-moving products like printed webs or sheet steel in a
continuous process. Some of these applications use area cameras, and the
resulting images are “stitched” together in software. However, you can also
use a line scan camera [15]. Using rows of pixels, these cameras are set up
to take a single-line photo at the same speed as the moving object. Using
downstream air jets, these cameras could be used to eliminate trash and
food that isn’t good enough to eat. In general, these cameras are not like
regular vision sensors and need their own image processing.
35
Chapter 2 IoT Sensors and Their Interfacing Protocols
Thermocouples
Figure 2-6 shows a thermocouple used in industries for identifying the
temperature.
36
Chapter 2 IoT Sensors and Their Interfacing Protocols
1 Iron/Constantan J
2 Nickel-Chromium / Nickel-Alumel K
3 Copper/Constantan T
4 Nickel-Chromium/Constantan E
5 Nicrosil / Nisil N
6 Platinum Rhodium – 10% / Platinum S
7 Platinum Rhodium –13% / Platinum R
8 Platinum Rhodium – 30% / Platinum Rhodium – 6% B
37
Chapter 2 IoT Sensors and Their Interfacing Protocols
39
Chapter 2 IoT Sensors and Their Interfacing Protocols
40
Chapter 2 IoT Sensors and Their Interfacing Protocols
Thermometers
This type of thermometer is non-contact and does not use an analog scale
to measure temperature. It is possible to obtain a temperature reading
by measuring how much black body radiation an object emits. Through
a lens, a thermopile generates an electrical output proportional to the
amount of heat absorbed by a thermometer. The ability to record and save
data from infrared thermometers is a time-saving and process-simplifying
feature. It is common practice to use an infrared thermometer to monitor
the temperature of sensitive locations such as the tympanic membrane
(eardrum). A further benefit for firefighters is that they can analyze the
spread of a fire without manually inspecting or checking for hot spots
within a burning area using thermal imaging cameras. Figure 2-10 shows
an infrared based temperature identification sensor.
41
Chapter 2 IoT Sensors and Their Interfacing Protocols
Radiation Sensors
Figure 2-11 showcases a radiation based sensor for identifying the
temperature.
The following are the most frequently used types of radiation detectors.
Proximity Sensors
Figure 2-12 showcases a proximity sensor for position recognition.
Proximity sensors [20] are electronic devices that can tell when
something is close without touching it. A proximity sensor can find things
within a few centimeters and send a DC output signal to a controller.
In many manufacturing processes, proximity sensors are used to find
nearby items and machine parts. Important factors include the type of
sensor, its maximum sensing distance, minimum and maximum working
temperatures, and length and diameter. Most proximity sensors have a
short range, but some can pick up on things up to a few inches away. A
capacitive proximity sensor shows this type of sensor. This device detects
a change in capacitance caused by a decrease in the distance between
the plates of a capacitor, one of which is attached to the object under
observation. This change in capacitance is caused by a decrease in the
distance between the capacitor plates. The sensor can then tell how the
object is moving and where it is.
43
Chapter 2 IoT Sensors and Their Interfacing Protocols
There are different kinds of proximity sensors, and each has its own
way of working.
44
Chapter 2 IoT Sensors and Their Interfacing Protocols
Light Sensors/Photodetectors
Figure 2-14 showcases a light sensor and photo detector.
45
Chapter 2 IoT Sensors and Their Interfacing Protocols
46
Chapter 2 IoT Sensors and Their Interfacing Protocols
47
Chapter 2 IoT Sensors and Their Interfacing Protocols
Pressure Sensors
Figure 2-15 showcases an array based pressure sensor.
48
Chapter 2 IoT Sensors and Their Interfacing Protocols
Position Sensors
Figure 2-16 illustrates the position sensors.
49
Chapter 2 IoT Sensors and Their Interfacing Protocols
Photoelectric Sensors
Figure 2-17 shows the photoelectric sensors.
Particle Sensors
Dust and other airborne particulates are detected by sensors/detectors,
which provide signals to control and display inputs. The employment
of particle sensors [22] to monitor containers and baghouses is
commonplace. Transducer type, minimum detectable particle size, and
operational temperature range are critical specifications. In nuclear
engineering, particle detectors are used to detect radiation.
50
Chapter 2 IoT Sensors and Their Interfacing Protocols
The quality of the air is determined by the amount and size of aerosol
particles in the air. Particle count in a building or the surrounding air can
be estimated using this information. Furthermore, it helps to understand
the level of cleanliness in a controlled environment. In clean rooms,
aerosol particle sensors are commonly employed. Among other industries,
clean rooms are utilized in semiconductor manufacturing, biotechnology,
pharmaceutics, and optical disc drive manufacturing. In clean rooms, the
number of particles per cubic meter is regulated. Aerosol particle counters
or sensors ensure that a cleanroom satisfies regulatory standards.
51
Chapter 2 IoT Sensors and Their Interfacing Protocols
52
Chapter 2 IoT Sensors and Their Interfacing Protocols
The quality of any fluid can be determined via liquid particle sensors.
This information helps testers determine if the liquid is clean enough
for the intended application. For example, liquid particle counters can
be used to determine the quality of drinking water or cleaning solutions
and to inspect power generation equipment or injectable medicines for
cleanliness.
Fluid particle counters also monitor hydraulic fluid cleanliness and
systems like engines and gears. Hydraulic breakdowns are likely caused by
contamination in 75% to 80% of the cases. A wide variety of sensors can be
employed on equipment, in a laboratory for oil analysis, or on a machine
at the job site to verify fluid purity. Hydraulic failures can be minimized,
uptime and machine availability increased, and oil consumption lowered
by identifying and monitoring these levels and following a maintenance
program. Hydraulic fluids can be checked for appropriate cleanliness
levels using particle monitoring after they have been cleaned with
filtration.
53
Chapter 2 IoT Sensors and Their Interfacing Protocols
Metal Detectors
Figure 2-21 shows an RF based metal detector.
Level Sensors
Figure 2-22 shows a level detection sensor.
54
Chapter 2 IoT Sensors and Their Interfacing Protocols
Leak Detectors
Figure 2-23 shows a leak detection sensor.
55
Chapter 2 IoT Sensors and Their Interfacing Protocols
Sensors and detectors for liquid and gas leak detection and monitoring
are electronic equipment [23]. Ultrasonic technology, for example, can
detect air leaks in some leak detectors. Other leak detectors use simple
foaming agents to test the soundness of pipe junctions. Vacuum package
seals can be tested using other leak detectors.
Humidity Sensors
Figure 2-24 shows the DHT11 temperature and humidity sensor.
56
Chapter 2 IoT Sensors and Their Interfacing Protocols
Gas Detectors
Figure 2-25 showcases the gas detection MQ sensor.
Gas sensors and detectors [24] are used in many applications, from
flammable gases in industrial plants to ethanol in breathalyzer tests, to
detect the presence of gases. The most common gas sensors are made of
metal oxides and can detect a wide range of gases, including butane and
hydrogen. MQ detectors come in multiple shapes and sizes. Methane and
butane, for example, are detected by MQ2 sensors. MQ138 sensors detect
benzene and toluene.
A tin oxide-coated ceramic element is at the heart of an MQ2 sensor.
The tin oxide emits free electrons when the element is heated. These
electrons combine with oxygen, causing no current to flow through
the sensor. Some electrons remain uncombined with oxygen as the
atmosphere changes due to the presence of butane, for example, and
a small current flows through the sensor. More current flows through
the device as the amount of oxygen decreases, providing a quantifiable
measure of the amount of gas in the atmosphere. The sensor element is
57
Chapter 2 IoT Sensors and Their Interfacing Protocols
usually encased in mesh to keep dust out and prevent flammable gases
from igniting the element’s heating. MQ2 methane, butane, LPG; MQ3
methane, butane, LPG; MQ4 methane; MQ3 ethanol, Butane; and MQ6
LPG are some MQ series sensors.
Force Sensors
Figure 2-26 showcases an array based force sensor.
58
Chapter 2 IoT Sensors and Their Interfacing Protocols
59
Chapter 2 IoT Sensors and Their Interfacing Protocols
Flow Sensors
Figure 2-27 shows a simple generator based water flow sensor/meter.
60
Chapter 2 IoT Sensors and Their Interfacing Protocols
even combine the two. Flow rate, working pressure, and minimum and
maximum operating temperatures are all critical criteria for a sensor/
detector. Flow sensors [26] are frequently utilized in the manufacturing
business. Allowing process operators to quickly see flow conditions is a
benefit of some panel mounting designs.
There are three flow sensor classifications.
61
Chapter 2 IoT Sensors and Their Interfacing Protocols
Mass flow sensors, also known as mass air flow sensors, are commonly
used in automotive applications to measure the mass of air entering an
engine’s air intake system. Electronic engine control uses the sensor’s
output to calculate how much fuel to feed the engine to achieve the correct
fuel-air mixture for ignition.
Mass flow sensors measure energy transmission from a heated
surface to a flowing fluid. One method involves injecting a given amount
of thermal energy and watching the temperature change. In contrast,
the other involves maintaining a constant temperature for a probe and
estimating the amount of thermal energy required. A hot wire mass flow
sensor is a device that consists of a resistive wire connected to temperature
sensors through electric current. Convective heat transfer lowers the wire’s
electrical resistance as the airflow past the sensor increases. The electrical
current required to maintain the temperature of the hot wire increases
as the resistance decreases, allowing the electrical current required to
62
Chapter 2 IoT Sensors and Their Interfacing Protocols
maintain the temperature of the hot wire to be utilized as a mass flow rate
measurement. Temperature differences can be used to determine mass
flow rates in other ways.
The Coriolis flow meter is another type of mass flow sensor. As the
fluid moves through an oscillating tube, the inertia causes twisting in the
tube, which is directly proportional to the fluid’s mass flow rate, according
to this mass flow meter’s hypothesis. Using a driving coil, two tubes in the
sensor vibrate at opposite resonance frequencies to separate and direct the
process fluid. Electronic sensors in the tubes convert the oscillations into
a sine wave as they occur. No flow means that the entrance and outflow
sinusoids are in phase, indicating that the tubes are moving step by step.
The Coriolis force causes the tubes to bend in the opposite direction as
fluid flows through them. In response to this motion, the sine waves alter
in phase, indicating that the two tubes are moving at different rates.
In fluid flow, the time difference between two sine waves, given by the
symbol t, directly correlates to the mass flow rate. If you know how many
sine waves there are, you can figure out how dense the fluid in the tubes is.
On the other hand, the density of the fluid is directly related to the square
of the frequency. Denser fluids have a lower frequency of oscillation. When
the mass flow rate and fluid density are known, volumetric flow can be
easily calculated.
63
Chapter 2 IoT Sensors and Their Interfacing Protocols
• Ultrasonic
64
Chapter 2 IoT Sensors and Their Interfacing Protocols
65
Chapter 2 IoT Sensors and Their Interfacing Protocols
Flaw Sensors
Figure 2-30 shows an ultrasonic based flaw detection sensor.
Flame Detectors
Figure 2-31 shows an IR based flame detection sensor.
66
Chapter 2 IoT Sensors and Their Interfacing Protocols
These devices are electronic devices that detect the presence and kind
of fire and provide signals to control devices’ inputs, such as smoke and
heat detectors. A UV or infrared flame detector can be utilized in many
combustion control applications, including burners. When choosing a
detector, the type matters; under-the-hood fire suppression systems, for
example, make extensive use of flame detectors.
Contact Sensors
Figure 2-32 showcases a contact sensor.
67
Chapter 2 IoT Sensors and Their Interfacing Protocols
Non-Contact Sensors
Figure 2-33 showcases a non-contact sensor.
68
Chapter 2 IoT Sensors and Their Interfacing Protocols
HART
BACNET I2C
COMMON SENSOR
PROCESSOR INTERFACE
PROTOCOLS
RS485 SPI
UART
Summary
Sensor classification was discussed in this chapter. Wired interfacing with
SBCs was also covered. Programming sensors and interfacing with Python
is discussed in the next chapter.
69
Chapter 2 IoT Sensors and Their Interfacing Protocols
References
[1] Jeffrey Wishart, Yan Chen, Steven Como, Narayanan Kidambi, Duo
Lu, and Yezhou Yang, “Sensor and Actuator Hardware,” Fundamentals of
Connected and Automated Vehicles, SAE, 2022, pp. 70–89.
[5] Mohd Javaid, Abid Haleem, Ravi Pratap Singh, Shanay Rab, and Rajiv
Suman, “Significance of sensors for industry 4.0: Roles, capabilities,
and applications,” Sensors International, vol. 2, 2021. https://doi.
org/10.1016/j.sintl.2021.100110.
[6] J. Kim, H. Lim, S. Han, Y. Jung, and S. Lee, “Compensation Algorithm for
Misrecognition Caused by Hard Pressure Touch in Plastic Cover Capacitive
Touch Screen Panels,” Journal of Display Technology, vol. 12, no. 12, Dec.
2016, pp. 1623–1628. doi: 10.1109/JDT.2016.2615678.
70
Chapter 2 IoT Sensors and Their Interfacing Protocols
71
Chapter 2 IoT Sensors and Their Interfacing Protocols
72
Chapter 2 IoT Sensors and Their Interfacing Protocols
[22] R. Jia, L. Wang, C. Zheng, and T. Chen, “Online Wear Particle Detection
Sensors for Wear Monitoring of Mechanical Equipment—A Review,” in
IEEE Sensors Journal, vol. 22, no. 4, Feb. 15, 2022, pp. 2930–2947. doi:
10.1109/JSEN.2021.3131467.
[24] Jun Jiang and Guoming Ma, “Dissolved Gases Detection with
Optical Methods,” in Optical Sensing in Power Transformers, IEEE, 2021,
pp. 65–135. doi: 10.1002/9781119765325.ch4.
[25] C. Liu and H. Li, “Design and Experimental Validation of Novel Force
Sensor,” IEEE Sensors Journal, vol. 15, no. 8, Aug. 2015, pp. 4402–4408. doi:
10.1109/JSEN.2015.2418331.
73
CHAPTER 3
Programming SBCs
A sensor is a device that detects the presence of a specific entity or
function. A device can be electrical, optoelectrical, or electronic and made
of specialty electronics or other sensitive materials [1,2]. Transducers are
available to detect the physical presence, such as flame or metal. Other
sensors include those that measure levels or detect gas and chemical
presence. Some types detect motion or proximity, while others measure
physical properties like temperature, pressure, or radiation. Depending
on the application, they can use electromagnetic fields, optics, or a
combination. Sensors, detectors, and transducers of various kinds are
used in numerous applications across a wide range of industries to test,
measure, and control multiple machine processes and functions as the
Internet of Things (IoT) grows in popularity. Figure 3-1 shows the I2C
NodeMCU communication protocol.
© G. R. Kanagachidambaresan 2022 75
G. R. Kanagachidambaresan, Internet of Things Using Single Board Computers,
https://doi.org/10.1007/978-1-4842-8108-6_3
Chapter 3 Programming SBCs
Arduino Programming
//Master code
#include <Wire.h>
void setup() {
wire.begin();
serial.begin(9600);
}
void loop() {
wire.requestFrom(8, 6);
while (wire.available()) {
char c = Wire.read();
serial.print(c);
}
delay(500);
}
76
Chapter 3 Programming SBCs
//Slave code
#include <Wire.h>
void setup() {
wire.begin(8);
wire.onRequest(requestEvent);
}
void loop() {
delay(100);
}
Raspberry Pi
Raspberry Pi is a single-board computer with a small form factor.
Connecting the Raspberry Pi to peripherals such as a keyboard, mouse,
and display can function as a mini personal computer. Raspberry Pi is a
popular platform for real-time image/video processing, IoT applications,
and robotics.
While the Raspberry Pi is slower than a laptop or desktop computer,
it is still a computer capable of providing all the expected features or
capabilities while consuming little power.
Raspbian OS is officially provided by the Raspberry Pi Foundation
and is based on Debian. Additionally, they offer the NOOBS OS for the
Raspberry Pi. There are a variety of third-party operating systems, such as
Ubuntu, Arch Linux, RISC OS, and Windows 10 IoT Core.
Raspbian OS is an open source operating system that is available for
free use. This operating system is optimally optimized for use with the
Raspberry Pi. Raspbian includes a graphical user interface (GUI) that
includes tools for browsing, Python programming, office, and gaming.
77
Chapter 3 Programming SBCs
• Model 3B+
• Model 42 GB
• Model 4 4GB
• Model 4 8GB
• Model Pi Zero
• Model Pi Zero W
• Model Pi Zero WH
78
Chapter 3 Programming SBCs
with external devices. For instance, if you want to read the state of a
physical switch, you can assign any of the available GPIO pins as an
input and use the switch status to make decisions. Additionally, you can
configure any GPIO pin as an output to control an LED’s on/off state. The
Raspberry Pi can connect to the Internet via its built-in Wi-Fi or a Wi-Fi
USB adapter. Once the Raspberry Pi is connected to the Internet, you can
remotely control the devices connected to it.
The Raspberry Pi 3’s GPIO pinout is depicted in Figure 3-2.
GPIO pins on the Raspberry Pi 3 BCertain model’s GPIO pins are
multiplexed to perform alternate functions such as I2C, SPI, and UART. F.
Let’s define the GPIO pins used as output or input. Raspberry Pi has
two distinct methods for defining pin numbers: GPIO numbering and
physical numbering.
79
Chapter 3 Programming SBCs
In GPIO numbering, the term pin number refers to the location of a pin
on a Broadcom SoC (system-on-chip). As a result, when using GPIO pins,
you should always consider pin mapping.
While the pin number refers to the pin on the 40-pin P1 header on
the Raspberry Pi board in physical numbering. The physical numbering
scheme is straightforward, as you can simply count the pins on the P1
header and assign them to GPIO.
Now, let’s control the LED using Raspberry Pi’s switch. Here, you use
Python and C (WiringPi) to control the LEDs' ON/OFF state.
Now, let’s use Python on the Raspberry Pi to turn on and off an
LED. The switch turns the LED on and off.
To use Raspberry Pi’s GPIO pins in Python, you must import the RPi.
GPIO package, which contains GPIO-controlling classes. On Raspbian
OS, the RPi.GPIO Python package is already installed. As a result, there is
no need to install it externally. Simply put, you should include a library in
our program to enable us to use Python functions for GPIO access. This is
detailed next.
The value of a GPIO pin is read using this function; for example, how
the GPIO pins are used in BCM and BOARD modes in the RPi package is as
follows.
80
Chapter 3 Programming SBCs
In BCM,
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.OUT)
In BOARD,
GPIO.setmode(GPIO.BOARD)
GPIO.setup(40, GPIO.OUT)
#include <wiringPi.h>
#include <stdio.h>
int LED = 26; /* wiringPi – GPIO26, GPIO12-
BCM, 32 pin number */
int switch_input = 21; /* wiringPi –GPIO21, GPIO5 -
BCM, 29 Pin number */
int main(){
wiringPiSetup(); /* initialize setup*/
pinMode(LED,OUTPUT); /* configuring as output */
pullUpDnControl(switch_input, PUD_UP);
while (1){
if(digitalRead(switch_input))
digitalWrite(LED,LOW); /* off on GPIO */
else
digitalWrite(LED, HIGH); /* on on GPIO */
}
}
81
Chapter 3 Programming SBCs
Interfacing DHT
Figure 3-3 showcases the DHT sensors’ GPIO connections.
sensor = Adafruit_DHT.DHT11
If someone is using the DHT22 sensor, you must assign Adafruit DHT.
DHT22 to the sensor variable, as shown in Figure 3-4. Then assign the pin
number to which the data pin of the DHT sensor is connected. The DHT11
sensor’s output is connected to GPIO4, as illustrated in the preceding
interface diagram.
82
Chapter 3 Programming SBCs
import Adafruit_DHT
sensor = Adafruit_DHT.DHT11
pin = 4
while True:
humidity, temperature = Adafruit_DHT.read_
retry(sensor, pin)
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.
format(temperature, humidity))
if humidity is not None and temperature is not None:
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.
format(temperature, humidity))
else:
print(Try again!')
83
Chapter 3 Programming SBCs
• Resolution: 5 megapixels
• HD Video recording
sudo raspi-config
Then select the interfacing options, from which you can enable the
camera’s functionality.
85
Chapter 3 Programming SBCs
reboot
You can now access the camera on the Raspberry Pi. Now, you can
capture images and videos on the Raspberry Pi using the Pi camera.
import picamera
from time import sleep
camera = picamera.PiCamera()
camera.resolution = (1024, 768)
camera.brightness = 60
camera.start_preview()
#add text on image
camera.annotate_text = 'Hello folks'
sleep(5)
#store image
camera.capture('image1.jpeg')
camera.stop_preview()
86
Chapter 3 Programming SBCs
87
Chapter 3 Programming SBCs
while True:
#when motion detected turn on LED
if(GPIO.input(PIR_input)):
GPIO.output(LED, GPIO.HIGH)
else:
GPIO.output(LED, GPIO.LOW)
Python
Python is a high-level interpreted programming language. It supports
many programming concepts, such as object-oriented and functional
programming.
print("Hello, World!")
88
Chapter 3 Programming SBCs
89
Chapter 3 Programming SBCs
File Concepts
The following opens a file.
f = open("demofile.txt", "r")
print(f.read())
f = open("demofile.txt", "r")
print(f.read(5))
90
Chapter 3 Programming SBCs
f = open("demofile.txt", "r")
print(f.readline())
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
91
Chapter 3 Programming SBCs
Spreadsheet Concepts
pandas is used to work on the data. With the help of this module, you
can extract data from a database into an Excel spreadsheet, or you can
also convert an Excel spreadsheet into a programmatic format. pandas
is one of the most popular and favorite data science tools used in Python
programming for data wrangling and analysis. And pandas is a game
changer in cleaning, transforming, manipulating, and analyzing data.
92
Chapter 3 Programming SBCs
import pandas as pd
import numpy as np
Pd.readfiletype() #open a file
df=pd.read_excel(‘data.xlsx’,index_col=0)
df
93
Chapter 3 Programming SBCs
The following methods are used for viewing and inspecting data.
94
Chapter 3 Programming SBCs
The following methods are used in filtering, sorting, and grouping data.
• df.sort_values(col2,ascending=false): Column in an
descending order
• df.sort_values([col1,col2],ascending=[true,false]):
Sort values by col1 in ascending order then col2 in
descending order
Communication Concepts
Python provides two levels of access to network services. At a low level, you
can access the basic socket support in the underlying operating system,
allowing you to implement clients and servers for connection-oriented
and connectionless protocols.
95
Chapter 3 Programming SBCs
Socket
Sockets are the endpoints of a bidirectional communications channel.
Sockets may communicate within a process, between processes on the
same machine, or between processes on different continents [3].
Socket Modules
To create a socket, you must use the socket.socket() function available
in the socket module, which has the following general syntax. Socket
methods are listed and described in Table 3-1.
96
Chapter 3 Programming SBCs
A Simple Server
To write Internet servers, you use the socket function available in the
socket module to create a socket object. A socket object is then used to call
other functions to set up a socket server. Call the bind(hostname, port)
function to specify a port for your service on the given host. Next, call the
accept method of the returned object. This method waits until a client
connects to the port you specified and then returns a connection object
that represents the connection to that client [4].
97
Chapter 3 Programming SBCs
A Simple Client
The socket.connect(hosname, port) opens a TCP connection to the
hostname on the port. Once you have a socket open, you can read from it
like any IO object. When done, close it.
The following code is a simple client that connects to a given host and
port, reads any available data from the socket, and then exits.
s.connect((host, port))
print s.recv(1024)
s.close()# Close the socket when done
98
Chapter 3 Programming SBCs
import os
The following displays all the available SSIDs with the help of cmd
commands and a Python library named os.
99
Chapter 3 Programming SBCs
100
Chapter 3 Programming SBCs
<keyMaterial>"""+password+"""</keyMaterial>
</sharedKey>
</security>
</MSM>
</WLANProfile>"""
command ="netsh wlan add profile filename=\""+name+".
xml\""+" interface=Wi-Fi"
with open(name+".xml", 'w') as file:
file.write(config)
os.system(command)
import serial
• The port is the name of the port being used (find this in
the device manager).
101
Chapter 3 Programming SBCs
>>>ser=serial.Serial('COM3',38400,timeout=0,parity=serial
.PARITY_EVEN,rtscts=1) # read up to one hundred bytes
>>>s=ser.read(100)# or as much is in the buffer
102
Chapter 3 Programming SBCs
>>>ser=serial.Serial()
>>>ser.baudrate=19200
>>>ser.port='COM1'
>>>ser
Serial<id=0xa81c10, open=False>(port='COM1', baudrate=19200,
bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0,
rtscts=0)
>>>ser.open()
>>>ser.is_open
True
>>>ser.close()
>>>ser.is_open
False
Node-RED
Node-RED is a programming tool for wiring together hardware devices,
APIs, and online services in new and interesting ways. It provides a
browser-based editor that makes it easy to wire together flows using a wide
range of nodes in the palette that can be deployed to its runtime in a single
click [5].
Node-RED Features
• It supports browser-based flow editing.
103
Chapter 3 Programming SBCs
Node-RED Architecture
• Node-RED (latest version 0.16) is fast because it is driven
by the latest supported version of Node.js (LTS 6.x).
Node-RED Applications
• In Bluemix, Node-RED is used to connect to IoT (with
ReST and MQTT).
104
Chapter 3 Programming SBCs
MQTT Protocols
You could use HiveMQ as an MQQT broker for this explanation. It is a
messaging platform for fast, efficient, and reliable data movement to and
from connected IoT devices and enterprise systems [6].
The following installs MQQT.
import time
import paho.mqtt.client as paho
from paho import mqtt
def on_connect(client, userdata, flags, rc, properties=None):
print("Connection received with code %s." % rc)
def on_publish(client, userdata, mid, properties=None):
print("mid: "+str(mid))
105
Chapter 3 Programming SBCs
import gspread
import pandas as pd
from oauth2client.service_account import
ServiceAccountCredentials
# define the scope
scope = ['https://spreadsheets.google.com/feeds','https://www.
googleapis.com/auth/drive']
# add credentials to the account
creds = ServiceAccountCredentials.from_json_keyfile_
name('Script.json', scope) #Use the .json script API downloaded
from google cloud or any other cloud service.
# authorize the clientsheet
client = gspread.authorize(creds)
sheet = client.open('P2S')
sheet_instance = sheet.get_worksheet(0)
record = sheet_instance.get_all_records()
marks = sheet_instance.col_values(3)
print(record)
print(marks)
Firebase Programming
Firebase is a platform Google provides to accelerate app development. It
offers BaaS or back end as a service, which means that Firebase takes care
of cloud infrastructure and all your back-end needs. This lets you develop
and deploy faster [7].
107
Chapter 3 Programming SBCs
Matplotlib
The Matplotlib library for Python is a visualization library for creating
many types of graphs, like static graphs, animated graphs, and interactive
visualizations. Most Matplotlib utilities lie under the Pyplot submodule
and are imported under the plt alias [8].
108
Chapter 3 Programming SBCs
109
Chapter 3 Programming SBCs
Getting Started
Matplotlib plots the data on figures, the windows that contain one or more
axes (an area where points are specified in terms of x,y coordinates). A
simple graph is created using the following code.
110
Chapter 3 Programming SBCs
Thus, the simple graph is plotted with some random values of x and y
coordinates.
The simplest way of creating a figure with axes is using pyplot.subplots.
This pyplot.subplot creates subplots with the required number of axes.
Let’s create an empty figure using the plt.figure() function, as follows.
111
Chapter 3 Programming SBCs
112
Chapter 3 Programming SBCs
The preceding code used plt.plot() to plot a list of four values. The
x axis ranges from 0–3, and the y axis ranges from 1–4. If you provide a
list of values to plot, Matplotlib assumes it as a sequence of y values and
automatically generates values for x. Since the Python range generally
starts at 0, the default value of x axis starts from 0, and it has the same
length as y. So, the x values generated are [0,1,2,3]. The plt.ylabel()
function sets the label for the y axis. Similarly, plt.xlabel() function for the
x axis. The x axis and y axis values limit can also be given so that the output
graph can be plotted in a given range. It can be achieved by using plt.xlim()
and plt.ylim(). A title can be given to a figure using the plt.title() function.
113
Chapter 3 Programming SBCs
Fig = plt.figure()
plt.title("Sample Plot")
plt.plot([1, 3, 3, 4, 8, 9])
plt.ylabel('some numbers')
plt.xlabel("Python Generated Numbers")
plt.xlim(-3,3)
plt.ylim(-4,4)
plt.show()
114
Chapter 3 Programming SBCs
This is the output of the preceding code. The x and y axis labels are set.
The x axis and y axis ranges are given using xlim(), ylim function. Since the
range is negative to positive and the values start at 0, the graph is plotted
accordingly.
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.tan(2 * np.pi * x2)
plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'o-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')
plt.subplot(2, 1, 2)
plt.plot(x2, y2, '.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()
You are going to plot two subplots in a single figure. Four list values
are required to plot the graphs. Pyplot gets the values as a list and plots
it accordingly. x1, x2, y1, and y2 are the lists created with some values
generated using the NumPy array module. Then the plt.subplot(2,1,1).
115
Chapter 3 Programming SBCs
116
Chapter 3 Programming SBCs
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.tan(2 * np.pi * x2)
fig, (ax1, ax2) = plt.subplots(2, 1)
fig.suptitle('A tale of 2 subplots')
ax1.plot(x1, y1, 'o-')
ax1.set_ylabel('Damped oscillation')
ax2.plot(x2, y2, '.-')
ax2.set_xlabel('time (s)')
ax2.set_ylabel('Undamped')
plt.show()
The output is the same as the previous method; however, plt. subplot, a
Pyplot built-in function, created multiple subplots. Also, an empty figure was
created. Two axes—ax1 and ax2—were created using plt.subplots. The plotting
of these was done separately. Then, other actions, like setting the label and
axes limits—were done. Finally, the graph is shown using plt.show().
Bar Graphs
Bar graphs are best used when showing comparisons between categories.
Typically, the bars are proportional to the values they represent and can
be plotted either horizontally or vertically. One axis of the chart shows
the specific categories being compared, and the other axis represents
discrete values.
117
Chapter 3 Programming SBCs
118
Chapter 3 Programming SBCs
119
Chapter 3 Programming SBCs
120
Chapter 3 Programming SBCs
121
Chapter 3 Programming SBCs
122
Chapter 3 Programming SBCs
performance = 3 + 10 * np.random.rand(len(people))
ax.barh(y_pos, performance, align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis() # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')
plt.show()
123
Chapter 3 Programming SBCs
S
catter Plot
A scatter plot is a type of plot or mathematical diagram using Cartesian
coordinates to display values for typically two variables for a set of data.
Scatter plots are primarily used to observe and show relationships
between two numeric variables. The dots in a scatter plot report the values
of individual data points and patterns when the data are taken as a whole.
The following is an example.
Two lists of equal length with some values are considered. It is plotted
using plt.scatter(list1,list2), which plots the values of x and y in the
corresponding coordinates. The label and title are given, and the graph is
shown using plt.show().
Figure 3-17 shows the output.
124
Chapter 3 Programming SBCs
125
Chapter 3 Programming SBCs
s *= 10**2.
fig, ax = plt.subplots()
ax.scatter(x, s, marker=verts)
plt.show()
The area of the ellipse is fixed to mark in the graph. A verts variable is
defined, where the measurements about the ellipse is stored, which is then
mentioned in the ax.scatter()as marker=verts. Then two lists—x and s—
with random values are generated and are marked in the figure.
Figure 3-18 shows the output.
S
pectrum Representation
Matplotlib can also be used for spectrum representations. A signal is a
function of time that is represented by a series of sinusoidal components.
These sinusoidal components have different amplitudes, frequencies,
126
Chapter 3 Programming SBCs
phases, and magnitudes. Thus, the plotting of the frequency versus the
sinusoidal components’ amplitude and phase comprise a signal called a
frequency spectrum or the spectrum of a signal. The frequency spectrum of
a discrete-time signal is calculated using a fast Fourier transform (FFT).
A Fourier analysis of a periodic function refers to the extraction of a
series of sines and cosines. This analysis is called a Fourier series. FFT is a
mathematical method for transforming a function of time into a function
of frequency. It is very useful for time-dependent phenomena. The
resulting spectrum shows the frequency component of the given input
signal [9].
The following is an example.
127
Chapter 3 Programming SBCs
128
Chapter 3 Programming SBCs
Figure 3-19. The plots show the different spectrum graphs for a
sine signal
129
Chapter 3 Programming SBCs
The following example shows how to plot the coherence of two signals
using Python Matplotlib.
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
dt = 0.01
t = np.arange(0, 30, dt)
nse1 = np.random.randn(len(t)) # white noise 1
nse2 = np.random.randn(len(t)) # white noise 2
fig.tight_layout()
plt.show()
Random values are obtained and formed as an array using the NumPy
module. Two signals with a coherent part at 10 Hz and a random part are
created and are named s1 and s2. Then an empty figure is created with two
axes subplots. Then, the axes find coherence between the signals s1 and
s2.cohere function in Matplotlib.
130
Chapter 3 Programming SBCs
131
Chapter 3 Programming SBCs
Cross-Correlation Graph
Cross-correlation is a measurement that tracks the movements of two or
more sets of time series data relative to one another. It compares multiple
time series and determines how well they match up with each other and at
what point the best match occurs. It is also known as a sliding-dot product
or sliding-inner product. The time series data’s correlation coefficient range
is from –1 to +1. The closer the cross-correlation value is to 1, the more
likely the sets are identical.
The following is an example.
x, y = np.random.randn(2, 100)
fig, ax1 = plt.subplots()
ax1.xcorr(x, y, usevlines=True, maxlags=25, normed=True, lw=2)
ax1.set_title("Cross-Correlation")
ax1.set_xlabel("X values")
ax1.set_ylabel("Y values")
ax1.grid(True)
plt.show()
As usual, two sample lists with random values are created. The figure
and axes are formed. Then the values of the two lists are plotted in a
special manner using ax1.xcorr(). The Axes.xcorr() function plots the
correlation between x and y. Finally, the labels and titles are mentioned
and shown using plt.show().
Figure 3-21 shows the output.
132
Chapter 3 Programming SBCs
Autocorreleation Graph
Autocorrelation is a mathematical representation of the degree of
similarity between a given time series and a lagged version of itself over
successive time intervals. Autocorrelation, sometimes known as serial
correlation in the discrete-time case, is the correlation of a signal with a
delayed copy of itself as a delay function.
The following is an example.
133
Chapter 3 Programming SBCs
x, y = np.random.randn(2, 100)
fig, ax1 = plt.subplots()
ax1.acorr(x, usevlines=True, normed=True, maxlags=25, lw=2)
ax1.set_title("Auto-Correlation")
ax1.set_xlabel("X values")
ax1.set_ylabel("Y values")
ax1.grid(True)
plt.show()
134
Chapter 3 Programming SBCs
• Inches (default)
• Centimeters
• Pixels
135
Chapter 3 Programming SBCs
Scale
Two plots on the same axes with different left and right scales. The
trick is using two axes that share the same x axis. You can use separate
matplotlib.ticker formatters and locators as desired since the two axes are
independent. Such axes are generated by calling the Axes.twinx method.
Likewise, Axes.twiny is available to generate axes that share a y axis but
have different top and bottom scales.
136
Chapter 3 Programming SBCs
import numpy as np
import matplotlib.pyplot as plt
color = 'tab:blue'
ax2.set_ylabel('sin', color=color) # we already handled the
x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)
Two data lists are created using np.array. Then two subplots are
created, and the data lists are plotted in the same figure, identifying the
two graphs in different colors. The tight layout is then shown as a graph
using plt.show().
137
Chapter 3 Programming SBCs
Pie Charts
A pie chart is a circular statistical graphic divided into slices to illustrate
numerical proportions. In a pie chart, the arc length of each slice is
proportional to the quantity it represents. While it is named for its
resemblance to a pie that has been sliced, there are variations in how it can
be presented.
Pie charts are widely used in the business world and mass media. They
have been criticized, and many experts recommend avoiding them as
research has shown it is difficult to compare different sections of a given
pie chart or data across different pie charts. Pie charts can be replaced in
most cases by other plots, such as bar charts, box plots, and dot plots.
138
Chapter 3 Programming SBCs
The Matplotib API has a pie() function that generates a pie diagram
representing data in an array. The fractional area of each wedge is given by
x/sum(x).
If sum(x) < 1, then the values of x are given the fractional area directly,
and the array is not normalized.
The following is a sample program.
139
Chapter 3 Programming SBCs
140
Chapter 3 Programming SBCs
cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap([1, 2, 5, 6, 9, 10])
ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors,
wedgeprops=dict(width=size, edgecolor='w'))
ax.pie(vals.flatten(), radius=1-size, colors=inner_colors,
wedgeprops=dict(width=size, edgecolor='w'))
ax.set(aspect="equal", title='Pie plot with `ax.pie`')
plt.show()
141
Chapter 3 Programming SBCs
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 3),
subplot_kw=dict(aspect="equal"))
recipe = ["200 g Ice-cream",
"80 g sugar",
"100 g Cheese",
"250 g milk",
"100 g water"]
data = [float(x.split()[0]) for x in recipe]
ingredients = [x.split()[-1] for x in recipe]
def func(pct, allvals):
absolute = int(round(pct/100.*np.sum(allvals)))
return "{:.1f}%\n({:d} g)".format(pct, absolute)
wedges, texts, autotexts = ax.pie(data, autopct=lambda pct:
func(pct, data), textprops=dict(color="w"))
ax.legend(wedges, ingredients,
title="Ingredients",
loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1))
142
Chapter 3 Programming SBCs
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 3),
subplot_kw=dict(aspect="equal"))
recipe = ["200 g flour", "80 g sugar", "100 g butter",
"250 g milk", "100 g berries"]
143
Chapter 3 Programming SBCs
144
Chapter 3 Programming SBCs
Style Sheets
A web style sheet is a form of separation of presentation and content
for web design in which the markup of a webpage contains the page’s
semantic content and structure but does not define its visual layout. There
are many types of style sheets, and two of those are explained from the
style sheets.
145
Chapter 3 Programming SBCs
146
Chapter 3 Programming SBCs
147
Chapter 3 Programming SBCs
3D Graphs
A three-dimensional space is a geometric setting in which three values
are required to determine the position of an element. This is the informal
meaning of the term dimension. In geometry, a three-dimensional shape
can be defined as a solid figure, object, or shape with three dimensions:
length, width, and height.
import numpy as np
import matplotlib.pyplot as plt
ax = plt.figure().add_subplot(projection='3d')
# Plot a sin curve using the x and y axes.
x = np.linspace(0, 1, 100)
y = np.cos(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='curve in (x, y)')
# Plot scatterplot data (20 2D points per colour) on the x
and z axes.
colors = ('r', 'm', 'c', 'k')
# Fixing random state for reproducibility
np.random.seed(240)
x = np.random.sample(20 * len(colors))
y = np.random.sample(20 * len(colors))
c_list = []
for c in colors:
c_list.extend([c] * 20)
148
Chapter 3 Programming SBCs
149
Chapter 3 Programming SBCs
150
Chapter 3 Programming SBCs
151
Chapter 3 Programming SBCs
153
Chapter 3 Programming SBCs
3D Surfaces
The following is a sample program.
154
Chapter 3 Programming SBCs
Animation
Matplotlib has a very special animation function. The easiest way to make
a live animation in Matplotlib is to use the Animation classes.
155
Chapter 3 Programming SBCs
156
Chapter 3 Programming SBCs
The values get updated from the example.txt file and the graph moves
on according to the x axis.
Oscilloscope Live
Oscilloscopes test and display voltage signals as waveforms, which are
visual representations of voltage variation over time. The signals are
plotted on a graph showing how the signal changes. The vertical (y) access
represents the voltage measurement, and the horizontal (x) axis represents
time. One of the biggest advantages of oscilloscopes is that they give real-
time analysis. This means you get the right reading once you connect the
device to a power source. This oscilloscope graph can be implemented
using Matplotlib [10].
The following is an implementation.
import numpy as np
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython import display
157
Chapter 3 Programming SBCs
class Scope:
def __init__(self, ax, maxt=2, dt=0.02):
self.ax = ax
self.dt = dt
self.maxt = maxt
self.tdata = [0]
self.ydata = [0]
self.line = Line2D(self.tdata, self.ydata)
self.ax.add_line(self.line)
self.ax.set_ylim(-.1, 1.1)
self.ax.set_xlim(0, self.maxt)
self.ax.set_xlabel("Time in secs")
self.ax.set_ylabel("Voltage")
self.ax.set_title("Live Oscilloscope")
self.ax.figure.canvas.draw()
158
Chapter 3 Programming SBCs
def emitter(p=0.1):
"""Return a random value in [0, 1) with probability p,
else 0."""
while True:
v = np.random.rand(1)
if v > p:
yield 0.
else:
yield np.random.rand(1)
fig, ax = plt.subplots()
scope = Scope(ax)
The entire program is divided into two parts: the main and the class,
which has a few subfunctions defined within it.
There are two functions inside the Scope class: __init__ and update.
The __init__ function is the main function, in which the subplot is created,
and the x,y limits and labels are defined.
The update function plays a major role in animation. It plots graphs
accordingly with the incoming values generated by the emitter function.
Figure 3-36 shows the output.
159
Chapter 3 Programming SBCs
The values are updated in the plot, and since the x axis limit is set to a
particular value, the axis is updated accordingly.
Thus, with the help of the Matplotlib library from Python, many
types of graphs have been created and explained. Matplotlib is a Python
plotting package that makes it simple to create two-dimensional and
three-dimensional plots from data stored in various data structures,
including lists, NumPy arrays, and pandas dataframes. matplotlib.pyplot
is a collection of functions that make Matplotlib work like MATLAB. Each
Pyplot function changes a figure (e.g., creates a figure, creates a plotting
area in a figure, plots some lines in a plotting area, decorates the plot with
labels, etc.).
160
Chapter 3 Programming SBCs
References
[1] N. K. Sabat, U. C. Pati, B. R. Senapati, and S. K. Das, “An IoT Concept
for Region Based Human Detection Using PIR Sensors and FRED
Cloud,” 2019 IEEE 1st International Conference on Energy, Systems
and Information Processing (ICESIP), 2019, pp. 1–4, doi: 10.1109/
ICESIP46348.2019.8938286.
[2] Gabriel Gaspar, Peter Fabo, Michal Kuba, Juraj Ďuďák, and Eduard
Nemlaha, MicroPython as a Development Platform for IoT Applications,
2020, doi: 10.1007/978-3-030-51965-0_34.
[6] Biswajeeban Mishra and Attila Kertesz, The Use of MQTT in M2M and
IoT Systems: A Survey, IEEE Access, Volume 8, 2020.
[7] L. Goswami and P. Agrawal, “IOT based Diagnosing of Fault De-
tection in Power Line Transmission through GOOGLE Firebase da-
tabase,” 2020 4th International Conference on Trends in Electron-
ics and Informatics (ICOEI) (48184), 2020, pp. 415–420, doi: 10.1109/
ICOEI48184.2020.9143007.
161
Chapter 3 Programming SBCs
[10] W. Cai, B. Wang, and S. Zhang, "Remote Control and Data Acquisition
of Multiple Oscilloscopes Using LabVIEW," 2019 International Conference
on Smart Grid and Electrical Automation (ICSGEA), 2019, pp. 136–140,
doi: 10.1109/ICSGEA.2019.00039.
162
CHAPTER 4
Wireless Connectivity
in IoT
Introduction
The Internet of Things (IoT) starts with connecting to and gathering
information on nearby devices. The connectivity is attained wired and
wirelessly. The vast and multidimensional devices follow a star, mesh,
and hybrid topology with popular IoT wireless technologies. These
connections each have advantages and disadvantages. They can be
tailored through IoT user cases. Figure 4-1 compares the cost of wireless
technologies.
Cellular
Wi-fi
COST
Bluetooth
LTE-M
EC-GM
BLE NB-IOT
Zigbee
Z-Wave
RFID Lora
TECHNOLOGY
164
Chapter 4 Wireless Connectivity in IoT
consumables. On the other hand, LPWANs can only send small blocks of
data at a slow rate. This makes them better for applications that don’t need
a lot of bandwidth or need to be done quickly.
LPWANs aren’t all made equal. Today, there are licensed (NB-IoT,
LTE-M) and unlicensed (MYTHINGS, LoRa, Sigfox, etc.) technologies,
and each one performs differently in key network factors. For example,
licensed cellular-based LPWANs care most about how much power they
use, whereas unlicensed alternatives care more about the quality of service
and scalability. Standardization is another consideration if you want to
ensure long-term stability, security, and interoperability.
Let’s discuss what makes this group of wireless IoT technologies
important. The LoRa [2] tech stack is shown in Figure 4-2.
Application Layer
Figures 4-3 and 4-4 showcase the circuit connection of the LoRa sender
with the Arduino UNO and the LoRa receiver with the Arduino Nano.
165
Chapter 4 Wireless Connectivity in IoT
3.3V
#include <SPI.h>
#include <LoRa.h>
int counter = 0;
void setup() {
Serial.begin(9600);
while (!Serial);
166
Chapter 4 Wireless Connectivity in IoT
Serial.println("LoRa Sender");
if (!LoRa.begin(433E6)) {
Serial.println("Starting LoRa failed!");
while (1);
}
LoRa.setTxPower(20);
void loop() {
Serial.print("Sending packet: ");
Serial.println(counter);
counter++;
delay(5000);
}
//receiver code
#include <SPI.h>
#include <LoRa.h>
void setup() {
Serial.begin(9600);
while (!Serial);
Serial.println("LoRa Receiver");
167
Chapter 4 Wireless Connectivity in IoT
if (!LoRa.begin(433E6)) {
Serial.println("Starting LoRa failed!");
while (1);
}
}
void loop() {
// try to parse packet
int packetSize = LoRa.parsePacket();
if (packetSize) {
// received a packet
Serial.print("Received packet '");
RFID Protocol
Passive RFID [3] tags are different from most other digital radio systems
because they have limitations. Because the tags are cheap and don’t have
much intelligence, they can’t use advanced modulations like phase-shift
keying or quadrature-amplitude modulation (QAM). Also, turning off the
power from the reader reduces the power available to the tag, so the best
modulations for the reader are those in which the power is on most of the
168
Chapter 4 Wireless Connectivity in IoT
time. However, these modulations are not good at using the spectrum, so
they result in channels that are wide or data rates that are slow. The phase
or amplitude of the tag reflection can be changed. However, the small
tag reflection is added to large antenna reflections and reflections from
the environment, so the signal at the reader may change when the phase
or amplitude of the tag reflection changes. You can only hope to notice
changes in the antenna’s state, not its nature. You can count the number of
edges in the tag but can’t determine the absolute or differential phase or
amplitude. These rules must be considered when choosing tag and reader
symbols. Figure 4-5 shows how RFIDs are set up and the bands they use
to talk.
Passive A ctive
169
Chapter 4 Wireless Connectivity in IoT
Arduino Code
#include <SPI.h>
#include <MFRC522.h>
constexpr uint8_t RST_PIN = 9; // Configurable, see typical
pin layout above
constexpr uint8_t SS_PIN = 10; // Configurable, see typical
pin layout above
MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class
MFRC522::MIFARE_Key key;
void setup() {
Serial.begin(9600);
SPI.begin(); // Init SPI bus
rfid.PCD_Init(); // Init MFRC522
170
Chapter 4 Wireless Connectivity in IoT
void loop() {
171
Chapter 4 Wireless Connectivity in IoT
172
Chapter 4 Wireless Connectivity in IoT
/**
* Helper routine to dump a byte array as dec values to Serial.
*/
void printDec(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], DEC);
}
}
The data from the passive tag can be seen in the serial monitor after
executing this code.
Zigbee
Application Layer Alliance
Physical Layer
173
Chapter 4 Wireless Connectivity in IoT
Figure 4-8. XBee radio connected with serial data transfer with
XBee radio
//Configuration
Code //
int led = 13;
int received = 0;
int i;
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
received = Serial.read();
174
Chapter 4 Wireless Connectivity in IoT
Once the code is executed on both the sender and receiver sides, a
blinking LED can be observed on the receiver side.
175
Chapter 4 Wireless Connectivity in IoT
RFcomm SDP
L2CAP
Control and Audio
HCI
Link Manager
Baseband
Radio
char inputByte;
void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
176
Chapter 4 Wireless Connectivity in IoT
void loop() {
while(Serial.available()>0){
inputByte= Serial.read();
Serial.println(inputByte);
if (inputByte=='Z'){
digitalWrite(13,HIGH);
}
else if (inputByte=='z'){
digitalWrite(13,LOW);
}
}
}
177
Chapter 4 Wireless Connectivity in IoT
+5V
2.2k
GND
VCC
int state = 0;
const int pin = 9;
float gpslat, gpslon;
178
Chapter 4 Wireless Connectivity in IoT
TinyGPS gps;
SoftwareSerial sgps(4, 5);
SoftwareSerial sgsm(2, 3);
void setup()
{
sgsm.begin(9600);
sgps.begin(9600);
}
void loop()
{
sgps.listen();
while (sgps.available())
{
int c = sgps.read();
if (gps.encode(c))
{
gps.f_get_position(&gpslat, &gpslon);
}
}
if (digitalRead(pin) == HIGH && state == 0) {
sgsm.listen();
sgsm.print("\r");
delay(1000);
sgsm.print("AT+CMGF=1\r");
delay(1000);
/*Replace XXXXXXXXXX to 10 digit mobile number &
ZZ to 2 digit country code*/
sgsm.print("AT+CMGS=\"+ZZXXXXXXXXXX\"\r");
delay(1000);
179
Chapter 4 Wireless Connectivity in IoT
180
Chapter 4 Wireless Connectivity in IoT
2.2k
//Arduino code
#include <ESP8266WiFi.h>
// esp8266 library
#include <FirebaseArduino.h>
// firebase library
182
Chapter 4 Wireless Connectivity in IoT
void loop() {
fireStatus = Firebase.getString("LED_STATUS");
// get ld status input
from firebase
183
Chapter 4 Wireless Connectivity in IoT
R
eferences
[1] Q. M. Qadir, T. A. Rashid, N. K. Al-Salihi, B. Ismael, A. A. Kist, and
Z. Zhang, “Low Power Wide Area Networks: A Survey of Enabling
Technologies, Applications and Interoperability Needs,” IEEE Access, vol. 6,
2018, pp. 77454–77473. doi: 10.1109/ACCESS.2018.2883151.
184
Chapter 4 Wireless Connectivity in IoT
[3] R. Rayhana, G. Xiao, and Z. Liu, “RFID Sensing Technologies for Smart
Agriculture,” IEEE Instrumentation & Measurement Magazine, vol. 24, no.
3, May 2021, pp. 50–60. doi: 10.1109/MIM.2021.9436094.
[6] Ma May Thet Htar and Ma Hnin Yu Myaing, “GSM Based Home
Automation System Using Arduino,” International Journal of Trend in
Scientific Research and Development (IJTSRD), vol. 3, no. 5, August 2019,
pp. 1666–1669. https://doi.org/10.31142/ijtsrd26806
[7] Wu-Jeng Li, Chiaming Yen, You-Sheng Lin, Shu-Chu Tung, and Shih-
Miao Huang, “JustIoT Internet of Things based on the Firebase Real-time
Database,” IEEE, 2018. doi: 10.1109/SMILE.2018.8353979.
[8] Jonathan Álvarez Ariza and Heyson Baez, “Understanding the role of
single-board computers in engineering and computer science education:
A systematic literature review,” Computer Applications in Engineering
Education, 2021.
185
CHAPTER 5
The Internet
of Things Through
the Raspberry Pi
Introduction
Raspberry Pi is an elegant, low-cost single-board computer mainly used
for rapid prototyping and building small IoT applications [1]. Together
with sensors and other communication modules, it can play an important
role in making decisions in a smart environment. Figure 5-1 showcases
the different Raspberry Pi configurations, communication modules, and
available ports.
188
Chapter 5 The Internet of Things Through the Raspberry Pi
In this chapter,
189
Chapter 5 The Internet of Things Through the Raspberry Pi
ssh-keygen -t rsa
ssh-copy-id <username@hostip>
The public keys from the host must be copied to all clients. The
preceding command is run on each client to do this. Each client’s IP
address is given on the host computer, and each client’s IP address is
returned to the host.
MPI is installed by running the following scripts.
mpiexec -n 1 hostname
190
Chapter 5 The Internet of Things Through the Raspberry Pi
//C code
#include <mpi.h>
#include <stdio.h>
MPI_Comm_size(MPI_COMM_WORLD, &siz);
MPI_Comm_rank(MPI_COMM_WORLD, &r);
MPI_Get_processor_name(name, & length);
191
Chapter 5 The Internet of Things Through the Raspberry Pi
\\ Python Script
from mpi4py import MPI
import sys
siz = MPI.COMM_WORLD.Get_size()
r = MPI.COMM_WORLD.Get_rank()
name = MPI.Get_processor_name()
192
Chapter 5 The Internet of Things Through the Raspberry Pi
data that was sent in parallel. So, the sender program won’t keep running
while it waits for the results it needs to keep going.
Generic Python objects can talk to each other through the send(),
recv(), and sendrecv() methods. On the other hand, methods like Send()
and Recv() send and receive large data arrays, such as NumPy arrays.
Some types of calculations may need to be done faster, which is achieved
by making sure that the systems can talk to each other without waiting
for a response. This means they can send and share data for calculation
without waiting for a reply.
MPI also has functions that don’t block this kind of communication.
A call-reception function starts the action, and a control function lets you
determine if such a request was completed. The functions for getting calls
are lsend() and lrecv (). These functions give back a Request object, which
is a unique way to identify the operation that was asked for. Once this
operation has been sent, you can use control functions like Test(), Wait(),
and Cancel() from the Request class to see how well it works.
Persistent Communication
Non-blocking communication requests are run repeatedly since they
are in a loop. Using persistent communications can improve the code’s
performance in these situations. Send init() and Recvinit() are the
functions of the mpi4py module that takes care of this job. They are part
of the Comm class, and when they return a request object, they make a
persistent request.
Broadcasting
In broadcasting, the master node communicates the data to all the
other connected nodes. Figure 5-2 illustrates the same copy of the data
communicated to all the nodes in the cluster.
193
Chapter 5 The Internet of Things Through the Raspberry Pi
com = MPI.COMM_WORLD
r = comm.Get_rank()
if r == 0;
info={'key1': [1, 2, 1+2j],
'key2':('111','aaa')}
else:
info = None
info = com.bcast(data, root=0)
print('from'+str(r))
print(info)
The code must be copied to all the cluster members in the network to
broadcast the data.
194
Chapter 5 The Internet of Things Through the Raspberry Pi
Scattering
Scattering is a way for the master node to break up a data structure like
a list and send each part to a different system in the cluster as a separate
message. Figure 5-3 showcases the scattering of the data between the
clusters.
The code in Listing 5-4 must be copied to all the cluster members in
the network.
com = MPI.COMM_WORLD
siz = comm.Get_size()
r = comm.Get_rank()
if r == 0;
info = [(i+1)**2 for i in range(siz)]
else:
info = None
info = com.scatter(info, root=0)
assert info == (r+1)**2
195
Chapter 5 The Internet of Things Through the Raspberry Pi
Gathering
Gathering is almost the polar opposite of scattering. In this instance, the
master node is initialized and receives all data from the other cluster
nodes. Figure 5-4 shows the gathering mechanism in clusters.
com = MPI.COMM_WORLD
siz = comm.Get_size()
r = comm.Get_rank()
info = (r+1)**2
info = com.gather(info, root=0)
if r == 0;
for i in range(siz);
assert info[i] == (i+1)**2
else:
assert info is None
196
Chapter 5 The Internet of Things Through the Raspberry Pi
197
Chapter 5 The Internet of Things Through the Raspberry Pi
/rpiWbserver
/stat
/templ
Run the Python script shown in Listing 5-6 to check the button press in
the Flask web server.
@app.route("/")
def index():
# Read Sensors Status
but = GPIO.input(but)
templateData = {
'title' : 'GPIO status',
'button' : but,
}
return render_template('index.html', **templateData)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
198
Chapter 5 The Internet of Things Through the Raspberry Pi
// Template code
<!DOCTYPE html>
<head>
<title>{{ title }}</title>
<link rel="stylesheet" href='../static/style.css'/>
</head>
<body>
<h1>{{ title }}</h1>
<h2>Button pressed: {{ button }}</h1>
</body>
</html>
References
[1] G. R. Kanagachidambaresan, “Node-Red Programming and Page
GUI Builder for Industry 4.0 Dashboard Design,” Role of Single Board
Computers (SBCs) in Rapid IoT Prototyping, Springer, 2021, pp. 121–140.
199
Chapter 5 The Internet of Things Through the Raspberry Pi
[3] Rajkumar Buyya and Satish Narayana Srirama, “Wiley Series on Parallel
and Distributed Computing,” in Fog and Edge Computing: Principles and
Paradigms, Wiley, 2019, pp. 1–4. doi: 10.1002/9781119525080.scard.
200
CHAPTER 6
Home Electrification
and Node-RED
Node-RED [1] is a tool that uses flows and is written in Node.js. It takes
up little memory and works on the Raspberry Pi, which makes it a great
system for home automation projects [2]. Raspberry Pi comes with Node-
RED installed, but you may need to upgrade it.
This chapter covers
node-red start
202
Chapter 6 Home Electrification and Node-RED
203
Chapter 6 Home Electrification and Node-RED
204
Chapter 6 Home Electrification and Node-RED
205
Chapter 6 Home Electrification and Node-RED
Figure 6-7 shows the home screen to control the relays connected via
a local network. The same dashboard can be synchronized with Google
Firebase or other cloud platforms to operate the device through the
Internet.
206
Chapter 6 Home Electrification and Node-RED
207
Chapter 6 Home Electrification and Node-RED
References
[1] A. Rajalakshmi and H. Shahnasser, “Internet of Things using Node-RED
and Alexa,” in 2017 17th International Symposium on Communications
and Information Technologies (ISCIT), 2017, pp. 1–4. doi: 10.1109/
ISCIT.2017.8261194.
208
CHAPTER 7
Supply Chain
Management: Industry
4.0 and MQTT
Applications
Introduction
Supply chain management [1] [2] and creating transparency between
the shop floor workers and suppliers are achieved through Industry
4.0 standards. This chapter mainly deals with MQTT-based production
system monitoring and software design with the help of single-board
computers (SBCs) [3] [6]. An application is created in Python to send
live information to the assembly unit from the Original Equipment
Manufacturer (OEMs) [4] in a supply chain. A report must be generated
at the end of the shift, and an automatic email must be sent to higher
officials to maintain transparency throughout the supply chain and make
production as economical and efficient as possible. Figure 7-1 illustrates
the proposed model.
Working Principle
The application’s user interface is created with Python’s Tkinter library.
Individual modules are designed to complete certain tasks. The first is a
timer module that counts down the time in decrements and alerts you when
a shift is over, and an automatic email is sent to the appropriate authorities.
The shift information is in an Excel file attached to the email. The smtplib
and email packages in Python enable the automatic mail-send module.
210
Chapter 7 Supply Chain Management: Industry 4.0 and MQTT Applications
211
Chapter 7 Supply Chain Management: Industry 4.0 and MQTT Applications
17. qwe=[0,0,0,'0']
18.
19. defon_connect(client, userdata, flags, rc,
properties=None):
20. print("Connection Success! Received with code
%s."%rc)
21.
22. # with this callback you can see if your publish was
successful
23. defon_publish(client, userdata, mid, properties=None):
24. print("mid: "+str(mid))
25.
26. # print which topic was subscribed to
27. defon_subscribe(client, userdata, mid, granted_qos,
properties=None):
28. print("Subscribed: "+str(mid) +" "+str(granted_qos))
29.
30. defon_message(client, userdata, msg):
31. print(msg.topic+" "+str(msg.qos) +" "+str(msg.
payload))
32.
33. #Sends Automatic Mail once the Shift gets over
34. defautomaticEmail():
35. sender_email="mayoisnicee@gmail.com"
36. sender_pass="Mayonnaise24"
37. receiver_email="balakumarbk03@gmail.com"
38.
39. msg=EmailMessage()
40. msg['Subject'] ="REPORT"
41. msg['From'] =sender_email
42. msg['To'] =receiver_email
212
Chapter 7 Supply Chain Management: Industry 4.0 and MQTT Applications
213
Chapter 7 Supply Chain Management: Industry 4.0 and MQTT Applications
214
Chapter 7 Supply Chain Management: Industry 4.0 and MQTT Applications
96. df.to_excel(writer, sheet_
name='Sheet1',index =False)
97. workbook =writer.book
98. worksheet =writer.sheets['Sheet1']
99. worksheet.set_column('A:G',25)
100. writer.save()
101. print("Report Generated Successfully on "+dt_string)
102.
103.
104.
105. #Shift Runtime
106. defshiftRun():
107. l =[]
108. time_sec=int(t.get())
109. count =0; good =0; bad =0
110. whiletime_sec:
111. mins, secs=divmod(time_sec, 60)
112. timeformat='{:02d}:{:02d}'.format(mins, secs)
113. #print(timeformat, end='\r')
114. l.append(timeformat)
115. #print(l[-1])
116. count +=1
117. ifrandom.randint(0,1):
118. good +=1
119. else:
120. bad +=1
121. Label(root, text=l[-1], font ='arial 15 bold').
place(x=800, y=50)
122. Label(root, text="Production Count:
"+str(count), font ='arial 20 bold').
place(x=20, y=360)
215
Chapter 7 Supply Chain Management: Industry 4.0 and MQTT Applications
216
Chapter 7 Supply Chain Management: Industry 4.0 and MQTT Applications
147. client.on_publish=on_publish
148.
149. root =Tk()
150. root.geometry('1000x500')
151. #production_name = input("Production Name(Eg: Bulb/
Indicator/Housing/Electrical): ")
152. Label(root, text ='Indicator Production', font
='arial 20 bold').pack()
153.
154. #Starting Protocols
155. Label(root, font ='arial 15 bold', text ='Set
Time').place(x =20,y =50)
156. t =Entry(root,width=15)
157. t.place(x=180, y=55)
158. Label(root, font ='arial 15 bold', text ='Shift
Number').place(x =20,y =80)
159. number =Entry(root,width=15)
160. number.place(x=180, y=85)
161. Label(root, font ='arial 15 bold', text
='Supervisor').place(x =20,y =110)
162. name =Entry(root,width=15)
163. name.place(x=180,y=115)
164.
165. #Start Button
166. Button(root, text='START', bd='5', command
=shiftRun, font ='arial 10 bold').place(x=80, y=160)
167.
168. #Generate Report Button
169. Button(root, text='Generate Report', bd='5',
command =generateReport, font ='arial 10 bold').
place(x=800, y=400)
170.
217
Chapter 7 Supply Chain Management: Industry 4.0 and MQTT Applications
171.
172. #Quit Button
173. ttk.Button(root, text="Quit", command=root.destroy).
place(x=450,y=450)
174. root.mainloop()
175. print("Press 'Ctrl+C' to close the application.")
176. client.loop_forever()
177.
178.
179. exceptKeyboardInterrupt:
180. print("Byeeee!!")
181. pass
218
Chapter 7 Supply Chain Management: Industry 4.0 and MQTT Applications
14. # with this callback you can see if your publish was
successful
15. defon_publish(client, userdata, mid, properties=None):
16. print("mid: "+str(mid))
17.
18. # print which topic was subscribed to
19. defon_subscribe(client, userdata, mid, granted_qos,
properties=None):
20. print("Subscribed: "+str(mid) +" "+str(granted_qos))
21.
22. # print message, useful for checking if it was successful
23. defon_message(client, userdata, msg):
24. print(msg.topic+" "+str(msg.qos) +" "+str(msg.
payload))
25. topic =msg.topic
26. payload =msg.payload
27. if'Crompton_Good'intopic:
28. #print("Update Crompton Label: ",payload)
29. Label(root, text ='Crompton Production:
'+str(payload) , font ='arial 20 bold').
place(x=40,y=200)
30.
31. elif'Bosch_Good'intopic:
32. #print("Update Bosch Label: ",payload)
33. Label(root, text ='Bosch Production:
'+str(payload), font ='arial 20 bold').
place(x=40,y=80)
34. root.update()
35.
36.
37. # using MQTT version 5 here, for 3.1.1: MQTTv311,
3.1: MQTTv31
219
Chapter 7 Supply Chain Management: Industry 4.0 and MQTT Applications
220
Chapter 7 Supply Chain Management: Industry 4.0 and MQTT Applications
62.
63. #ttk.Button(root, text="Quit", command=root.destroy).
place(x=450,y=450)
64. client.loop_forever()
Figure 7-3 shows the full dashboard of the host industries. The
production count, including both the good and the defective products, is
tabulated to provide the shop floor output.
221
Chapter 7 Supply Chain Management: Industry 4.0 and MQTT Applications
Figure 7-4 shows the round-trip time it takes to update the consumer
dashboard through 3G and 4G communication modules.
5RXQGWULSWLPHLQPVHF
* *
222
Chapter 7 Supply Chain Management: Industry 4.0 and MQTT Applications
Summary
This chapter discussed Python-based supply chain management through
the MQTT protocol. The data is shared in 3G and 4G modules, and the
response time is recorded for delay analysis. Image processing–based kit
design for Industry 4.0 is discussed in the next chapter.
References
[1] Devendra A. Patil, “The Study of Industry 4.0 and Its Impact on Supply
Chain Management,” International Research Journal of Engineering and
Technology, vol. 7, 2020.
[5] Biswajeeban Mishra and Attila Kertesz, “The Use of MQTT in M2M and
IoT Systems: A Survey,” IEEE Access, vol. 8, 2020.
[6] Jonathan Álvarez Ariza and Heyson Baez, “Understanding the role of
single-board computers in engineering and computer science education:
A systematic literature review,” Computer Applications in Engineering
Education, 2021.
223
CHAPTER 8
Raspberry Pi–Based
Go/No-Go Kit Design
Using the RPi Camera
and Image Processing
Algorithms
Introduction
Image-based recommendation systems [1] [2] are widely used in
many industries to approve completed products and validate the
products supplied by their suppliers. These consumer industries share
specifications, and in many cases, they share the precise tool to operate
and measure so that the quality of the product is high. High-quality
products provide a high mean time to fail, often increasing customer
and consumer trust. The devices and products in industries differ, and
it is difficult to design an image processing–based recommendation
system. With improvements in single-board computers and with the help
of Python programs [3], it is easy to build a custom tool to monitor and
validate production activities.
226
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
to find a problem without taking samples or harming it irreparably.
The classifications of NDTs are a visual-based method, dye penetrant
inspection, radiography, ultrasonic testing, eddy current technique, and
thermography. They are predominantly employed in the realm of aviation.
Artificial intelligence, fuzzy math, expert systems, and fault tree
analysis are classical fault detection methods derived from signal
processing. The sensor embedded in the signal acquisition card limits
the data quality for those approaches. In a real-world scenario, external
elements such as heat, humidity, and electromagnetic radiation affect the
sensor. As a result, sensor failure is one of the most common reasons for
system failure in industrial robots [6].
In the automotive industry, industrial robots are used for welding,
spraying, handling, and other applications. For each type of robot,
manufacturers from Japan, Germany, the United States, and China provide
a variety of models. Robot communication protocols are inherently
complicated, and no single consistent standard exists.
Furthermore, because the interior environment’s electromagnetic
interference shielding is often disregarded, thermal radiation and other
influences might cause erroneous measurements with the monitoring
system embedded in the execution system. Other variables that contribute
to robot failure, besides signal interference, include device aging, metal
fatigue, and a lack of maintenance.
Industrial robots [7] [8] are a significant production tool for
intelligent manufacturing and advanced industry. India is a significant
manufacturing nation with many industrial robots in use. Unfortunately,
industrial robots may mistakenly hurt surrounding workers while
functioning at high intensity, high workload, and for lengthy periods
of time, resulting in irreversible losses. The typical defect detection
approach for robots mostly depends on the sensors, signal processing, and
mathematical analysis.
227
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
The following are the disadvantages of such a system due to it being
pricey and sensitive to sensor readings.
228
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
Figure 8-2 provides the GUI design and user interface to classify the
drill hole with standard-size coins. The permissible amount of tolerance
to accept the job piece is 0.9%. When the image-based classification
identifies the amount of tolerance with a 96% confidence level, the output
is communicated to the servo mechanism with GPIO pins to move the job
piece further into the conveyer system for additional machining/assembly.
The GUI is designed with the Tkinter package. Figure 8-2 shows the size of
the hole measured by the classification model.
229
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
230
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
except ImportError:
import tkinter.ttk as ttk
py3 = True
import industry_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
industry_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(rt, *args, **kwargs):
'''Starting point when module is imported by
another module.
Correct form of call: 'create_Toplevel1(root, *args,
**kwargs)' .'''
global w, w_win, root
#rt = root
root = rt
w = tk.Toplevel (root)
top = Toplevel1 (w)
industry_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
231
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the
toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
top.geometry("600x450+342+122")
top.minsize(116, 1)
top.maxsize(1284, 782)
top.resizable(1, 1)
top.title("New Toplevel")
top.configure(background="#d9d9d9")
self.Canvas1 = tk.Canvas(top)
self.Canvas1.place(relx=0.217, rely=0.067,
relheight=0.518, relwidth=0.588)
self.Canvas1.configure(background="#d9d9d9")
self.Canvas1.configure(borderwidth="2")
self.Canvas1.configure(insertbackground="black")
self.Canvas1.configure(relief="ridge")
self.Canvas1.configure(selectbackground="blue")
self.Canvas1.configure(selectforeground="white")
self.Label1 = tk.Label(top)
self.Label1.place(relx=0.067, rely=0.778, height=21,
width=100)
self.Label1.configure(background="#d9d9d9")
232
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''GO COUNT 20''')
self.Label1_1 = tk.Label(top)
self.Label1_1.place(relx=0.7, rely=0.778, height=21,
width=100)
self.Label1_1.configure(activebackground="#f9f9f9")
self.Label1_1.configure(activeforeground="black")
self.Label1_1.configure(background="#d9d9d9")
self.Label1_1.configure(disabledforeground="#a3a3a3")
self.Label1_1.configure(foreground="#000000")
self.Label1_1.configure(highlightbackground="#d9d9d9")
self.Label1_1.configure(highlightcolor="black")
self.Label1_1.configure(text='''NO- GO COUNT 1''')
if __name__ == '__main__':
vp_start_gui()
Below code shows the python code support module for size verification.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 5.4
# in conjunction with Tcl version 8.6
# Dec 16, 2021 10:34:30 PM +0530 platform: Windows NT
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
233
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def destroy_window():
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
if __name__ == '__main__':
import APRESS9
industry.vp_start_gui()
234
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="path to the input image")
ap.add_argument("-w", "--width", type=float, required=True,
help="width of the left-most object in the image (in
inches)")
args = vars(ap.parse_args())
# resize image
image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
235
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
# 'pixels per metric' calibration variable
(cnts, _) = contours.sort_contours(cnts)
pixelsPerMetric = None
236
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
(tltrX, tltrY) = midpoint(tl, tr)
(blbrX, blbrY) = midpoint(bl, br)
# compute the midpoint between the top-left and top-
right points,
# followed by the midpoint between the top-righ and
bottom-right
(tlblX, tlblY) = midpoint(tl, bl)
(trbrX, trbrY) = midpoint(tr, br)
# draw the midpoints on the image
cv2.circle(orig, (int(tltrX), int(tltrY)), 5, (255,
0, 0), -1)
cv2.circle(orig, (int(blbrX), int(blbrY)), 5, (255,
0, 0), -1)
cv2.circle(orig, (int(tlblX), int(tlblY)), 5, (255,
0, 0), -1)
cv2.circle(orig, (int(trbrX), int(trbrY)), 5, (255,
0, 0), -1)
# draw lines between the midpoints
cv2.line(orig, (int(tltrX), int(tltrY)), (int(blbrX),
int(blbrY)), (255, 0, 255), 2)
cv2.line(orig, (int(tlblX), int(tlblY)), (int(trbrX),
int(trbrY)), (255, 0, 255), 2)
237
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
if pixelsPerMetric is None:
pixelsPerMetric = dB / args["width"]
([HFXWLRQ7LPH VHF
5SL% 5SL*%5$0 5SL*%5$0
([HFXWLRQ7LPH VHF
238
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
Figure 8-3 compares the execution time of the code in different
Raspberry Pi models. The Raspberry Pi 4 with 4 GB RAM executes fastest,
and the Raspberry Pi 3 executes slower than the other models.
A smart farming–based project with single-board computers is
discussed in the next chapter. Different water quality sensors and
interfacing with the single-board computers and calibrations are also
discussed.
References
[1] P. Yin and L. Zhang, “Image Recommendation Algorithm Based on
Deep Learning,” IEEE Access, vol. 8, 2020, pp. 132799–132807. doi: 10.1109/
ACCESS.2020.3007353.
[3] A. Saxena, M. Tyagi, and P. Singh, “Digital Outing System Using RFID
And Raspberry Pi with MQTT Protocol,” 2018 3rd International Conference
on Internet of Things: Smart Innovation and Usages (IoT-SIU), 2018,
pp. 1–4. doi: 10.1109/IoT-SIU.2018.8519923.
239
CHAPTER 8 RASPBERRY PI–BASED GO/NO-GO KIT DESIGN USING THE RPI CAMERA
AND IMAGE PROCESSING ALGORITHMS
[6] Karthick Thiyagarajan, Sarath Kodagoda, Linh Van Nguyen, and
Ravindra Ranasinghe, “Sensor Failure Detection and Faulty Data
Accommodation Approach for Instrumented Wastewater Infrastructures,”
IEEE Access, vol. 6.
240
CHAPTER 9
Programming
Water-Quality Sensors
Introduction
Water quality [1] is mainly determined by various water quality
parameters, such as the following.
• pH
• DO
• Turbidity
• Salinity
• TDS
• Water Temperature
242
Chapter 9 Programming Water-Quality Sensors
(Source: http://iitk.ac.in/iwd/wq/drinkingwater.htm )
243
Chapter 9 Programming Water-Quality Sensors
The water quality parameters suitable for irrigation purposes are listed
in Table 9-3.
244
Chapter 9 Programming Water-Quality Sensors
245
Table 9-4. Programming water quality sensors with arduino
246
Sensors Sensor Image Voltage Connectivity Detection Pin Arduino Code
Chapter 9
void loop()
Programming Water-Quality Sensors
{
p H_Value =
analogRead(A0);
V oltage = pH_Value *
(5.0 / 1023.0);
S erial.
println(Voltage);
delay(500);
}
DO +3.3V- Analog 0-20mg/L VCC-3.3V #include <Arduino.h>
+5.5V GND-GND
#define VREF
Analog
5000//VREF(mv)
output-A1
#define ADC_RES
1024//ADC Resolution
uint32_t raw;
void setup()
{
S erial.
begin(115200);
Chapter 9
void loop()
{
r aw=analogRead(A1);
Serial.
println("raw:
\t"+String(raw)+"\
tVoltage(mv)"+String
(raw*VREF/ADC_RES));
delay(1000);
}
247
Programming Water-Quality Sensors
(continued)
Table 9-4. (continued)
248
Sensors Sensor Image Voltage Connectivity Detection Pin Arduino Code
Chapter 9
S erial.println
("Sensor Output
(V):");
S erial.println
(voltage);
Serial.println();
delay(1000);
}
Salinity 5V Analog 0-50ppt (0- VCC-5V int potPin = 0;
50,000ppm) GND-GND float refvoltage = 5.0;
A0-A0
voidsetup()
{
Serial.begin(9600);
S erial.println("Sal
sensor ");
}
voidloop()
{
Chapter 9
249
Programming Water-Quality Sensors
(continued)
Table 9-4. (continued)
250
Sensors Sensor Image Voltage Connectivity Detection Pin Arduino Code
Chapter 9
Serial.print("Analog
in reading: ");
Serial.print(aRead);
Serial.print(" -
voltage: ");
Serial.
println(voltage , 3);
Programming Water-Quality Sensors
Serial.print(" -
Calculated ppt: ");
S erial.println(ppt,
2);
delay(500);
}
TDS 3.3V-5.5V Analog 0-1000ppm VCC-5V #include <EEPROM.h>
GND-GND #include "GravityTDS.h"
Analog output-
#define TdsSensorPin A1
any analog
GravityTDS gravityTds;
output
float temperature =
25,tdsValue = 0;
void setup()
{
Serial.begin(115200);
gravityTds.
Chapter 9
setPin(TdsSensorPin);
gravityTds.
setAref(5.0);
//reference voltage
on ADC, default 5.0V
on Arduino UNO
gravityTds.
setAdcRange(1024);
//1024 for 10bit ADC;
4096 for 12bit ADC
(continued)
251
Programming Water-Quality Sensors
Table 9-4. (continued)
252
Sensors Sensor Image Voltage Connectivity Detection Pin Arduino Code
Chapter 9
gravityTds.begin();
//initialization
}
void loop()
{
//temperature =
readTemperature();
//add your temperature
sensor and read it
Programming Water-Quality Sensors
gravityTds.set
Temperature
(temperature);
// set the temperature
and execute temperature
compensation
gravityTds.update();
//sample and calculate
tdsValue = gravityTds.
getTdsValue();
// then get the value
Serial.
print(tdsValue,0);
Serial.
println("ppm");
delay(1000);
}
//Constants
Data-D2
#define DHTPIN 2
// what pin we're
connected to
#define DHTTYPE DHT11
// DHT 11 (AM2302)
// Initialize DHT
sensor for normal
16mhz Arduino
DHT dht(DHTPIN,
DHTTYPE);
253
Programming Water-Quality Sensors
(continued)
Table 9-4. (continued)
254
Sensors Sensor Image Voltage Connectivity Detection Pin Arduino Code
Chapter 9
//Variables
int chk;
float hum; //Stores
humidity value
float temp; //Stores
temperature value
void setup()
{
Serial.begin(9600);
Programming Water-Quality Sensors
dht.begin();
}
void loop()
{
//Read data and
store it to variables
hum and temp
hum = dht.
readHumidity();
temp= dht.
readTemperature();
//Print temp and
humidity values to
serial monitor
Serial.
print("Humidity: ");
Serial.print(hum);
Serial.print(" %,
Temp: ");
Serial.print(temp);
Chapter 9
Serial.println("
Celsius");
delay(2000);
//Delay 2 sec.
}
255
Programming Water-Quality Sensors
Table 9-5. Python based interface for water quality sensors
256
Sensors Python Code
Chapter 9
value1 = 0
value2 = 6.5
value3 = 7.5
value4 = 14
response = mybolt.serialRead('10')
print response
while True:
print("Reading Sensor Value")
response = mybolt.serialRead('10') #Fetching the value from Arduino
data = json.loads(response)
ph_value = data['value'].rstrip()
print("pH Valueis:"+str(data['value']))
try:
if ph_value > value1 and ph_value < value2:
print("Making request to send SMS")
r esponse = sms.send_sms("The liquid is ACIDIC. pH value of the liquid
is:"+str(ph_value))
print("Response recieved:"+ste(response.status))
elif ph_value > value2 and ph_value < value3:
print("Making request to send SMS")
r esponse = sms.send_sms("The liquid is NEUTRAL. pH value of the
liquid is:"+str(ph_value))
Chapter 9
print("Response recieved:"+ste(response.status))
elif ph_value > value3 and ph_value < value4:
print("Making request to send SMS")
r esponse = sms.send_sms("The liquid is ALKALINE. pH value of the
liquid is:"+str(ph_value))
print("Response recieved:"+ste(response.status))
except Exception as e:
print("Error occured: Below are the details")
print(e)
time.sleep(100) #reads sensor value for every 100 seconds
(continued)
257
Programming Water-Quality Sensors
Table 9-5. (continued)
258
Sensors Python Code Chapter 9
DO
turbidity Importtime
importboard
importbusio
importadafruit_ads1x15.ads1015asADS
fromadafruit_ads1x15.analog_inimportAnalogIn
# Create the I2C bus
i2c=busio.I2C(board.SCL,board.SDA)
# Create the ADC object using the I2C bus
ads=ADS.ADS1015(i2c)
Programming Water-Quality Sensors
class GroveTDS:
@property
def TDS(self):
value = self.adc.read(self.channel)
if value != 0:
voltage = value*5/1024.0
t dsValue = (133.42/voltage*voltage*voltage-255.86*voltage*voltage+857
.39*voltage)*0.5
return tdsValue
else:
return 0
(continued)
259
Programming Water-Quality Sensors
Table 9-5. (continued)
260
Sensors Python Code
Chapter 9
Grove = GroveTDS
def main():
if len(sys.argv) < 2:
print('Usage: {} adc_channel'.format(sys.argv[0]))
sys.exit(1)
sensor = GroveTDS(int(sys.argv[1]))
print('Detecting TDS...')
while True:
print('TDS Value: {0}'.format(sensor.TDS))
Programming Water-Quality Sensors
time.sleep(1)
if __name__ == '__main__':
main()
Temperature import serial
import re
import csv
import numpy as np
import matplotlib.pyplot as plt
from drawnow import *
sim_time = 10
# Initializing Lists
# Data Collection
data_log = []
line_data = []
(continued)
261
Programming Water-Quality Sensors
Table 9-5. (continued)
262
Sensors Python Code
Chapter 9
plt.ion() #Tell matplotlib you want interactive mode to plot live data
263
Programming Water-Quality Sensors
Chapter 9 Programming Water-Quality Sensors
References
[1] A. N. Prasad, K. Mamun, F. Islam, and H. Haqva, “Smart Water Quality
Monitoring System,” IEEE, 2015. doi: 10.1109/APWCCSE.2015.7476234.
264
CHAPTER 10
IoT-Based Shrimp
Farming
Shrimp farming is an aquaculture business [1] that can occur in saltwater
or freshwater [2]. Ocean shrimp farming is a very old industry popular
in many Asian countries. Prior to ten years ago, shrimp were usually
considered a second crop in traditional fish farming systems. The shrimp
caught in salt beds, coastal paddy fields, or brackish water fishponds are
left to grow until they are big enough to sell, and then they are harvested
as a secondary crop. But in recent years, farmers have started growing
shrimp as their main crop. Many farmers have made shrimp farms in their
rice fields, fish ponds, and salt beds. Nowadays, most shrimp farmers [3]
use modern methods to raise shrimp. A small piece of land can be used to
make a lot of food.
Shrimp farming [4] in freshwater is also growing in popularity. In 2010,
about 670,000 tons of freshwater prawns were raised around the world, the
majority in China.
The influencing factors of shrimp farming are shown in Figure 10-1.
The key points of land selection include avoiding residential areas and
accessibility to good electricity, water, and transportation. There are many
ways to raise shrimp: in ponds made of soil, concrete tanks, plastic tanks,
or any other type of water reservoir.
Organizations like the Central Institute of Brackishwater Aquaculture
(CIBA) provide guidelines for shrimp pond setup [1]. Shrimp farming
works best in a simple pond with enough water depth. Before preparing
land for shrimp production, the types and texture of the soil in the chosen
region must be studied. Soil samples from arbitrary locations (preferably
up to a depth of 0.5 meters) are collected. Physical and chemical tests are
conducted to evaluate the soil’s acidity, organic load, fertility level, and
physical makeup.
266
Chapter 10 IoT-Based Shrimp Farming
267
Chapter 10 IoT-Based Shrimp Farming
Figure 10-2 shows the data buoy constructed for continuous water-
quality monitoring.
268
Chapter 10 IoT-Based Shrimp Farming
269
Chapter 10 IoT-Based Shrimp Farming
270
Chapter 10 IoT-Based Shrimp Farming
//nodemcu code
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "HTTPSRedirect.h"
#define SensorPin A0
#include "DHT.h"
#define DHTPIN D4
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 32, &Wire);
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS D3
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float Celcius=0;
unsigned long int avgValue;
float b;
int buf[10],temp;
#include <Wire.h>
#include <Adafruit_ADS1X15.h>
const char* ssid = "IoT";
const char* password = "IoT@1234";
//const char* ssid = "Akash";
//const char* password = "Akash@1234";
Adafruit_ADS1015 ads1115;
271
Chapter 10 IoT-Based Shrimp Farming
Serial.begin(9600);
delay(10);
Serial.println('\n');
ads1115.begin();
sensors.begin();
dht.begin();
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
272
Chapter 10 IoT-Based Shrimp Farming
display.display();
delay(1000);
display.clearDisplay();
display.display();
display.setTextSize(0.5);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0,0);
display.print("DBT Brackish Water");
display.display();
// Connect to WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to ");
Serial.print(ssid); Serial.println(" ...");
Serial.print("Connecting to ");
Serial.println(host);
273
Chapter 10 IoT-Based Shrimp Farming
void loop() {
int16_t adc1, adc2, adc3;
adc1 = ads1115.readADC_SingleEnded(1);
adc2 = ads1115.readADC_SingleEnded(2);
adc3 = ads1115.readADC_SingleEnded(3);
for(int i=0;i<10;i++) //Get 10 sample value from the
sensor for smooth the value
{
buf[i]=analogRead(SensorPin);
delay(10);
}
for(int i=0;i<9;i++) //sort the analog from small
to large
274
Chapter 10 IoT-Based Shrimp Farming
{
for(int j=i+1;j<10;j++)
{
if(buf[i]>buf[j])
{
temp=buf[i];
buf[i]=buf[j];
buf[j]=temp;
}
}
}
avgValue=0;
for(int i=2;i<8;i++) //take the average
value of 6
center sample
avgValue+=buf[i];
float phValue=(float)avgValue*5.0/1024/6; //convert the
analog into
millivolt
phValue=3.5*phValue; //convert the
millivolt into
pH value
Serial.print(" pH:");
Serial.print(phValue,2);
Serial.println(" ");
Serial.print("AIN1: "); Serial.println(adc1);
delay(300);
sensors.requestTemperatures();
Celcius=sensors.getTempCByIndex(0);
float h = dht.readHumidity();
float t = dht.readTemperature();
275
Chapter 10 IoT-Based Shrimp Farming
display.display();
display.println(value0);
display.println(value1);
display.println(value2);
display.println(value3);
display.println(value4);
display.println(value5);
display.println(value6);
display.display();
276
Chapter 10 IoT-Based Shrimp Farming
else{
Serial.println("Error creating client object!");
}
277
Chapter 10 IoT-Based Shrimp Farming
References
[1] Mahesh Salunke, Amol Kalyankar, Chandraprakash D. Khedkar,
Mahesh Shingare, and Gulab D. Khedkar, “A Review on Shrimp
Aquaculture in India: Historical Perspective, Constraints, Status and
Future Implications for Impacts on Aquatic Ecosystem and Biodiversity,”
Reviews in Fisheries Science & Aquaculture, vol. 28:3, pp. 283–302. doi:
10.1080/23308249.2020.1723058.
[3] Ravi Patel and Bhanu Sharma, “Shrimp farming,” June 2022.
278
Chapter 10 IoT-Based Shrimp Farming
279
Index
A Blemish sensors, 33
Bluetooth, 8, 175–177
Aerosol particle sensors, 51
Broadcasting data, 193, 194
Animation function
classes, 155
live line graph, 155–157 C
oscilloscopes live, 157, 159, 160
Camera serial interface (CSI), 85
Application-level network
Carbon monoxide (MQ7), 58
protocols, 96
Cartesian coordinates, 124
Application programming interface
Central Institute of Brackishwater
(API), 173
Aquaculture (CIBA), 266
Arduino programming, 76
Coherence, 131
GSM/GPS modules, 177–180
Communication protocols, 8, 10,
serial communication, 176
11, 28, 69, 75, 76, 227, 228
Autocorrelation graph, 133, 134
Contact sensors, 67–68
Automobile systems, 22, 23
Coriolis flow meter, 63
axes.cohere() function, 131
Cross-correlation graph, 132, 133
Axes.twinx method, 136
Axes.xcorr() function, 132
D
Data lists, 137
B
Detectors, 31, 32, 36, 42, 43, 48, 50,
Bar graphs
54–57, 60, 66, 68
categorical data, 118
Dimension, 16, 59, 65, 148
grouped bar, 118, 119
Donut chart, 142–144
horizontal bar, 122, 123
Dust sensor, 52
proportional, 117
Dynamic Host Configuration
stacked bar, 120, 121
Protocol (DHCP), 190
E H
Electromagnetic flow sensors, 65 Horizontal bar graph, 122, 123
Human-computer interaction
(HCI), 16, 17
F Humidity sensors, 56
Fast Fourier transform
(FFT), 127
Figure size, 135, 136 I, J, K
Firebase, 107, 108, 180, 181, 206 I2C NodeMCU communication
FiveThirtyEight style sheet, protocol, 76
145, 146 Image processing algorithms
Flame sensor, 66, 67 artificial intelligence, 227
Flaw sensors and detectors, 66 artificial vision, 226
Flow sensors, 60–62 automotive/industrial
Force sensor, 58, 59 robots, 227
Fourier analysis, 127 comparison, 238
Fourier series, 127 dimension verification,
Frequency spectrum, 127 234–236, 238
disadvantages, 228
high-quality products, 225
G industrial production, 226
Gas/chemical sensors/ industrial robots, 227
detectors, 57 module source code, 230–233
General-purpose input/output support module code, 233, 234
(GPIO), 78 visual inspection, 226
Google Cloud Platform (GCP), 180 visual processing
Google Firebase, 181–185, 206 algorithms, 226
Google Sheets Programming Imitation learning, 12
(gspread), 106, 107 Inductive proximity sensors, 44
GPIO numbering, 79, 80 Industry 4.0, 1, 228, 229
Graphical user interface Industry 4.0 standards, 209
(GUI), 77, 229 Information and Communication
Grouped bar graph, 118, 119, 121 Technology (ICT), 25–27
282
INDEX
283
INDEX
284
INDEX
285
INDEX
286
INDEX
287
INDEX
288
INDEX
289
INDEX
290