IoT O Level
IoT O Level
Ankit Kumar
Scientist ‘B’
NIELIT Patna
Course Design Committee
Director-in-Charge
Sri Alok Tripathi
NIELIT Patna Center
Author
Ankit Kumar
Scientist ‘B’
NIELIT Patna
i
Preface
The digital space has witnessed major transformations in the last couple of years and as per
industry experts would continue to evolve itself. The latest entrant to the digital space is the
Internet of Things (IoT). The Internet of Things (IoT) is a scenario in which objects, animals or
people are provided with unique identifiers and the ability to transfer data over a network
without requiring human-to-human or human to-computer interaction. The Internet of Things
(IoT, sometimes Internet of Everything) is the network of physical objects or "things"
embedded with electronics, software, sensors and connectivity to enable it to achieve greater
value and service by exchanging data with the manufacturer, operator and/or other connected
devices.
With the advent of the Internet of Things (IoT), fed by sensors soon to number in the trillions,
working with intelligent systems in the billions, and involving millions of applications, the
Internet of Things will drive new consumer and business behavior that will demand increasingly
intelligent industry solutions, which, in turn, will drive trillions of dollars in opportunity for IT
industry and even more for the companies that take advantage of the IoT.
The number of Internet-connected devices (12.5 billion) surpassed the number of human beings
(7 billion) on the planet in 2011, and by 2020, Internet-connected devices are expected to
number between 26 billion and 50 billion globally. To better compete in the global market,
successful companies are finding that investments in hardware and software are no longer
enough. Human elements with specialized engineering and design skills have become the
essential part of the equation.
IoT (Internet of Things) devices are already abundant, but new products that include IoT
modules are now a common trend. Also, almost everything is already connected to a Cloud,
and much more will be in the future. Naturally, as this trend continues, in the near future almost
all devices and appliances will include IoT modules which will use sensor data collection and
control/management based on Clouds. Since we will live in an IoT world supported by Clouds,
knowledge of the core technologies and platforms of IoT and Clouds will enable you with the
tools to become a true leader in the future product and business world
The primary purpose of this course content is to capture state-of-the-art in IoT, its architecture,
technologies, protocols and its applications. Development of a complete IoT system and service
includes several components. The hardware base includes embedded processors, sensors,
ii
actuators, cloud servers, intermediate processing systems, network systems and gateways. The
software base includes operating systems, data bases and control applications for several
application domains, to the very least. I have tried to include most of the aspects of IoT
development in this short
IoT is a fast-changing field. This course material provides a snapshot of its current state. We
continue to work in this area and hope to create updates to this book as the field progresses.
Ankit Kumar
Scientist ‘B’, NIELIT Patna
iii
Contents
Chapter 1: Internet of Things: An overview ………………………………………………1
1.1 Introduction ……………………………………………………………………..1
1.2 Concept of IoT……………………………………………………………..........2
1.3 The Promise of the Internet of Things……………………………………..........3
1.4 The IoT Landscape: Current and Potential Applications……………….............5
1.5 Internet of Things (IoT) characteristics…………………………………………6
1.6 IoT Architecture…………………………………………………………………6
1.7 IoT Terminologies and Technologies……………………………………..........12
1.8 Applications of IoT……………………………………………………………..19
Chapter 2: Sensors and Transducers……………………………………………………...22
2.1 Introduction …………………………………………………………………...22
2.2 Working Principle ……………………………………………………………22
2.3 Classification of Transducers…………………………………………….........23
2.4 Sensor Characteristics …………………………………………………………25
2.5 Types of sensors…….. ………………………………………………………..27
2.6 Actuator ……………………………………………….....................................32
2.7 Signal Conditioning Device…………………………………………………...32
2.8 Data conversion devices …………………………………………………........33
2.9 Factors driving adoption of Sensors within the IoT……………………………35
2.10 Sensors and Actuators Used in IoT applications……………………………...37
Chapter 3: Networking Fundamentals for IoT……………………………………………………..44
3.1 Introduction…………………………………………………………………………….44
3.2 Open System Interconnection Reference Model…………………………....................49
3.3 Networking devices used at Layers………………………………………………........52
3.4 Functions of the OSI Layers……………………………………………………….......54
3.5 Networking Protocols………………………………………………………………….55
3.6 TCP/IP Model………………………………………………………………………….60
3.7 IoT Protocol stack………………………………………………………………….......61
Chapter 4: IoT hardware platforms……………………………………………………….64
4.1 Importance of Hardware Platforms…………………………………………….64
4.2 Hardware Platforms used in IoT Implementation……………………………..73
4.3 Arduino ………………………………………………………………………...75
Chapter 5: IoT Connectivity Solution…………………………………………………….162
5.1 Introduction……………………………………………………………………162
5.2 WIRELESS LOW-POWER TECHNOLOGIES FOR THE IOT……………...162
Chapter 6: IoT Security…………….……………………………………………………...173
6.1 Introduction……………………………………………………………………173
iv
6.2 Attacks and Countermeasurs………………………............................................177
6.3 Securing IoT……………………………..……………………………………...179
i
0
Chapter 1
In your kitchen, a blinking light reminds you it’s time to take your tablets. If you forget, the
medicine bottle cap goes online and emails your doctor to let her know.
On your way out of the house, you catch a glow in the corner of your eye. Your umbrella
handle is lit up, which means that it has checked the BBC weather reports and predicts rain.
You sigh and pick it up.
As you pass the bus stop on the way to the station, you notice the large LCD display flash that
the bus number 23 is due. It arrives when you turn the next corner. When the bus company
first installed those displays, they ran on the expected timetable information only, but now
that every bus has GPS tracking its location, they simply connect to the bus company’s online
service and always give the updated information.
When you get to the station, your phone checks you in automatically to a location-based
service. On your mantelpiece at home, an ornament with a dial notices the change and starts
to turn so that the text on it points to the word “Travelling”. Your family will also see later
that you’ve arrived at “Work” safely
On your lunch break, a pedometer in your training shoes and a heart monitor in your wrist
band help track your run around the block. The wrist band’s large display also makes it easy
to glance down and see how fast you are running and how many calories you’ve burned. All
the data is automatically uploaded to your sports tracking site, which also integrates with your
online supermarket shopping account to make it easy to compare with how many calories
you’ve eaten
As you can see from the following example, each of these products is feasible with today’s
technology. Each has been prototyped, and many of them exist as market products.
1.1 INTRODUCTION
2
and machines. Physical and virtual things in an IoT have their own identities and attributes
and are capable of using intelligent interfaces and being integrated as an information network.
In easy terms IoT can be treated as a set of connected devices that are uniquely identifiable.
The words “Internet” and “Things” mean an inter-connected world-wide network based on
sensors, communication, networking, and information processing technologies, which might
be the new version of information and communications technology (ICT). To date, a number
of technologies are involved in IoT, such as wireless sensor networks (WSNs), barcodes,
intelligent sensing, RFID, NFCs, low energy wireless communications, cloud computing and
so on. The IoT describes the next generation of Internet, where the physical things could be
accessed and identified through the Internet. Depending on various technologies for the
implementation, the definition of the IoT varies. However, the fundamental of IoT implies
that objects in an IoT can be identified uniquely in the virtual representations. Within an IoT,
all things are able to exchange data and if needed, process data according to predefined
schemes.
The “Internet of Things” (sometimes also referred to as the “Internet of Everything,” or IoE)
generally refers to the multiple networks of devices or technology platforms (“things”) that
communicate with each other via wireless protocols and without direct human interaction.
Connections made through IoT-enabled devices facilitate the rapid and efficient transfer of
data needed to support a wide range of activities and operations. In this way, the application
of IoT technologies can lead to significant operational improvements, such as increased
efficiency, better performance and enhanced safety. Many think of the IoT as a single global
network. But the IoT actually encompasses a multitude of independent but complementary
networks in various service sectors, such as those supporting efficient energy distribution and
usage (so-called smart grids), home automation systems, vehicular traffic management and
healthcare services. Indeed, technology research and consulting firm Beecham Research has
identified nine different IoT service sectors and 29 separate applications for current and
potential IoT development or expansion. The potential in this broad applicability of IoT
technologies is reflected in projections of future IoT market revenue and growth. IDC
Research estimates that the global market value for IoT products and devices, currently about
$655 billion (USD), will increase to $1.7 trillion by the year 2020, a compound annual growth
rate (CAGR) of 16.9 percent. A separate projection from ABI Research indicates that the
number of IoT-connected devices will increase from around 16 billion in 2014 to nearly 41
billion by 2020. Clearly, leveraging the growth potential of the IoT is likely to be an essential
element of the strategy of technology companies in the years to come.
While the Internet of Things (IoT) will ultimately have an enormous impact on consumers,
enterprises and society as a whole, it is still at an early stage in its development. As mobile
operators and their partners pilot new services across multiple sectors, ranging from health to
automotive, they have identified several distinctive features of the Internet of Things. A
common understanding of the distinctive nature of this nascent opportunity should help hasten
the development of this market
The Internet of Things can enable the next wave of life-enhancing services across several
fundamental sectors of the economy. As the Internet of Things evolves, the proliferation of
smart connected devices supported by mobile networks, providing pervasive and seamless
connectivity, will unlock opportunities to provide life-enhancing services for consumers while
3
boosting productivity for enterprises. For consumers, connectivity provided by the IoT could
enhance their quality of life in multiple ways, such as, but not limited to, energy efficiency
and security at home and in the city. In the home, the integration of connected smart devices
and cloud-based services will help address the pressing issue of energy efficiency and
security. Connected smart devices will enable a reduction in utility bills and outages, while
also improving home security via remote monitoring.
4
In education, mobile-enabled solutions will tailor the learning process to each student’s needs,
improving overall proficiency levels, while linking virtual and physical classrooms to make
learning more convenient and accessible. Mobile education solutions have already been
shown to improve learners’ proficiency rates and reduce dropout rates, and have the potential
to enable, by 2017, the education of up to 180 million additional students in developing
countries who will be able to stay in school due to mEducation
7
Any server-side architecture would ideally be highly scalable, and be able to support millions
of devices all constantly sending, receiving, and acting on data. However, many “high-
scalability architectures” have come with an equally high price – both in hardware, software,
and in complexity. An important requirement for this architecture is to support scaling from a
small deployment to a very large number of devices. Elastic scalability and the ability to
deploy in a cloud infrastructure are essential. The ability to scale the server side out on small
cheap servers is an important requirement to make this an affordable architecture for small
deployments as well as large ones.
1.6.1.5 SECURITY
Security is one of the most important aspects for IoT. IoT devices are often collecting highly
personal data, and by their nature are bringing the real world onto the Internet (and vice
versa). This brings three categories of risks: • Risks that are inherent in any Internet system,
but that product/IoT designers may not be aware of • Specific risks that are unique to IoT
devices • Safety to ensure no harm is caused by, for instance, misusing actuators The first
category includes simple things such as locking down open ports on devices (like the Internet-
attached fridge that had an unsecured SMTP server and was being used to send spam). The
second category includes issues specifically related to IoT hardware, e.g. the device may have
its secure information read. For example, many IoT devices are too small to support proper
asymmetric encryption. Another specific example is the ability for someone to attack the
hardware to understand security. Another example - university security researchers who
famously reverse-engineered and broke the Mifare Classic RFID card solution3. These sort of
reverse engineering attacks are an issue compared with pure web solutions where there is
often no available code to attack (i.e. completely server-side implementation). Two very
important specific issues for IoT security are the concerns about identity and access
management. Identity is an issue where there are often poor practices implemented. For
example, the use of clear text/ Base64 encoded user IDs/passwords with devices and machine-
to-machine (M2M) is a common mistake. Another common issue is to hard-code access
management rules into either client- or server-side code. A much more flexible and powerful
approach is to utilize models such as “Attribute Based Access Control” and “Policy Based
Access Control”.
1.6.2 Potential IoT Architectures
]The four-stage architecture of an IoT system
Stage 1 of an IoT architecture consists of your networked things, typically wireless sensors
and actuators. Stage 2 includes sensor data aggregation systems and analog-to-digital data
conversion. In Stage 3, edge IT systems perform preprocessing of the data before it moves on
to the data center or cloud. Finally, in Stage 4, the data is analyzed, managed, and stored on
traditional back-end data center systems. Clearly, the sensor/actuator state is the province of
operations technology (OT) professionals. So is Stage 2. Stages 3 and 4 are typically
controlled by IT, although the location of edge IT processing may be at a remote site or nearer
to the data center. The dashed vertical line labeled "the edge" is the traditional demarcation
between OT and IT responsibilities, although this is blurring. Here's a look at each in detail.
8
Stage 1. Sensors/actuators
Sensors collect data from the environment or object under measurement and turn it into useful
data. Think of the specialized structures in your cell phone that detect the directional pull of
gravity—and the phone's relative position to the “thing” we call the earth—and convert it into
data that your phone can use to orient the device. Actuators can also intervene to change the
physical conditions that generate the data. An actuator might, for example, shut off a power
supply, adjust an air flow valve, or move a robotic gripper in an assembly process.
The sensing/actuating stage covers everything from legacy industrial devices to robotic
camera systems, water-level detectors, air quality sensors, accelerometers, and heart rate
monitors. And the scope of the IoT is expanding rapidly, thanks in part to low-power wireless
sensor network technologies and Power over Ethernet, which enable devices on a wired LAN
to operate without the need for an A/C power source.
In an IoT architecture, some data processing can occur in each of the four stages. However,
while you can process data at the sensor, what you can do is limited by the processing power
available on each IoT device. Data is at the heart of an IoT architecture, and you need to
choose between immediacy and depth of insight when processing that data. The more
immediate the need for information, the closer to the end devices your processing needs to be.
9
For deeper insights that require more extensive processing, you'll need to move the data into a
cloud- or data center-based system that can bring several sources of data together. But some
decisions simply can’t wait for deep processing. Did the robotic arm performing the surgery
cut an artery? Will the car crash? Is the aircraft approaching the threat detection system a
friend or a foe? You don't have time to send that data to your core IT assets. You must process
the data right at the sensor— at the very edge of the edge network—for the fastest response.
The data from the sensors starts in analog form. That data needs to be aggregated and
converted into digital streams for further processing downstream. Data acquisition systems
(DAS) perform these data aggregation and conversion functions. The DAS connects to the
sensor network, aggregates outputs, and performs the analog-to-digital conversion. The
Internet gateway receives the aggregated and digitized data and routes it over Wi-Fi, wired
LANs, or the Internet, to Stage 3 systems for further processing.
Stage 2 systems often sit in close proximity to the sensors and actuators. For example, a pump
might contain a half-dozen sensors and actuators that feed data into a data aggregation device
that also digitizes the data. This device might be physically attached to the pump. An adjacent
gateway device or server would then process the data and forward it to the Stage 3 or Stage 4
systems.
Why preprocess the data? The analog data streams that come from sensors create large
volumes of data quickly. The measurable qualities of the physical world in which your
business may be interested—motion, voltage, vibration, and so on—can create voluminous
amounts of constantly changing data. Think how much sensor data a complex machine like an
aircraft engine might generate in one day, and there’s no theoretical limit to the number of
sensors that could be feeding data into an IoT system. What’s more, an IoT system is always
on, providing continuous connectivity and data feeds. IoT data flows can be immense—I've
seen as much as 40 TB/second in one case. That's a lot of data to transport into the data center.
It's best to preprocess it.
Another reason not to pass the data on to the data center in this form is that analog data has
specific timing and structural characteristics that require specialized software to process. It's
best to convert the data into digital form first, and that's what happens in Stage 2.
Intelligent gateways can build on additional, basic gateway functionality by adding such
capabilities as analytics, malware protection, and data management services. These systems
enable the analysis of data streams in real time. Although delivering business insights from
the data is a little less immediate at the gateway than it would be when sent directly from the
sensor/actuator zone, the gateway has the compute power to render the information in a form
that is more understandable to business stakeholders.
10
Gateways are still edge devices—they’re external to the data center—so geography and
location matter. In the pump example, if you have 100 pump units and want to process data
on-premises, you might have instant data at the pump level, aggregate the information to
create a plantwide view for the facility, and pass the data on to the data center for
companywide view. DAS and gateway devices may end up in a wide variety of environments,
from the factory floor to mobile field stations, so these systems are usually designed to be
portable, easy to deploy, and rugged enough to withstand variations in temperature, humidity,
dust, and vibration.
Stage 3. Edge IT
Once IoT data has been digitized and aggregated, it's ready to cross into the realm of IT.
However, the data may require further processing before it enters the data center. This is
where edge IT systems, which perform more analysis, come into play. Edge IT processing
systems may be located in remote offices or other edge locations, but generally these sit in the
facility or location where the sensors reside closer to the sensors, such as in a wiring closet.
Because IoT data can easily eat up network bandwidth and swamp your data center resources,
it's best to have systems at the edge capable of performing analytics as a way to lessen the
burden on core IT infrastructure. If you just had one large data pipe going to the data center,
you'd need enormous capacity. You'd also face security concerns, storage issues, and delays
processing the data. With a staged approach, you can preprocess the data, generate
meaningful results, and pass only those on. For example, rather than passing on raw vibration
data for the pumps, you could aggregate and convert the data, analyze it, and send only
projections as to when each device will fail or need service.
Here's another example: You might use machine learning at the edge to scan for anomalies
that identify impending maintenance problems that require immediate attention. Then you
could use visualization technology to present that information using easy-to-understand
dashboards, maps, or graphs. Highly integrated computer systems, such as hyper-converged
infrastructure, are ideally suited to these tasks because they're relatively fast, and easy to
deploy and manage remotely.
Data that needs more in-depth processing, and where feedback doesn't have to be immediate,
gets forwarded to physical data center or cloud-based systems, where more powerful IT
systems can analyze, manage, and securely store the data. It takes longer to get results when
you wait until data reaches Stage 4, but you can execute a more in-depth analysis, as well as
combine your sensor data with data from other sources for deeper insights. Stage 4 processing
may take place on-premises, in the cloud, or in a hybrid cloud system, but the type of
processing executed in this stage remains the same, regardless of the platform.
11
Living on the edge
The 4-stage approach to IoT infrastructure and processing will require new levels of
collaboration, particularly as the separations between these stages start to blur. If you’re an
OT professional, be prepared to work side by side with IT professionals. If you’re in IT, get
ready to collaborate more closely with OTs. Eventually, the two functions will converge as
the IoT pulls domain expertise deeper into data processing.
IT professionals can build their IoT skills by starting small and working with domain experts
to identify sources of potentially valuable data. Would understanding the operating conditions
of a machine help operations design more efficient maintenance cycles? Could developing
knowledge of air temperature fluctuations in a warehouse help to improve product storage?
Investigate the sensors and edge devices you would need to harvest the data. Design the
infrastructure. Then experiment to make sure that the project produces results that make for a
strong business case.
The IoT continues to reshape commercial, industrial, scientific, and engineering endeavors in
profound and unpredictable ways. In the scientific revolution of the 17th century, newly
invented instruments extended the reach of human senses far into the microscopic and
astronomic realms. The IoT is the instrument that will enable your organization to connect
intelligent technologies to the data-emitting universe of objects. The implications for IT
infrastructure will be just as far-reaching.
All IoT applications need to have one or more sensors to collect data from the environment.
Sensors are essential components of smart objects. One of the most important aspects of the
Internet of Things is context awareness, which is not possible without sensor technology. IoT
sensors are mostly small in size, have low cost, and consume less power. They are constrained
by factors such as battery capacity and ease of deployment.
In specific, the smartphone is a very handy and user friendly device that has a host of built in
communication and data processing features. With the increasing popularity of smartphones
among people, researchers are showing interest in building smart IoT solutions using
smartphones because of the embedded sensors. Some additional sensors can also be used
depending upon the requirements. Applications can be built on the smartphone that uses sensor
data to produce meaningful results. Some of the sensors inside a modern smartphone are as
follows.
12
(1) The accelerometer senses the motion and acceleration of a mobile phone. It typically
measures changes in velocity of the smartphone in three dimensions. There are many types of
accelerometers.
(2) The gyroscope detects the orientation of the phone very precisely. Orientation is measured
using capacitive changes when a seismic mass moves in a particular direction.’
(3) The camera and microphone are very powerful sensors since they capture visual and audio
information, which can then be analyzed and processed to detect various types of contextual
information. For example, we can infer a user’s current environment and the interactions that
she is having. To make sense of the audio data, technologies such as voice recognition and
acoustic features can be exploited.
(4) The GPS (Global Positioning System) detects the location of the phone, which is one of the
most important pieces of contextual information for smart applications. The location is detected
using the principle of trilateration. The distance is measured from three or more satellites (or
mobile phone towers in the case of A-GPS) and coordinates are computed.
(5) The light sensor detects the intensity of ambient light. It can be used for setting the
brightness of the screen and other applications in which some action is to be taken depending
on the intensity of ambient light. For example, we can control the lights in a room.
1.7.2 Actuators
Let us look at some examples of actuators that are used in the Internet of Things. An actuator
is a device, which can effect a change in the environment by converting electrical energy into
some form of useful energy. Some examples are heating or cooling elements, speakers, lights,
displays, and motors.
The actuators, which induce motion, can be classified into three categories, namely, electrical,
hydraulic, and pneumatic actuators depending on their operation. Hydraulic actuators facilitate
mechanical motion using fluid or hydraulic power. Pneumatic actuators use the pressure of
compressed air and electrical ones use electrical energy.
As an example, we can consider a smart home system, which consists of many sensors and
actuators. The actuators are used to lock/unlock the doors, switch on/off the lights or other
electrical appliances, alert users of any threats through alarms or notifications, and control the
temperature of a home (via a thermostat).
1.7.3 Preprocessing
As smart things collect huge amount of sensor data, compute and storage resources are required
to analyze, store, and process this data. The most common compute and storage resources are
cloud based because the cloud offers massive data handling, scalability, and flexibility. But this
13
will not be sufficient to meet the requirements of many IoT applications because of the
following reasons.
(1) Mobility: most of the smart devices are mobile. Their changing location makes it difficult
to communicate with the cloud data center because of changing network conditions across
different locations.
(2) Reliable and real time actuation: communicating with the cloud and getting back
responses takes time. Latency sensitive applications, which need real time responses, may not
be feasible with this model. Also, the communication may be lossy due to wireless links, which
can lead to unreliable data.
(3) Scalability: More devices s more requests to the cloud, thereby increasing the latency.
(4) Power constraints: communication consumes a lot of power, and IoT devices are battery
powered. They thus cannot afford to communicate all the time.
As a solution to these problems, we can bring some compute and storage resources to the edge
of the network instead of relying on the cloud for everything. This concept is known as fog
computing. The fog can be viewed as a cloud, which is close to the ground. Data can be stored,
processed, filtered, and analyzed on the edge of the network before sending it to the cloud
through expensive communication media. The fog and cloud paradigms go together. Both of
them are required for the optimal performance of IoT applications. A smart gateway can be
employed between underlying networks and the cloud to realize fog computing as shown in
Figure.
14
(2) Location awareness: as the fog is located on the edge of the network, it is aware of the
location of the applications and their context. This is beneficial as context awareness is an
important feature of IoT applications
(3) Distributed nodes: fog nodes are distributed unlike centralized cloud nodes. Multiple fog
nodes need to be deployed in distributed geographical areas in order to provide services to
mobile devices in those areas. For example, in vehicular networks, deploying fog nodes at
highways can provide low latency data/video streaming to vehicles.
(4) Mobility: the fog supports mobility as smart devices can directly communicate with smart
gateways present in their proximity.
(5) Real time response: fog nodes can give an immediate response unlike the cloud, which
has a much greater latency.
(6) Interaction with the cloud: fog nodes can further interact with the cloud and communicate
only that data, which is required to be sent to the cloud.
1.7.4 IoT Gateway
An Internet of Things (IoT) gateway is a physical device or software program that serves as the
connection point between the cloud and controllers, sensors and intelligent devices. All data
moving to the cloud, or vice versa, goes through the gateway, which can be either a dedicated
hardware appliance or software program. An IoT gateway may also be referred to as an
intelligent gateway or a control tier.
15
Some sensors generate tens of thousands of data points per second. A gateway provides a place
to preprocess that data locally at the edge before sending it on to the cloud. When data is
aggregated, summarized and tactically analyzed at the edge, it minimizes the volume of data
that needs to be forwarded on to the cloud, which can have a big impact on response times and
network transmission costs.
Another benefit of an IoT gateway is that it can provide additional security for the IoT network
and the data it transports. Because the gateway manages information moving in both directions,
it can protect data moving to the cloud from leaks and IoT devices from being compromised by
malicious outside attacks with features such as tamper detection, encryption, hardware random
number generators and crypto engines.
1.7.5 Communication
As the Internet of Things is growing very rapidly, there are a large number of heterogeneous
smart devices connecting to the Internet. IoT devices are battery powered, with minimal
compute and storage resources. Because of their constrained nature, there are various
communication challenges involved, which are as follows:
(1) Addressing and identification: since millions of smart things will be connected to the
Internet, they will have to be identified through a unique address, on the basis of which they
communicate with each other. For this, we need a large addressing space, and a unique address
for each smart object.
(2) Low power communication: communication of data between devices is a power
consuming task, specially, wireless communication. Therefore, we need a solution that
facilitates communication with low power consumption.
(3) Routing protocols with low memory requirement and efficient communication patterns.
IoT devices typically connect to the Internet through the IP (Internet Protocol) stack. This stack
is very complex and demands a large amount of power and memory from the connecting
devices. The IoT devices can also connect locally through non-IP networks, which consume
less power, and connect to the Internet via a smart gateway. Non-IP communication channels
such as Bluetooth, RFID, and NFC are fairly popular but are limited in their range (up to a few
meters). Therefore, their applications are limited to small personal area networks. Personal area
networks (PAN) are being widely used in IoT applications such as wearables connected to
smartphones. For increasing the range of such local networks, there was a need to modify the
IP stack so as to facilitate low power communication using the IP stack. One of the solutions is
6LoWPAN, which incorporates IPv6 with low power personal area networks. The range of a
PAN with 6LoWPAN is similar to local area networks, and the power consumption is much
lower.
The leading communication technologies used in the IoT world are IEEE 802.15.4, low power
WiFi, 6LoWPAN, RFID, NFC, Sigfox, LoraWAN, and other proprietary protocols for wireless
networks.
16
1.7.6 IoT Network Protocol Stack
The Internet Engineering Task Force (IETF) has developed alternative protocols for
communication between IoT devices using IP because IP is a flexible and reliable standard
[50, 51]. The Internet Protocol for Smart Objects (IPSO) Alliance has published various white
papers describing alternative protocols and standards for the layers of the IP stack and an
additional adaptation layer, which is used for communication between smart objects.
(1) Physical and MAC Layer (IEEE 802.15.4). The IEEE 802.15.4 protocol is designed for
enabling communication between compact and inexpensive low power embedded devices that
need a long battery life. It defines standards and protocols for the physical and link (MAC) layer
of the IP stack. It supports low power communication along with low cost and short range
communication. In the case of such resource constrained environments, we need a small frame
size, low bandwidth, and low transmit power.
Transmission requires very little power (maximum one mill watt), which is only one percent of
that used in WiFi or cellular networks. This limits the range of communication. Because of the
limited range, the devices have to operate cooperatively in order to enable multihop routing
over longer distances. As a result, the packet size is limited to 127 bytes only, and the rate of
communication is limited to 250 kbps. The coding scheme in IEEE 802.15.4 has built in
redundancy, which makes the communication robust, allows us to detect losses, and enables the
retransmission of lost packets. The protocol also supports short 16-bit link addresses to decrease
the size of the header, communication overheads, and memory requirements.
(2) Adaptation Layer. IPv6 is considered the best protocol for communication in the IoT
domain because of its scalability and stability. Such bulky IP protocols were initially not
thought to be suitable for communication in scenarios with low power wireless links such as
IEEE 802.15.4.
6LoWPAN, an acronym for IPv6 over low power wireless personal area networks, is a very
popular standard for wireless communication. It enables communication using IPv6 over the
IEEE 802.15.4 protocol. This standard defines an adaptation layer between the 802.15.4 link
layer and the transport layer. 6LoWPAN devices can communicate with all other IP based
devices on the Internet. The choice of IPv6 is because of the large addressing space available
in IPv6. 6LoWPAN networks connect to the Internet via a gateway (WiFi or Ethernet), which
also has protocol support for conversion between IPv4 and IPv6 as today’s deployed Internet is
mostly IPv4. IPv6 headers are not small enough to fit within the small 127 byte MTU of the
802.15.4 standard. Hence, squeezing and fragmenting the packets to carry only the essential
information is an optimization that the adaptation layer performs.
Specifically, the adaptation layer performs the following three optimizations in order to reduce
communication overhead:
(i)Header compression 6loWPAN defines header compression of IPv6 packets for decreasing
the overhead of IPv6. Some of the fields are deleted because they can be derived from link level
information or can be shared across packets.
17
(ii)Fragmentation: the minimum MTU size (maximum transmission unit) of IPv6 is 1280
bytes. On the other hand, the maximum size of a frame in IEEE 802.15.4 is 127 bytes.
Therefore, we need to fragment the IPv6 packet. This is done by the adaptation layer
(iii)Link layer forwarding 6LoWPAN also supports mesh under routing, which is done at the
link layer using link level short addresses instead of in the network layer. This feature can be
used to communicate within a 6LoWPAN network.
(3) Network Layer. The network layer is responsible for routing the packets received from the
transport layer. The IETF Routing over Low Power and Lossy Networks (ROLL) working
group has developed a routing protocol (RPL) for Low Power and Lossy Networks (LLNs)
For such networks, RPL is an open routing protocol, based on distance vectors. It describes how
a destination oriented directed acyclic graph (DODAG) is built with the nodes after they
exchange distance vectors. A set of constraints and an objective function is used to build the
graph with the best path. The objective function and constraints may differ with respect to their
requirements. For example, constraints can be to avoid battery powered nodes or to prefer
encrypted links. The objective function can aim to minimize the latency or the expected number
of packets that need to be sent.
The making of this graph starts from the root node. The root starts sending messages to
neighboring nodes, which then process the message and decide whether to join or not depending
upon the constraints and the objective function. Subsequently, they forward the message to their
neighbors. In this manner, the message travels till the leaf nodes and a graph is formed. Now
all the nodes in the graph can send packets upwards hop by hop to the root. We can realize a
point to point routing algorithm as follows. We send packets to a common ancestor, from which
it travels downwards (towards leaves) to reach the destination.
To manage the memory requirements of nodes, nodes are classified into storing and nonstoring
nodes depending upon their ability to store routing information. When nodes are in a nonstoring
mode and a downward path is being constructed, the route information is attached to the
incoming message and forwarded further till the root. The root receives the whole path in the
message and sends a data packet along with the path message to the destination hop by hop.
But there is a trade-off here because nonstoring nodes need more power and bandwidth to send
additional route information as they do not have the memory to store routing tables.
(4) Transport Layer. TCP is not a good option for communication in low power environments
as it has a large overhead owing to the fact that it is a connection oriented protocol. Therefore,
UDP is preferred because it is a connectionless protocol and has low overhead.
(5) Application Layer. The application layer is responsible for data formatting and presentation.
The application layer in the Internet is typically based on HTTP. However, HTTP is not suitable
in resource constrained environments because it is fairly verbose in nature and thus incurs a
large parsing overhead. Many alternate protocols have been developed for IoT environments
such as CoAP (Constrained Application Protocol) and MQTT (Message Queue Telemetry
Transport)
.
18
1.7.7 Wireless Protocols for IoT
Bluetooth Low Energy, also known as “Bluetooth Smart,” was developed by the Bluetooth
Special Interest Group. It has a relatively shorter range and consumes lower energy as compared
to competing protocols. The BLE protocol stack is similar to the stack used in classic Bluetooth
technology. It has two parts: controller and host. The physical and link layer are implemented
in the controller. The controller is typically a SOC (System on Chip) with a radio. The
functionalities of upper layers are included in the host. BLE is not compatible with classic
Bluetooth. Let us look at the differences between classic Bluetooth and BLE.
The main difference is that BLE does not support data streaming. Instead, it supports quick
transfer of small packets of data (packet size is small) with a data rate of 1 Mbps.
There are two types of devices in BLE: master and slave. The master acts as a central device
that can connect to various slaves. Let us consider an IoT scenario where a phone or PC serve
as the master and mobile devices such as a thermostat, fitness tracker, smart watch, or any
monitoring device act as slaves. In such cases, slaves must be very power efficient. Therefore,
to save energy, slaves are by default in sleep mode and wake up periodically to receive packets
from the master.
There are a diverse set of areas in which intelligent applications have been developed. All of
these applications are not yet readily available; however, preliminary research indicates the
potential of IoT in improving the quality of life in our society. Some uses of IoT applications
are in home automation, fitness tracking, health monitoring, environment protection, smart
cities, and industrial settings.
Smart homes are becoming more popular today because of two reasons. First, the sensor and
actuation technologies along with wireless sensor networks have significantly matured. Second,
people today trust technology to address their concerns about their quality of life and security
of their homes (see below Figure).
19
Fig 1.6: Block diagram of a smart home system.
In smart homes, various sensors are deployed, which provide intelligent and automated services
to the user. They help in automating daily tasks and help in maintaining a routine for individuals
who tend to be forgetful. They help in energy conservation by turning off lights and electronic
gadgets automatically. We typically use motion sensors for this purpose. Motion sensors can
be additionally used for security also.
For example, the project, MavHome, provides an intelligent agent, which uses various
prediction algorithms for doing automated tasks in response to user triggered events and adapts
itself to the routines of the inhabitants. Prediction algorithms are used to predict the sequence
of events in a home. A sequence matching algorithm maintains sequences of events in a queue
and also stores their frequency. Then a prediction is made using the match length and frequency.
Other algorithms used by similar applications use compression based prediction and Markov
models.
Energy conservation in smart homes is typically achieved through sensors and context
awareness. The sensors collect data from the environment (light, temperature, humidity, gas,
and fire events). This data from heterogeneous sensors is fed to a context aggregator, which
forwards the collected data to the context aware service engine. This engine selects services
based on the context. For example, an application can automatically turn on the AC when the
humidity rises. Or, when there is a gas leak, it can turn all the lights off.
20
Smart home applications are really beneficial for the elderly and differently abled. Their health
is monitored and relatives are informed immediately in case of emergencies. Floors are
equipped with pressure sensors, which track the movement of an individual across the smart
home and also help in detecting if a person has fallen down. In smart homes, CCTV cameras
can be used to record events of interest. These can then be used for feature extraction to find
out what is going on.
In specific, fall detection applications in smart environments are useful for detecting if elderly
people have fallen down. Yu et al. use computer vision based techniques for analyzing postures
of the human body. Sixsmith et al. used low cost infrared sensor array technology, which can
provide information such as the location, size, and velocity of a target object. It detects
dynamics of a fall by analyzing the motion patterns and also detects inactivity and compares it
with activity in the past. Neural networks are employed and sample data is provided to the
system for various types of falls. Many smartphones based applications are also available,
which detect a fall on the basis of readings from the accelerometer and gyroscope data.
There are many challenges and issues with regard to smart home applications. The most
important is security and privacy since all the data about the events taking place in the home is
being recorded. If the security and trustworthiness of the system are not guaranteed, an intruder
may attack the system and may make the system behave maliciously. Smart home systems are
supposed to notify the owners in case they detect such abnormalities. This is possible using AI
and machine learning algorithms, and researchers have already started working in this direction.
Reliability is also an issue since there is no system administrator to monitor the system.
21
Chapter 2
Sensors and Transducers
2.1 Introduction
Measurement is an important aspect of IoT based system. Its main function is to collect the
information on system status and to feed it to the micro-processor(s) for controlling the whole
system. Measurement system comprises of sensors, transducers and signal processing devices.
Today a wide variety of these elements and devices are available in the market. For an IoT
system designer it is quite important to choose suitable sensors/transducers for the desired
application(s). It is therefore essential to learn the principle of working of commonly used
sensors/transducers. Sensor is defined as an element which produces signal relating to the
quantity being measured. According to the Instrument Society of America, sensor can be
defined as “A device which provides a usable output in response to a specified measurand.”
Here, the output is usually an ‘electrical quantity’ and measurand is a ‘physical quantity,
property or condition which is to be measured’. Thus in the case of, say, a variable inductance
displacement element, the quantity being measured is displacement and the sensor transforms
an input of displacement into a change in inductance. Transducer It is defined as an element
when subjected to some physical change experiences a related change or an element which
converts a specified measurand into a usable output by using a transduction principle. It can
also be defined as a device that converts a signal from one form of energy to another form. A
wire of Constantan alloy (copper-nickel 55-45% alloy) can be called as a sensor because
variation in mechanical displacement (tension or compression) can be sensed as change in
electric resistance. This wire becomes a transducer with appropriate electrodes and input-
output mechanism attached to it. Thus we can say that ‘sensors are transducers’.
Sensor/transducers specifications Transducers or measurement systems are not perfect
systems. Mechatronics design engineer must know the capability and shortcoming of a
transducer or measurement system to properly assess its performance. There are a number of
performance related parameters of a transducer or measurement system. These parameters are
called as sensor specifications. Sensor specifications inform the user to the about deviations
from the ideal behavior of the sensors.
22
Fig 2.1: Sensing System Block Diagram
The transduction element transforms the output of the sensor to an electrical output, as shown
in the above Fig. A transducer will have basically two main components. They are
1. Sensing Element The physical quantity or its rate of change is sensed and responded to by
this part of the transistor.
2. Transduction Element The output of the sensing element is passed on to the transduction
element. This element is responsible for converting the non-electrical signal into its
proportional electrical signal. There may be cases when the transduction element performs the
action of both transduction and sensing. The best example of such a transducer is a
thermocouple. A thermocouple is used to generate a voltage corresponding to the heat that is
generated at the junction of two dissimilar metals.
2.3 Classification of Transducers
The Classification of Transducers is done in many ways. Some of the criteria for the
classification are based on their area of application, Method of energy conversion, Nature of
output signal, according to Electrical principles involved, Electrical parameter used, principle
of operation, & Typical applications. The transducers can be classified broadly
i. On the basis of transduction form used
ii. As primary and secondary transducers
iii. As active and passive transducers
A component whose output energy is supplied entirely by its input signal (physical quantity
under measurement) is commonly called a „passive transducer‟. In other words, the passive
transducers derive the power required for transduction from an auxiliary source. Active
transducers are those which do not require an auxiliary power source to produce their output.
They are also known as self-generating type since they produce their own voltage or current
output. Some of the passive transducers (electrical transducers), their electrical parameter
(resistance, capacitance, etc), principle of operation and applications are listed below.
2.3.1 Resistive Transducers
1. Resistance Strain Gauge – The change in value of resistance of metal semi-conductor due to
elongation or compression is known by the measurement of torque, displacement or force
2. . 2. Resistance Thermometer – The change in resistance of metal wire due to the change in
temperature known by the measurement of temperature
3. Photoconductive Cell – The change in resistance of a cell due to a corresponding change in
light flux is known by its corresponding light intensity.
23
4. Thermistor – The change in resistance of a semi-conductor that has a negative co-efficient of
resistance is known by its corresponding measure of temperature.
5. Potentiometer Type – The change in resistance of a potentiometer reading due to the
movement of the slider as a part of an external force applied is known by its corresponding
pressure or displacement.
2.3.2 Capacitance Transducers
1. Variable capacitance pressure gage - Principle of operation: Distance between two parallel
plates is varied by an externally applied force Applications: Measurement of Displacement,
pressure
2. Capacitor microphone Principle of operation: Sound pressure varies the capacitance
between a fixed plate and a movable diaphragm. Applications: Speech, music, noise
3. Dielectric gauge Principle of operation: Variation in capacitance by changes in the
dielectric. Applications: Liquid level, thickness
2.3.3 Inductance Transducers
1. Magnetic circuit transducer Principle of operation: Self-inductance or mutual inductance of
ac-excited coil is varied by changes in the magnetic circuit. Applications: Pressure,
displacement
2. Reluctance pickup Principle of operation: Reluctance of the magnetic circuit is varied by
changing the position of the iron core of a coil. Applications: Pressure, displacement,
vibration, Applications: Force, pressure, sound
2.3.4 Voltage and current Transducers
1. Hall effect pickup Principle of operation: A potential difference is generated across a
semiconductor plate (germanium) when magnetic flux interacts with an applied current.
Applications: Magnetic flux,
2.3.5 Self-Generating Transducers (No External Power) – Active Transducers
They do not require an external power, and produce an analog voltage or current when
stimulated by some physical form of energy.
1. Thermocouple and thermopile Principle of operation: An emf is generated across the
junction of two dissimilar metals or semiconductors when that junction is heated.
Applications: Temperature, heat flow, radiation
2. Piezoelectric pickup An emf is generated when an external force is applied to certain
crystalline materials, such as quartz Sound, vibration. acceleration, pressure changes
3. Photovoltaic cell Principle of operation: A voltage is generated in a semi-conductor
junction device when radiant energy stimulates the cell Applications: Light meter, solar cell
24
2.4.6 Primary Transducers and Secondary Transducers- Bourden tube acting as a
primary detector senses the pressure and converts the pressure into a displacement of its free
end. The displacement of the free end moves the core of a linear variable differential
transformer(LVDT) which produces an output voltage.
2.4 Sensor Specifications
Following are the various specifications of a sensor/transducer system.
1. Range: The range of a sensor indicates the limits between which the input can vary. For
example, a thermocouple for the measurement of temperature might have a range of 25-225
°C.
2. Span: The span is difference between the maximum and minimum values of the input.
Thus, the above-mentioned thermocouple will have a span of 200 °C.
3. Error: Error is the difference between the result of the measurement and the true value of
the quantity being measured. A sensor might give a displacement reading of 29.8 mm, when
the actual displacement had been 30 mm, then the error is –0.2 mm.
4. Accuracy: The accuracy defines the closeness of the agreement between the actual
measurement result and a true value of the measurand. It is often expressed as a percentage of
the full range output or full–scale deflection. A piezoelectric transducer used to evaluate
dynamic pressure phenomena associated with explosions, pulsations, or dynamic pressure
conditions in motors, rocket engines, compressors, and other pressurized devices is capable to
detect pressures between 0.1 and 10,000 psig (0.7 KPa to 70 MPa). If it is specified with the
accuracy of about ±1% full scale, then the reading given can be expected to be within ± 0.7
MPa.
5. Sensitivity: Sensitivity of a sensor is defined as the ratio of change in output value of a
sensor to the per unit change in input value that causes the output change. For example, a
general purpose thermocouple may have a sensitivity of 41 µV/°C.
6. Nonlinearity: The nonlinearity indicates the maximum deviation of the actual measured
curve of a sensor from the ideal curve. Figure shows a somewhat exaggerated relationship
between the ideal, or least squares fit, line and the actual measured or calibration line.
25
Fig 2.2: Nonlinearity Curve
7. Hysteresis: The hysteresis is an error of a sensor, which is defined as the maximum
difference in output at any measurement value within the sensor’s specified range when
approaching the point first with increasing and then with decreasing the input parameter. The
hysteresis error value is normally specified as a positive or negative percentage of the
specified input range.
26
8. Resolution: Resolution is the smallest detectable incremental change of input parameter
that can be detected in the output signal. Resolution can be expressed either as a proportion of
the full-scale reading or in absolute terms. For example, if a LVDT sensor measures a
displacement up to 20 mm and it provides an output as a number between 1 and 100 then the
resolution of the sensor device is 0.2 mm.
9. Stability: Stability is the ability of a sensor device to give same output when used to
measure a constant input over a period of time. The term ‘drift’ is used to indicate the change
in output that occurs over a period of time. It is expressed as the percentage of full range
output.
10.Repeatability: It specifies the ability of a sensor to give same output for repeated
applications of same input value. It is usually expressed as a percentage of the full range
output:
Repeatability = (maximum – minimum values given) X 100 ⁄ full range
11.Response time: Response time describes the speed of change in the output on a step-wise
change of the measurand. It is always specified with an indication of input step and the output
range for which the response time is defined.
2.5 Various Types of sensors
Sensors can be classified into various groups according to the factors such as measurand,
application fields, conversion principle and energy domain of the measurand. Detail
classification of sensors in view of their applications in manufacturing is as follows.
A. Displacement, position and proximity sensors
• Potentiometer
• Strain-gauged element
• Capacitive element •
• Inductive proximity switch
B. Force
• Strain gauge load cell
C. pressure
• Diaphragm pressure gauge
• Capsules, bellows, pressure tubes
• Piezoelectric sensors
D. Liquid flow
• Orifice plate
• Turbine meter
E. Temperature
• Resistance temperature detectors
• Thermistors
• Thermocouples
F. Light sensors
27
• Photo diodes
Sensors are basically used for the measurement of movement of an object. Position sensors
are employed to determine the position of an object in relation to some reference point.
Proximity sensors are a type of position sensor and are used to trace when an object has
moved with in particular critical distance of a transducer. Displacement sensors
2.5.1Potentiometer Sensors
Below Figure shows Schematic of a potentiometer sensor for measurement of linear
displacement. The potentiometer can be of linear or angular type. It works on the principle of
conversion of mechanical displacement into an electrical signal. The sensor has a resistive
element and a sliding contact (wiper). The slider moves along this conductive body, acting as
a movable electric contact. The object of whose displacement is to be measured is connected
to the slider by using
29
processing • Microelectronics • Air, gas and liquid temperature measurement in pipes and
tanks • Exhaust gas temperature measurement
2.5.2.2 Thermistors:
Thermistors follow the principle of decrease in resistance with increasing temperature. The
material used in thermistor is generally a semiconductor material such as a sintered metal
oxide (mixtures of metal oxides, chromium, cobalt, iron, manganese and nickel) or doped
polycrystalline ceramic containing barium titanate (BaTiO3) and other compounds. As the
temperature of semiconductor material increases the number of electrons able to move about
increases which results in more current in the material and reduced resistance. Thermistors are
rugged and small in dimensions. They exhibit nonlinear response characteristics. Thermistors
are available in the form of a bead (pressed disc), probe or chip
Applications of Thermistors
• To monitor the coolant temperature and/or oil temperature inside the engine • To monitor
the temperature of an incubator • Thermistors are used in modern digital thermostats • To
monitor the temperature of battery packs while charging • To monitor temperature of hot ends
of 3D printers • To maintain correct temperature in the food handling and processing industry
equipment’s • To control the operations of consumer appliances such as toasters, coffee
makers, refrigerators, freezers, hair dryers, etc.
2.5.2.3 Thermocouple:
Thermocouple works on the fact that when a junction of dissimilar metals heated, it produces
an electric potential related to temperature. As per Thomas Seebeck , when two wires
composed of dissimilar metals are joined at both ends and one of the ends is heated, then there
is a continuous current which flows in the thermoelectric circuit. Figure shows the schematic
of thermocouple circuit.
30
∆VAB = α ∆T
where α, the Seebeck coefficient, is the constant of proportionality.
Generally, Chromel (90% nickel and 10% chromium)–Alumel (95% nickel, 2% manganese,
2% aluminum and 1% silicon) are used in the manufacture of a thermocouple. Applications of
Thermocouples • To monitor temperatures and chemistry throughout the steel making process
• Testing temperatures associated with process plants e.g. chemical production and petroleum
refineries • Testing of heating appliance safety • Temperature profiling in ovens, furnaces and
kilns • Temperature measurement of gas turbine and engine exhausts • Monitoring of
temperatures throughout the production and smelting process in the steel, iron and aluminum
industry
2.5.7 Light sensors
A light sensor is a device that is used to detect light. There are different types of light sensors
such as photocell/photoresistor and photo diodes being used in manufacturing and other
industrial applications. Photoresistor is also called as light dependent resistor (LDR). It has a
resistor whose resistance decreases with increasing incident light intensity. It is made of a
high resistance semiconductor material, cadmium sulfide (CdS). The resistance of a CdS
photoresistor varies inversely to the amount of light incident upon it. Photoresistor follows the
principle of photoconductivity which results from the generation of mobile carriers when
photons are absorbed by the semiconductor material. Photoresistors are used in science and in
almost any branch of industry for control, safety, amusement, sound reproduction, inspection
and measurement.
Applications of photo resistor • Computers, wireless phones, and televisions, use ambient
light sensors to automatically control the brightness of a screen • Barcode scanners used in
retailer locations work using light sensor technology • In space and robotics: for controlled
and guided motions of vehicles and robots. The light sensor enables a robot to detect light. •
Auto Flash for camera • Industrial process control
Photo diodes
Photodiode is a solid-state device which converts incident light into an electric current. It is
made of Silicon. It consists of a shallow diffused p-n junction, normally a p-on-n
configuration. When photons of energy greater than 1.1eV (the bandgap of silicon) fall on the
device, they are absorbed and electron-hole pairs are created. The depth at which the photons
are absorbed depends upon their energy. The lower the energy of the photons, the deeper they
are absorbed. Then the electron-hole pairs drift apart. When the minority carriers reach the
junction, they are swept across by the electric field and an electric current establishes.
Photodiodes are one of the types of photodetector, which convert light into either current or
voltage. These are regular semiconductor diodes except that they may be either exposed to
detect vacuum UV or X-rays or packaged with a opening or optical fiber connection to allow
light to reach the sensitive part of the device. It is constructed from single crystal silicon
wafers. It is a p-n junction device. The upper layer is p layer. It is very thin and formed by
thermal diffusion or ion implantation of doping material such as boron. Depletion region is
narrow and is sandwiched between p layer and bulk n type layer of silicon. Light irradiates at
front surface, anode, while the back surface is cathode. The incidence of light on anode
generates a flow of electron across the p-n junction which is the measure of light intensity.
31
2.6 Actuator
An actuator is a device that actuates or moves something. An actuator uses some type of
energy to provide motion or to apply a force. For example, an electric motor uses electrical
energy to create a rotational movement or to turn on object, or to move an object. A tire jack
or screw jack uses mechanical energy to provide enough force lift a car. In short, an actuator
converts some type of energy into motion. Actuators include motors, gears, pumps, pistons,
valves, and switches.
DC Motor
A DC motor (Direct Current motor) is the most common type of motor. DC motors normally
have just two leads, one positive and one negative. If you connect these two leads directly to a
battery, the motor will rotate. If you switch the leads, the motor will rotate in the opposite
direction.
Electrical DC Motors are continuous actuators that convert electrical energy into mechanical
energy. The DC motor achieves this by producing a continuous angular rotation that can be
used to rotate pumps, fans, compressors, wheels, etc.
As well as conventional rotary DC motors, linear motors are also available which are capable
of producing a continuous liner movement. There are basically three types of conventional
electrical motor available: AC type Motors, DC type Motors and Stepper Motors.
The signals given by a transducer may be nonlinear in nature or may contain noise. Thus
before sending these signals to the mechatronics control unit it is essential to remove the
32
noise, nonlinearity associated with the raw output from a sensor or a transducer. It is also
needed to modify the amplitude (low/high) and form (analogue/digital) of the output signals
into respective acceptable limits and form which will be suitable to the control system. These
activities are carried out by using signal conditioning devices and the process is termed as
‘signal conditioning’.
Signal conditioning system enhances the quality of signal coming from a sensor in terms of:
1. Protection to protect the damage to the next element of mechatronics system such
microprocessors from the high current or voltage signals.
2. Right type of signal to convert the output signal from a transducer into the desired form i.e.
voltage / current
3. Right level of the signal to amplify or attenuate the signals to a right /acceptable level for
the next element.
4. Noise to eliminate noise from a signal.
5. Manipulation to manipulate the signal from its nonlinear form to the linear form.
2.8 Data conversion devices
ADC are an important component when it comes to dealing with digital systems
communicating with real-time signals. With IoT developing quickly to be applied in everyday
life, real-world/time signals have to be read by these digital systems to accurately provide
vital information. We’ll take a dive into how ADCs work and the theory behind them.
How ADCs Work
In the real world, analog signals are signals that have a continuous sequence with continuous
values (there are some cases where it can be finite). These types of signals can come from
sound, light, temperature and motion. Digital signals are represented by a sequence of discrete
values where the signal is broken down into sequences that depend on the time series or
sampling rate
Microcontrollers can’t read values unless it’s digital data. This is because microcontrollers
can only see “levels” of the voltage, which depends on the resolution of the ADC and the
system voltage.
ADCs follow a sequence when converting analog signals to digital. They first sample the
signal, then quantify it to determine the resolution of the signal, and finally set binary values
and send it to the system to read the digital signal. Two important aspects of the ADC are its
sampling rate and resolution.
he ADC’s sampling rate, also known as sampling frequency, can be tied to the ADC’s speed.
The sampling rate is measured by using “samples per second”, where the units are in SPS or
S/s (or if you’re using sampling frequency, it would be in Hz). This simply means how many
samples or data points it takes within a second. The more samples the ADC takes; the higher
frequencies it can handle.
One important equation on the sample rate is:
fs = 1/T
Where,
33
fs = Sample Rate/Frequency
T = Period of the sample or the time it takes before sampling again
For example, in Figure 1, it seems fs is 20 S/s (or 20 Hz), while T is 50 ms. The sample rate is
very slow, but the signal still came out similar to the original analog signal. This is because
the frequency of the original signal is a slow 1 Hz, meaning the frequency rate was still good
enough to reconstruct a similar signal.
“What happens when the sampling rate is considerably slower?” you might ask. It is
important to know the sampling rate of the ADC because you will need to know if it will
cause aliasing. Aliasing means that when a digital image/signal is reconstructed, it differs
greatly from the original image/signal caused from sampling.
If the sampling rate is slow and the frequency of the signal is high, the ADC will not be able
to reconstruct the original analog signal which will cause the system to read incorrect data.
One rule of thumb when figuring out if aliasing will happen is using Nyquist Theorem.
According to the theorem, the sampling rate/frequency needs to be at least twice as much as
the highest frequency in the signal to recreate the original analog signal. The following
equation is used to find the Nyquist frequency:
fNyquist = 2fMax
Where,
Where,
34
N = 2n
Where,
n = Bit Size
For example, let’s say that a sine waves with a voltage range of 5 needs to be read. The ADC
has a bit size of 12-bit. Plug in 12 to n and N will be 4096. With that known and the voltage
reference set to 5V, you’ll have: Step Size = 5V/4096. You will find that the step size will be
around 0.00122V (or 1.22mV). This is accurate as the digital system will be able to tell when
the voltage changes on an accuracy of 1.22mV.
If the ADC was a very small bit length, let’s say only 2 bits, then the accuracy would reduce
to only 1.25V, which is very poor as it will only be able to tell the system of four voltage
levels (0V, 1.25V, 2.5V, 3.75V and 5V).
2.9 Factors driving adoption within the IoT
There are three primary factors driving the deployment of sensor technology: price,
capability, and size. As sensors get less expensive, “smarter,” and smaller, they can be used in
a wider range of applications and can generate a wider range of data at a lower cost.
• Cheaper sensors: The price of sensors has consistently fallen over the past several years as
shown in figure below, and these price declines are expected to continue into the future.
Sensors vary widely in price, but many are now cheap enough to support broad business
applications.
35
Fig 2.9: Microprocessor Clock Speed Improvement over the years
• Smaller sensors: There has been a rapid growth in the use of smaller sensors that can be
embedded in smartphones and wearables. Micro-electro-mechanical systems (MEMS)
sensors—small devices that combine digital electronics and mechanical components—have
the potential to drive wider IoT applications. The average number of sensors on a smartphone
has increased from three (accelerometer, proximity, ambient light) in 2007 to at least ten
(including advanced sensors such as fingerprint- and gesture-based sensors) in 2014.
Similarly, biosensors that can be worn and even ingested present new opportunities for the
health care industry.
A Temperature Sensor senses and measures the temperature and converts it into an electrical
signal. They have a major role in Environment, Agriculture and Industries. For example, these
sensors can detect the temperature of the soil, which is more helpful in the production of
crops. There are many types of temperature sensors and the commonly used are NTC
thermistor, Resistance Temperature Detectors RTDs, Thermocouples and Thermopiles. They
are efficient, easy to install and reliable that responds to human activity. The RTDs work on
the correlation between the metals and the temperature, as the resistance of the device is
directly proportional to the temperature. The widely used DHT 11 is the temperature and
humidity sensor, which is the basic, low-cost, digital and capacitive sensor.
The DHT11 is a basic, ultra-low-cost digital temperature and humidity sensor. It uses a
capacitive humidity sensor and a thermistor to measure the surrounding air, and spits out a
digital signal on the data pin (no analog input pins needed). It’s fairly simple to use, but
requires careful timing to grab data. The only real downside of this sensor is you can only get
new data from it once every 2 seconds, so when using our library, sensor readings can be up
to 2 seconds old.
37
Fig 2.10: DHT11Temperature sensor
TECHNICAL DETAILS
Low cost
3 to 5V power and I/O
2.5mA max current use during conversion (while requesting data)
Good for 20-80% humidity readings with 5% accuracy
Good for 0-50°C temperature readings ±2°C accuracy
No more than 1 Hz sampling rate (once every second)
Body size 15.5mm x 12mm x 5.5mm
4 pins with 0.1" spacing
2.10.2 LDR
LDR is Light Dependent Resistor. LDRs are made from semiconductor materials to enable
them to have their light-sensitive properties. There are many types but one material is popular
and it is cadmium sulfide). These LDRs or PHOTO RESISTORS works on the principle of
“Photo Conductivity”. Now what this principle says is, whenever light falls on the surface of
the LDR (in this case) the conductance of the element increases or in other words, the resistance
of the LDR falls when the light falls on the surface of the LDR. This property of the decrease
in resistance for the LDR is achieved because it is a property of semiconductor material used
on the surface.
38
Fig 2.11: LDR
Vcc- The Vcc pin powers the sensor, typically with +5V
39
Trigger- Trigger pin is an Input pin. This pin has to be kept high for 10us to initialize
measurement by sending US wave.
Echo- Echo pin is an Output pin. This pin goes high for a period of time which will be equal
to the time taken for the US wave to return back to the sensor.
In today’s world, we encounter different scenario where we see different gasses being emitted
in atmosphere such as home appliances like air conditioner and industrial chimneys. Monitoring
of these gasses is very important with safety point of view. Gas Sensors are very helpful in
accomplishing this task. Small nose like sensor spontaneously respond to the alteration of gas.
The gas sensor module consists of a steel exoskeleton under which a sensing element is housed.
This sensing element is subjected to current through connecting leads. This current is known as
40
heating current through it, the gases coming close to the sensing element get ionized and are
absorbed by the sensing element. This changes the resistance of the sensing element which
alters
the value of current going out of it.
The Relay Module is a convenient board which can be used to control high voltage, high
current load such as motor, solenoid valves, lamps and AC load. It is designed to interface
with microcontroller such as Arduino, PIC and etc. The relay module we are going to use is
the SRD-05VDC-SL-C. It runs on 5V and we can control it with any micro-controller.
The Arduino relay module can be used in two states which are
In the normally open state, the initial output of the relay will be low when it will be powered.
In this state, the common and the normally open pins are used.
In the normally closed state, the initial output of the relay will be high when it will be
powered. In this state, the common and the normally close pins are used.
43
Chapter 3
Networking Fundamentals for IoT
The merging of computers & communications has had a profound influence on the way
computer systems are organized. The concept of the computer center as a room with a large
computer to which users bring their work for processing is now totally obsolete. The old model
of single computer serving all of the organizations computational needs has been replaced by
one in which a large number of separate but interconnected computers do the job. These systems
are called computer networks.
These days, even the smallest organization has a connection to the Internet. Almost all
companies have websites and have their presence on the World Wide Web. Companies now
operate on networks and do get customers via internet.
Computer networks help users on the network to share the resources and in communication.
Can you imagine a world now without emails, online newspapers, blogs, chat and the other
services offered by the internet?
44
The following are the important uses and benefits of a computer network.
File sharing: Networking of computers helps the network users to share data files.
Hardware sharing: Users can share devices such as printers, scanners, CD-ROM drives,
hard drives etc. Without computer networks, device sharing is not possible.
Application sharing: Applications can be shared over the network, and this allows to
implement client/server applications.
User communication: Networks allow users to communicate using e-mail, newsgroups, and
video conferencing etc.
Network gaming: A lot of network games are available, which allow multi-users to play from
different locations.
Voice over IP (VoIP): Voice over Internet Protocol (IP) is a revolutionary change in
telecommunication which allows to send telephone calls (voice data) using standard Internet
Protocol (IP) rather than by traditional PSTN.
46
Fig 3.3: optical fiber
A fiber optic cable carries signals in the form of fluctuating light in a glass or plastic cable. An
optical fiber cable consists of a glass or plastic core surrounded by a cladding of a similar
material but with a lower refractive index. The core transmits the light while the change in
refractive index. The core transmits the light while the change in refractive index between the
core and the cladding causes total internal reflection, thus minimizing the loss of light from
fiber.
As light waves gave a much wider wand width then the electrical then the electrical signal and
are immune from electromagnetic interferences, this leads to high data transfer rate of about
1000 mega bites per second & can be used for long & medium distance transmission links.
Topologies
BUS Topology
Bus topology is shown below all stations are connected to a single communication line. This
single communication line is referred to a bus. Information frames originating at a station are
propagated away from the station in both directions on the bus. Each station on the bus
interrogates the information frame destination address failed for its on addresses. If the
destination failed does not match the station address, the station discards the information frame
back on to the bus. If the destination address matches the station addresses, it accepts the
information frame & processes the frame.
47
Fig 3.5: Ring topology
A ring topology is shown below. Local area network that have each station attached to an
adjacent station using point to point links from a physical ring. Each station attached and active
to the ring regenerate the information frame, then retransmits the information frame on the ring.
Star Topology
The Open System Interconnection (OSI) reference model describes how information from a
software application in one computer moves through a network medium to a software
application in another computer. The OSI reference model is a conceptual model composed of
seven layers, each specifying particular network functions. The model was developed by the
International Organization for Standardization (ISO) in 1984, and it is now considered the
primary architectural model for inter-computer communications. The OSI model divides the
tasks involved with moving information between networked computers into seven smaller,
more manageable task groups. A task or group of tasks is then assigned to each of the seven
OSI layers. Each layer is reasonably self-contained so that the tasks assigned to each layer can
be implemented independently. This enables the solutions offered by one layer to be updated
without adversely affecting the other layers.
The OSI Reference Model includes seven layers:
7. Application Layer: Provides Applications with access to network services.
6. Presentation Layer: Determines the format used to exchange data among networked
computers.
5. Session Layer: Allows two applications to establish, use and disconnect a connection
between them called a session. Provides for name recognition and additional functions like
security, which are needed to allow applications to communicate over the network.
4. Transport Layer: Ensures that data is delivered error free in sequence and with no loss,
duplications or corruption. This layer also repackages data by assembling long messages into
lots of smaller messages for sending, and repackaging the smaller messages into the
original larger message at the receiving end.
49
3. Network Layer: This is responsible for addressing messages and data so they are sent to the
correct destination, and for translating logical addresses into physical addresses. This layer is
also responsible for finding a path through the network to the destination computer.
2. Data-Link Layer: This layer takes the data frames or messages from the Network Layer and
provides for their actual transmission. At the receiving computer, this layer receives the
incoming data and sends it to the network layer for handling. The Data-Link Layer also
provides error-free delivery of data between the two computers by using the physical layer. It
does this by packaging the data from the Network Layer into a frame, which includes error
detection information. At the receiving computer, the Data-Link Layer reads the incoming
frame, and generates its own error detection information based on the received frames data.
After receiving the entire frame, it then compares its error detection value with that of the
incoming frames, and if they match, the frame has been received correctly.
1. Physical Layer: Controls the transmission of the actual data onto the network cable. It
defines the electrical signals, line states and encoding of the data and the connector types used.
An example is 10BaseT.
3.2.1 Characteristics of the OSI Layers
The seven layers of the OSI reference model can be divided into two categories: upper layers
and lower layers as shown in fig below
The upper layers of the OSI model deal with application issues and generally are implemented
only in software. The highest layer, the application layer, is closest to the end user. Both users
and application layer processes interact with software applications that contain a
communications component. The term upper layer is sometimes used to refer to any layer above
another layer in the OSI model.
50
The lower layers of the OSI model handle data transport issues. The physical layer and the data
link layer are implemented in hardware and software. The lowest layer, the physical layer, is
closest to the physical network medium (the network cabling, for example) and is responsible
for actually placing information on the medium.
3.2.2 Protocols
The OSI model provides a conceptual framework for communication between computers,
but the model itself is not a method of communication. Actual communication is made possible
by using communication protocols. In In the context of data networking, a protocol is a formal
set of rules and conventions that governs how computers exchange information over a
network medium. A protocol implements the functions of one or more of the OSI layers.
A wide variety of communication protocols exist. Some of these protocols include LAN
protocols, WAN protocols, network protocols, and routing protocols. LAN protocols operate at
the physical and data link layers of the OSI model and define communication over various LAN
media. WAN protocols operate at the lowest three layers of the OSI model and define
communication over the various wide-area media. Routing protocols are network layer
protocols that are responsible for exchanging information between routers so that the routers
can select the proper path for network traffic. Finally, network protocols are the various upper-
layer protocols that exist in a given protocol suite. Many protocols rely on others for operation.
For example, many routing protocols use network protocols to exchange information between
routers. This concept of building upon the layers already in existence is the foundation of the
OSI model.
Information being transferred from a software application in one computer system to a software
application in another must pass through the OSI layers. For example, if a software application
in System A has information to transmit to a software application in System B, the application
program in System A will pass its information to the application layer (Layer 7) of
System A. The application layer then passes the information to the presentation layer (Layer
6), which relays the data to the session layer (Layer 5), and so on down to the physical layer
(Layer 1). At the physical layer, the information is placed on the physical network medium and
is sent across the medium to System B. The physical layer of System B removes the information
from the physical medium, and then its physical layer passes the information up to the data link
layer (Layer 2), which passes it to the network layer (Layer 3), and so on, until it reaches the
application layer (Layer 7) of System B. Finally, the application layer of System B passes the
information to the recipient application program to complete the communication process.
3.2.4 Interaction Between OSI Model Layers
.
51
Fig 3.9: OSI layers communicating with each other
A given layer in the OSI model generally communicates with three other OSI layers: the layer
directly above it, the layer directly below it, and its peer layer in other networked computer
systems. The data link layer in System A, for example, communicates with the network layer
of System A, the physical layer of System A, and the data link layer in System B. Figure1.9
illustrates this example.
3.3. Encapsulation and Layered Communication
As data is passed from the user application down the virtual layers of the OSI model, each layer
adds a header (and sometimes a trailer) containing protocol information specific to that layer.
These headers are called Protocol Data Units (PDUs), and the process of adding these headers
is called encapsulation. Note that in the TCP/IP protocol suite only the lower layers perform
encapsulation, generally. For example, a Transport layer protocol such as TCP will add a header
containing flow control, port numbers, and sequencing. The Network layer header contains
logical addressing information, and the Data-link header contains physical addressing and other
hardware specific information.
The PDU of each layer is identified with a different term:
Each layer communicates with the corresponding layer on the receiving device. For example,
on the sending device, source and destination hardware addressing is placed in a Data-link
52
header. On the receiving device, that Data-link header is processed and stripped away
(decapsulated) before being sent up to the Network and other upper layers. Network devices
are commonly identified by the OSI layer they operate at; or, more specifically, what header or
PDU the device processes. For example, switches are generally identified as Layer-2 devices,
as switches process information stored in the Data-Link header of a frame, such as Ethernet
MAC addresses. Similarly, routers are identified as Layer- 3 devices, as routers process logical
addressing information in the Network header of a packet, such as IP addresses.
Encapsulation Illustrated
The following illustrates how basic encapsulation occurs with the TCP/IP stack, which typically
performs encapsulation only at the lower layers:
During encapsulation on the sending host:
• Data from the user application is handed off to the Transport layer.
• The Transport layer adds a header containing protocol-specific information, and then hands
the segment to the Network layer.
• The Network layer adds a header containing source and destination logical addressing, and
then hands the packet to the Data-Link layer.
• The Data-Link layer adds a header containing source and destination physical addressing and
other hardware-specific information.
• The Data-Link frame is then handed off to the Physical layer to be transmitted on the network
medium as bits.
53
• The Network layer processes its header, strips it off, and then hands it off to the Transport
layer.
• The Transport layer processes its header, strips it off, and then hands the data to the user
application.
3.4 Networking devices used at the Layers
Bridges
Bridges are used to connect two LANs that use identical LAN protocols over a wide area. The
bridge acts as an address filter which picks up packets from one LAN that are identical for a
destination on the another LAN and passes these packets on the network. Bridges operate at the
data link layer (layer 2) of the OSI model. As all devices use the same protocols, the amount of
processing required at the bridge is minimal. If the distance between the two LANs is large, the
user would require two additional bridges at either end of the communication link. Besides a
point to point link, the intervening communication facility can be a network such as a wide area
packet switching network in such case the bridges need to add X. 25 link layer header and
trailer.
Routers
Routers can be used to connect networks that may not be similar. It is used at network layer in
OSI model. Routers provide connectivity between two LANs or two WANs over large
geographical distance. Routers operate at the network layer (layer 3) of the OSI model. All
routers participate in routing protocols to access the network topology, and based on this
information router computes the best route from a sender to the receiver. For large wide area
network spanning thousands of kilometers, the normal practice is to put network routers at
suitable locations to minimize link cost for leased link and provide adequate reliability from
link failures. Networks and other system are then connected to the nearest router.
Gateways
Gateways are used to connect to dissimilar LANs. The term gateway and routers are used
interchangeably, though there is a subtle difference between the two. A router operates at the
network layer (layer 3) of the OSI model, whereas a gateway operates on the application layer
(layer 7) of the OSI model. A gateway is required to convert data packets from one protocol
format to another before forwarding it, as it connects two dissimilar networks.
Switches and Hubs
Switches are higher-performance alternatives to hubs. Both pass data between devices
connected to them. Hubs do so by broadcasting the data to all other connected devices, while
switches first determine which device is the intended recipient of the data and then sends it to
that one device directly via a so-called "virtual circuit."
When four computers are connected to a hub, for example, and two of those computers
communicate with each other, hubs simply pass through all network traffic to each of the four
computers. Switches, on the other hand, are capable of determining the destination of each
54
individual traffic element (such as an Ethernet frame) and selectively forwarding data to the
one computer that actually needs it.
This behaviour allows switches to generate less overall network traffic compared to hubs - a
big advantage on busy networks.
Hub is used at physical layer whereas switches are used at data link layer.
Functions of different layers of the OSI model are presented in this section.
The Physical Layer also referred to as Layer 1 is where everything connects together and
comprises of devices that do not translate the information flowing on the network, but only
pass it on. The physical layer is concerned with transmission of raw bits over a
communication channel. It specifies the mechanical, electrical and procedural network
interface specifications and the physical transmission of bit streams over a transmission
medium connecting two pieces of communication equipment. In simple terms, the physical
layer decides the following:
• Number of pins and functions of each pin of the network connector (Mechanical)
• Signal Level, Data rate (Electrical)
• Whether simultaneous transmission in both directions
• Establishing and breaking of connection
• Deals with physical transmission
The Physical Layer consists of things like:
i)The wires in the network, which could be Ethernet cables or fiber optic cables. Other
technology for sending signals such as infrared or micro wave.
ii)The connectors at the ends of the wires (used to join devices together)
iii) Repeaters (devices that amplify any signal coming in without checking the signal)
iv)Hubs (devices used to join multiple computers together)
v)Devices that control the speed at which information is sent so that most of the information
makes it to its destination. These devices know the speed of the networks they are connected
to as in 10 Mbps or 100 Mbps and slow down or speed up the packets on the network.
55
The goal of the data link layer is to provide reliable, efficient communication between
adjacent machines connected by a single communication channel. Data link layer is most
reliable node to node delivery of data. It forms frames from the packets that are received
from network layer and gives it to physical layer. It also synchronizes the information which
is to be transmitted over the data.
The data link layer functionality is usually split it into logical sub-layers, the upper sub-layer,
termed as LLC, that interacts with the network layer above and the lower sub-layer, termed
as MAC, that interacts with the physical layer. While LLC is responsible for handling
multiple Layer3 protocols (multiplexing/de-multiplexing) and link services like reliability
and flow control, the MAC is responsible for framing and media access control for broadcast
media.
LLC Sublayer responsibilities:
The MAC sub-layer interacts with the physical layer and is primarily responsible for
framing/de-framing and collision resolution.
Framing/De-Framing and interaction with PHY: On the sending side, the MAC sub-
layer is responsible for creation of frames from network layer packets, by adding the frame
header and the frame trailer. While the frame header consists of layer2 addresses (known as
MAC address) and a few other fields for control purposes, the frame trailer consists of the
CRC/checksum of the whole frame. After creating a frame, the MAC layer is responsible for
interacting with the physical layer processor (PHY) to transmit the frame.
On the receiving side, the MAC sub-layer receives frames from the PHY and is responsible
for accepting each frame, by examining the frame header. It is also responsible for verifying
the checksum to conclude whether the frame has come uncorrupted through the link without
bit errors. Since checksum computation and verification are compute intensive tasks, the
framing/de-framing functionality is done by dedicated piece of hardware (e.g. NIC card on
PCs).
56
Collision Resolution: On shared or broadcast links, where multiple end nodes are connected
to the same link, there has to be a collision resolution protocol running on each node, so that
the link is used cooperatively. The MAC sub-layer is responsible for this task and it is the
MAC sub-block that implements standard collision resolution protocols like CSMA/CD,
CSMA etc. For half-duplex links, it is the MAC sub-layer that makes sure that a node sends
data on the link only during its turn. For full-duplex point-to-point links, the collision
resolution functionality of MAC sub-layer is not required.
Overall data link layer has following tasks:
1.Group the physical layer bit stream into units called frames. Note that frames are nothing
more than ``packets'' or ``messages''. By convention, we shall use the term ``frames'' when
discussing DLL packets.
2. Sender calculates the checksum and sends checksum together with data. The checksum
allows the receiver to determine when a frame has been damaged in transit or received correctly.
3. Receiver computes the checksum and compares it with the received value. If they differ, an
error has occurred and the frame is discarded.
4. Error control protocol returns a positive or negative acknowledgment to the sender. A
positive acknowledgment indicates the frame was received without errors, while a negative
acknowledgment indicates the opposite.
5. Flow control prevents a fast sender from overwhelming a slower receiver. For example, a
supercomputer can easily generate data faster than a PC can consume it.
6. In general, data link layer provides service to the network layer. The network layer wants to
be able to send packets to its neighbors without worrying about the details of getting it there in
one piece.
The third-lowest layer of the OSI Reference Model is the network layer. If the data link layer
is the one that basically defines the boundaries of what is considered a network, the network
layer is the one that defines how internetworks (interconnected networks) function. The
network layer is the lowest one in the OSI model that is concerned with actually getting data
from one computer to another even if it is on a remote network; in contrast, the data link layer
only deals with devices that are local to each other.
The basic purpose of the network layer is to provide an end-to-end communication.
Network Layer Functions
Some of the specific jobs normally performed by the network layer include:
Logical Addressing: Every device that communicates over a network has associated with it a
logical address, sometimes called a layer three address. For example, on the Internet, the
Internet Protocol (IP) is the network layer protocol and every machine has an IP address. Note
57
that addressing is done at the data link layer as well, but those addresses refer to local physical
devices. In contrast, logical addresses are independent of particular hardware and must be
unique across an entire internetwork.
Routing: Moving data across a series of interconnected networks is probably the defining
function of the network layer. It is the job of the devices and software routines that function at
the network layer to handle incoming packets from various sources, determine their final
destination, and then figure out where they need to be sent to get them where they are supposed
to go. Routing is the act of moving information across an internetwork from a source to a
destination. Along the way, at least one intermediate node typically is encountered. Routing is
often contrasted with bridging, which might seem to accomplish precisely the same thing to the
casual observer. The primary difference between the two is that bridging occurs at Layer 2 (the
link layer) of the OSI reference model, whereas routing occurs at Layer 3 (the network layer).
This distinction provides routing and bridging with different information to use in the process
of moving information from source to destination, so the two functions accomplish their tasks
in different ways.
Fragmentation and Reassembly: The network layer must send messages down to the data
link layer for transmission. Some data link layer technologies have limits on the length of any
message that can be sent. If the packet that the network layer wants to send is too large, the
network layer must split the packet up, send each piece to the data link layer, and then have
pieces reassembled once they arrive at the network layer on the destination machine.
Error Handling and Diagnostics: Special protocols are used at the network layer to allow
devices that are logically connected, or that are trying to route traffic, to exchange information
about the status of hosts on the network or the devices themselves.
58
.
3.5.5 Session Layer
This layer allows users on different machines to establish session between them. A
session allows ordinary data transport but it also provides enhanced services useful in some
applications. A session may be used to allow a user to log into a remote time-
sharing machine or to transfer a file between two machines. Some of the session related services
are:
1.This layer manages Dialogue Control. Session can allow traffic to go in both directions at the
same time, or in only one direction at one time.
2.Token management: For some protocols, it is required that both sides don't attempt same
operation at the same time. To manage these activities, the session layer provides tokens that
can be exchanged. Only one side that is holding token can perform the critical operation. This
concept can be seen as entering into a critical section in operating system using semaphores.
3.Synchronization: Consider the problem that might occur when trying to transfer a 4- hour file
transfer with a 2-hour mean time between crashes. After each transfer was aborted, the whole
transfer has to start again and again would probably fail. To Eliminate this problem, Session
layer provides a way to insert checkpoints into data streams, so that after a crash, only the data
transferred after the last checkpoint have to be repeated.
This layer is concerned with Syntax and Semantics of the information transmitted, unlike other
layers, which are interested in moving data reliably from one machine to other. Few of the
services that Presentation layer provides are:
1.Encoding data in a standard agreed upon way.
2.It manages the abstract data structures and converts from representation used inside 3omputer
to network standard representation and back.
The application layer consists of what most users think of as programs. The application does
the actual work at hand. Although each application is different, some applications are so useful
that they have become standardized. The Internet has defined standards for:
• File transfer (FTP): Connect to a remote machine and send or fetch an arbitrary file. FTP
deals with authentication, listing a directory contents, ASCII or binary files, etc.
59
• Remote login (telnet): A remote terminal protocol that allows a user at one site to establish a
TCP connection to another site, and then pass keystrokes from the local host to the remote host.
• Mail (SMTP): Allow a mail delivery agent on a local machine to connect to a mail delivery
agent on a remote machine and deliver mail.
• News (NNTP): Allows communication between a news server and a news client.
• Web (HTTP): Base protocol for communication on the World Wide Web.
Like OSI network model, TCP/IP also has a network model. TCP/IP was on the path of
development when the OSI standard was published and there was interaction between the
designers of OSI and TCP/IP standards. The TCP/IP model is not same as OSI model. OSI is
a seven-layered standard, but TCP/IP is a four layered standard. The OSI model has been very
influential in the growth and development of TCP/IP standard, and that is why much OSI
terminology is applied to TCP/IP. The following figure compares the TCP/IP and OSI
network models.
As we can see from the figure, presentation and session layers are not there in TCP/IP model.
Also note that the network access layer in TCP/IP model combines the functions of Datalink
Layer and Physical Layer.
How it differs from OSI model:
The OSI model is a “generic, protocol-independent standard”. The TCP/IP are regarded as the
standard around which the internet has developed.
TCP/IP is a simple model because of fewer layers (four) as compare to OSI that defined seven
layers in original version.
TCP/IP is more reliable model as compare to OSI model because the internet was developed
around it.
60
Fig 3.11: Comparison between seven layer OSI and four layer TCP/IP Models
The OSI model is bottom to up process of network connection whereas the TCP/IP is the top to
bottom process structure for internet purpose.
The TCP/IP combines the OSI data link and physical into network access layer.
61
Fig 3.20: IoT Stacks vs Web Stack
.
The Physical layer plays a vital role in establishing the communication channel. IoT’s
significance involves the following traits:
The above features can be achieved with effective Physical layer standards. IEEE 802.15.4
(ZigBee, 6LoWPAN, WirelessHART, Mi-Wi), IEEE 802.15.1 (Bluetooth Low Energy (BLE)
– Bluetooth 4.0), Near Field Communication (NFC), etc. are the standards set by specific
bodies such as IEEE (Institute of Electrical and Electronic Engineers) and proprietary vendors
(Z-Wave by SIGMA DESIGNS). We will discuss in detail about these Protocols and
standards in chapter five.
Network Layer
Once physical connectivity has been established, there has to be a unique method for
differentiating the devices operating in their own range. The network address plays a vital role
in identifying each device connected to the same router, similar to unique numbers or IDs
representing buses departing from a terminus at the same time.
62
In IoT, each alliance has its own network address. For instance, ZigBee is one alliance with its
own network addresses. Similarly, BLE and Z-Wave have their own network addresses
respective to their environments.
Wi-Fi devices come with IP stack in their chip, enabling IP-based connectivity. The IP layer
aids the respective devices to effectively communicate within their operating range.
6LoWPAN (IPv6 Low Power Wireless Personal Area Network) devices also operate in IEEE
802.15.4, but they have the network stack with IP connectivity (IPv6). As an analogy,
consider TV remotes which could be operated on the internet.
Transport Layer
The Transport layer plays the role of advanced safes and locking mechanisms in networks and
data exchanges. IoT networks, being low-powered, are easily prone to attacks. The Transport
layer has to be embedded with efficient security features, in addition to being responsible for
effective bandwidth consumption and session maintenance.
The applications developed on top of the Transport layer have to select the appropriate
Transport layer protocol for effective power and bandwidth preservation.
Application Layer
Finally, the application layer serves as the interface between the user and the desired sensor
application. Protocols such as HTTP/HTTPS (Hyper Text Transfer Protocol – Secure) have
been in existence ever since IP began. A common browser makes use of HTTP. With IoT,
protocols such as Message Queuing Telemetry Protocol (MQTT), Advanced Message
Queuing Protocol (AMQP), Constrained Application Protocol (CoAP), etc., have emerged
significantly. For instance, Adhaar card makes use of AMQP, and Facebook Messenger uses
the MQTT protocol.
63
Chapter 4
IoT hardware platforms
4.1 Importance of Hardware Platforms
In chapter 1 we discussed about the IoT architecture and we know that hardware platform is
integral part of IoT applications. With the help of these devices we can quickly develop IoT
based prototypes. IoT prototyping kits and development boards combine microcontrollers and
processors with wireless chips and other components in a pre-built, ready-to-program
package. They come in nearly infinite configurations, from tiny battery-powered chips that
chirp intermittently over Bluetooth to credit card-sized computers with USB power supplies
and high-bandwidth Wi-Fi radios. So there is plenty of development kits out there in the
market with various features integrated within them. As an IoT developer one should be
aware of configuration and specifications available in these boards so that one chooses the
board that fits exact requirement. In this chapter we will discuss various hardware platforms
in brief then we will discuss in detail about a particular hardware platform. We will use the
same platform for implementing IoT based experiments and application. In later chapters
some more platforms will be discussed in detail and we will use those platforms for
implementing IoT based applications.
Microcontroller
64
decipher and apply the incoming data. It then uses its I/O peripherals to communicate and
enact the appropriate action.
Microcontrollers are used in a wide array of systems and devices. Devices often utilize
multiple microcontrollers that work together within the device to handle their respective tasks.
For example, a car might have many microcontrollers that control various individual systems
within, such as the anti-lock braking system, traction control, fuel injection or suspension
control. All the microcontrollers communicate with each other to inform the correct actions.
Some might communicate with a more complex central computer within the car, and others
might only communicate with other microcontrollers. They send and receive data using their
I/O peripherals and process that data to perform their designated tasks.
The processor (CPU) -- A processor can be thought of as the brain of the device. It processes
and responds to various instructions that direct the microcontroller's function. This involves
performing basic arithmetic, logic and I/O operations. It also performs data transfer
operations, which communicate commands to other components in the larger embedded
system.
Memory -- A microcontroller's memory is used to store the data that the processor receives
and uses to respond to instructions that it's been programmed to carry out. A microcontroller
has two main memory types:
1. Program memory, which stores long-term information about the instructions that the CPU
carries out. Program memory is non-volatile memory, meaning it holds information over time
without needing a power source.
2. Data memory, which is required for temporary data storage while the instructions are being
executed. Data memory is volatile, meaning the data it holds is temporary and is only
maintained if the device is connected to a power source.
65
I/O peripherals -- The input and output devices are the interface for the processor to the
outside world. The input ports receive information and send it to the processor in the form of
binary data. The processor receives that data and sends the necessary instructions to output
devices that execute tasks external to the microcontroller.
While the processor, memory and I/O peripherals are the defining elements of the
microprocessor, there are other elements that are frequently included. The term I/O
peripherals itself simply refers to supporting components that interface with the memory and
processor. There are many supporting components that can be classified as peripherals.
Having some manifestation of an I/O peripheral is elemental to a microprocessor, because
they are the mechanism through which the processor is applied.
Analog to Digital Converter (ADC) -- An ADC is a circuit that converts analog signals to
digital signals. It allows the processor at the center of the microcontroller to interface with
external analog devices, such as sensors.
Digital to Analog Converter (DAC) -- A DAC performs the inverse function of an ADC and
allows the processor at the center of the microcontroller to communicate its outgoing signals
to external analog components.
System bus -- The system bus is the connective wire that links all components of the
microcontroller together.
Serial port -- The serial port is one example of an I/O port that allows the microcontroller to
connect to external components. It has a similar function to a USB or a parallel port but
differs in the way it exchanges bits.
Microcontroller features
A microcontroller's processor will vary by application. Options range from the simple 4-bit, 8-
bit or 16-bit processors to more complex 32-bit or 64-bit processors. Microcontrollers can use
volatile memory types such as random access memory (RAM) and non-volatile memory types
66
-- this includes flash memory, erasable programmable read-only memory (EPROM) and
electrically erasable programmable read-only memory (EEPROM).
When they first became available, microcontrollers solely used assembly language. Today,
the C programming language is a popular option. Other common microprocessor languages
include Python and JavaScript.
MCUs feature input and output pins to implement peripheral functions. Such functions
include analog-to-digital converters, liquid crystal display (LCD) controllers, real-time clock
(RTC), universal synchronous/asynchronous receiver transmitter (USART), timers, universal
asynchronous receiver transmitter (UART) and universal serial bus (USB) connectivity.
67
Sensors gathering data related to humidity and temperature, among others, are also often
attached to microcontrollers.
Types of microcontrollers
Common MCUs include the Intel MCS-51, often referred to as an 8051 microcontroller,
which was first developed in 1985; the AVR microcontroller developed by Atmel in 1996; the
programmable interface controller (PIC) from Microchip Technology; and various licensed
Advanced RISC Machines (ARM) microcontrollers.
Microcontroller applications
Microcontrollers are used in multiple industries and applications, including in the home and
enterprise, building automation, manufacturing, robotics, automotive, lighting, smart energy,
industrial automation, communications and internet of things (IoT) deployments.
One very specific application of a microcontroller is its use as a digital signal processor.
Frequently, incoming analog signals come with a certain level of noise. Noise in this context
means ambiguous values that cannot be readily translated into standard digital values. A
microcontroller can use its ADC and DAC to convert the incoming noisy analog signal into an
even outgoing digital signal.
68
scenarios, microcontrollers can regulate the operations of an artificial heart, kidney or other
organs. They can also be instrumental in the functioning of prosthetic devices.
The distinction between microcontrollers and microprocessors has gotten less clear as chip
density and complexity has become relatively cheap to manufacture and microcontrollers
have thus integrated more "general computer" types of functionality. On the whole, though,
microcontrollers can be said to function usefully on their own, with a direct connection to
sensors and actuators, where microprocessors are designed to maximize compute power on
the chip, with internal bus connections (rather than direct I/O) to supporting hardware such as
RAM and serial ports. Simply put, coffee makers use microcontrollers; desktop computers use
microprocessors. Microcontrollers are less expensive and use less power than
microprocessors. Microprocessors do not have built-in RAM, read-only memory (ROM) or
other peripherals on the chip, but rather attach to these with their pins. A microprocessor can
be considered the heart of a computer system, whereas a microcontroller can be considered
the heart of an embedded system.
There are a number of technology and business considerations to keep in mind when choosing
a microcontroller for a project.
Beyond cost, it is important to consider the maximum speed, amount of RAM or ROM,
number or types of I/O pins on an MCU, as well as power consumption and constraints and
development support.
69
The Raspberry pi is a single computer board with credit card size, that can be used for many
tasks that your computer does, like games, word processing, spreadsheets and also to play HD
video. It was established by the Raspberry pi foundation from the UK. It has been ready for
public consumption since 2012 with the idea of making a low-cost educational
microcomputer for students and children. The main purpose of designing the raspberry pi
board is, to encourage learning, experimentation and innovation for school level students. The
raspberry pi board is a portable and low cost. Maximum of the raspberry pi computers is used
in mobile phones. In the 20th century, the growth of mobile computing technologies is very
high, a huge segment of this being driven by the mobile industries. The 98% of the mobile
phones were using ARM technology. The Raspberry Pi is a very cheap computer that runs
Linux, but it also provides a set of GPIO (general purpose input/output) pins that allow you to
control electronic components for physical computing and explore the Internet of Things
(IoT). Raspberry Pi is the best choice for data-heavy connected devices like hubs, gateways,
datum collectors or personal cloud servers.
The raspberry pi board comprises a program memory (RAM), processor and graphics chip,
CPU, GPU, Ethernet port, GPIO pins, Xbee socket, UART, power source connector. And
various interfaces for other external devices. It also requires mass storage, for that we use an
SD flash memory card. So that raspberry pi board will boot from this SD card similarly as a
PC boots up into windows from its hard disk.
70
specifications include USB mouse, powered USB hub, case, internet connection, the Model A
or B: USB WiFi adaptor is used and internet connection to Model B is LAN cable.
Memory
The raspberry pi model Aboard is designed with 256MB of SDRAM and model B is designed
with 51MB.Raspberry pi is a small size PC compare with other PCs. The normal PCs RAM
memory is available in gigabytes. But in raspberry pi board, the RAM memory is available
more than 256MB or 512MB
The Central processing unit is the brain of the raspberry pi board and that is responsible for
carrying out the instructions of the computer through logical and mathematical operations. The
raspberry pi uses ARM11 series processor, which has joined the ranks of the Samsung galaxy
phone.
The GPU is a specialized chip in the raspberry pi board and that is designed to speed up the
operation of image calculations. This board designed with a Broadcom video core IV and it
supports OpenGL
Ethernet Port
The Ethernet port of the raspberry pi is the main gateway for communicating with additional
devices. The raspberry pi Ethernet port is used to plug your home router to access the internet.
GPIO Pins
The general purpose input & output pins are used in the raspberry pi to associate with the other
electronic boards. These pins can accept input & output commands based on programming
raspberry pi. The raspberry pi affords digital GPIO pins. These pins are used to connect other
electronic components. For example, you can connect it to the temperature sensor to transmit
digital data.
XBee Socket
The XBee socket is used in raspberry pi board for the wireless communication purpose.
The power source cable is a small switch, which is placed on side of the shield. The main
purpose of the power source connector is to enable an external power source.
UART
71
The Universal Asynchronous Receiver/ Transmitter is a serial input & output port. That can be
used to transfer the serial data in the form of text and it is useful for converting the debugging
code.
Display
The connection options of the raspberry pi board are two types such as HDMI and Composite.
Many LCD and HD TV monitors can be attached using an HDMI male cable and with a low-
cost adaptor. The versions of HDMI are 1.3 and 1.4 are supported and 1.4 version cable is
recommended. The O/Ps of the Raspberry Pi audio and video through HMDI, but does not
support HDMI I/p. Older TVs can be connected using composite video. When using a
composite video connection, audio is available from the 3.5mm jack socket and can be sent to
your TV. To send audio to your TV, you need a cable which adjusts from 3.5mm to double
RCA connectors.
72
Fig 4.2: Hardware Specification of Raspberry Pi
The Raspberry Pi launched in 2012, and there have been several iterations and variations
released since then. So based on the requirement of the project we should choose appropriate
model. When you are in the process of making a decision, you usually write down your
requirements; computers are no exception! Your first task is to determine what is most
important for your project. Such requirements can usually be reduced to the following list.
73
Speed
Speed is sometimes one of the most important factors in a computing scenario. The faster a
computer is, the more work it can do before slowing down and becoming unresponsive. The
Raspberry Pi range of computers is very fast, compared to microcontrollers such as PIC,
AVR, and STM, but there is a noticeable difference between Pi computers.
The first Raspberry Pi computer, the model B, features a quad-core 32-bit ARM Cortex
processor, whereas the cheaper version, which was released shortly after the B, the model A,
has a single-core 700MHz ARM processor. This means the Raspberry Pi B can do four things
simultaneously across its separate cores, but tasks on a single core on the model B will be
approximately 30 percent faster than on the A (that, however, is one big assumption for many
reasons). The later models, such as the Raspberry Pi 3 B, have a 1.2GHz 64-bit quad-core
processor, which is not only faster than the Raspberry Pi 2, but it can handle larger data sizes.
RPi has a 1.5 GHz 64-bit ARM Cortex-A72CPU.
Memory
Memory can be critical in a computing environment if you need to run large programs. For
example, operating systems are notorious for using large amounts of RAM. So, if one is going
to be used, maximizing RAM would not be a bad move. The Raspberry Pi A computer has
between 256MB and 512MB of RAM, whereas the Raspberry 2 and 3B have 1GB; however,
this is shared with the GPU. The Compute devices’ RAM size ranges from 512MB to 1GB,
with the more advanced computers having the most memory. RPi 4 has RAM up to 4 GB.
Therefore, if RAM is important, you may need to look at the top-of-the-range Raspberry Pi
computers, such as the Raspberry 3 B. or RPi 4
I/O
If you want your computer to perform office tasks, such as writing letters and sending emails,
then using a laptop or PC will be the ideal choice. Raspberry Pi computers are used usually
because there is a need for I/O. The Raspberry Pi A and B computers are very good for
connecting to external circuits and devices since they contain pin headers. The 1 A has 8
GPIO, while the +1 A and B computers have 17 GPIO. Interestingly, the Raspberry Pi Zero,
despite its cost and size, has 17 GPIO, just like the model B.
74
4.2.2 ESP8266
The ESP8266 is a coin-size, low cost, WiFi microchip with TCP/IP stack and a 32-bit
microcontroller developed by a Chinese manufacturer called as Espressif Systems. A third-
party company, Ai- Thinker manufactured a module called ESP-01, which allows the
microcontroller to connect with the WiFi connections and make a simple TCP/IP connection.
It has 16 GPIO pins for inputs and outputs for Voltage, ground, receiver and transmitter data,
reset, chip power-down.
It also has a Serial Peripheral Interface (SPI), memory of 32 KiB instruction RAM and an 80
KiB user-data RAM. The VCC is +3.3 volt and it can handle up to 3.6 voltage. it has a
Software Development Kit (SDK) in which there is no need for a microcontroller and can be
directly programmed. It has two versions, one is from FreeRTOS and another one is callback.
also, there are a lot of open-source SDKs which includes NodeMCU, Arduino etc.
The latest ESP-12E has a special feature, it has an inclusion of on-board USB-UART and a
micro USB connector with a 3.3 voltage regulator to provide power to the both the boards and
the connectivity to the host computer called as the console. So it can be easily connected to
any boards, for example in NodeMCU with ESP8266.
4.3 Arduino
In this section we will discuss about Arduino in detail, for implementing IoT based
experiments we will use Arduino as hardware platforms.
Let’s start from the very beginning. What is the Arduino, and where did it begin?
The Arduino is not a single thing. It is a prototyping platform. The platform is a collection of
hardware, software, workflows (ways of doing things) and support networks (places where
75
you can find help and information) designed to help people create prototypes (and often,
finished products) very quickly.
All of these components are open source, meaning that their designs and source code is
available for anyone to copy and use.
A microcontroller is like a processor in your computer, except that it is very cheap, slower,
and it has many connectors for peripherals like sensors and switches.
As a result, microcontrollers are great for sensing and controlling applications, and you find
them everywhere: in your toaster, fridge, alarm system, in your car, printer and paper
shredder.
The Arduino was created by educators and students at the Interaction Design Institute Ivrea in
Ivrea, Italy. Massimo Banzi, one of the founders, was one of the instructors at Ivrea. At the
time, students were using expensive hardware to build their micro-controller based creations.
The Ivrea students and their instructors decided to build their microcontroller platform by
using a popular “AVR” microcontroller from Atmega, and a light version of the Wiring
development platform written by (then student) Hernando Barragan.
Wiring influenced the development of what we now call the “Arduino Language”.
The Arduino Language is, in fact, a simplified version of the C++ language. C++ is a general-
purpose programming language used in the world’s most critical infrastructure, virtually all
operating systems, desktop and smartphone applications. Learning a bit of C++ is definitely
not a waste of time.
The Arduino Integrated Development Environment (IDE) is also inherited from Wiring.
Arduino Boards
Wiring
The Wiring Board was designed by Hernando Barragán, then a student at Interaction Design
Institute Ivrea (IDII). This board looked a bit like what a modern Arduino looks like.
Massimo Banzi and Casey Reas were Hernando’s thesis supervisors.
76
Fig 4.6 : Wiring Board
The Wiring Board contains the basic features so common in modern Arduino boards: a USB
connection for uploading programs and for communications, an Atmega microcontroller, pins
arranged along the edges, an onboard LED that you can control programmatically, and LED
that light up when a program is transferred via the USB port.
Arduino
A year later, Massimo Banzi and David Mellis forked (a programming term that describes a
copy of an original work) Wiring, and created the Arduino. The created the first Arduino
prototype, pictured below:
77
Fig 4.7: Arduino Prototype
And shortly after, the second prototype:
Fast-forward to today, and in 2020 there are around 15 active and many more retired official
Arduinos.
Because Arduino is open source hardware, there are many more Arduino compatible boards,
made by countless manufacturers. You can make your own, if you wish.
Arduino Uno
As a beginner in Arduino and electronics, the Arduino Uno is recommended; this is the
classic Arduino board. It is hard to destroy by miswiring , has tons of high-quality
documentation, example sketches, and libraries while still surprisingly capable. It is relatively
easy to expand as your projects grow.
79
Arduino Pro Mini
If you are looking to build a project that requires small size, you can go for one of the small
footprint Arduinos, like the Pro Mini or the Micro. These boards contain the bare-essential
hardware. It contains all of the functionality of the Uno except for the USB.
The two example boards, the Uno and the Pro Mini, share the same basic architecture, and are
powered by the same microcontroller. This means that your circuits and sketches work the
same way on these boards.
Arduino Mega
There are also Arduinos based on more capable microcontrollers, like the Mega, or even
microprocessors running Linux, like the Arduino Yún rev 2.
The Arduino Mega 2560 is a super-sized Arduino Uno with a faster microcontroller (the
ATmega2560) and many more input/output pins. This board is perfect for projects with a lot
of buttons, motors, sensors, and, really, a lot of everything.
80
Fig 4.11: Arduino Mega
Arduino Yún
The Arduino Yún rev 2, is essentially a computer combined with an Arduino. It runs a version
of Linux, has built-in Wifi capability and is made for Internet of Things applications.
81
Arduino Gemma and LilyPad
Worth mentioning are also the various wearable Arduinos. If you are interested in making
electronics that you can embed in clothing, then you can look at something like the super-tiny
Arduinos Gemma or LilyPad. These are small, battery-ready, low power Arduinos, and
circular so that they don’t catch onto fabrics.
Arduino is open source that means that its specifications are published so that anyone can
create their own compatible and custom design. It is easy to get lost in this variety of
alternatives, but it is advised is to start with the classic Arduino Uno.
Digital pins: 14 (These pins have only 2 states i.e. high or low or in simple words either 5 V or
0 V no in between values. These pins are mostly used to sense the voltage presence when switch
is open or close)
82
Analog pins: 6 (A0 to A5 and they come up with a resolution of 10 bits and they provide
flexibility of connecting any external device via these pins. These pins are configured from 0 V
to 5 V but they can be configured to high range by using AREF pin or analogReference ()
function. ADC (analog to digital convertor) is used to sample these pins. These pins take analog
signal and by using ADC convertor they convert this analog signal to number between 0 – 1023)
16 MHz crystal oscillator
32 general purpose registers
3 general purpose timers
Out of 14 digital pins, 6 can be used for PWM (pulse width modulation)
USB port
TX and RX pins (for serial communication)
Total 8 , 6 channel 10 bit ADC
SPI (serial peripheral interface)
External adaptor to deliver power to this board by external power supply up to 12 volts (board
will make use of its voltage regulator and will make this voltage up to 5 V or 3.3 V as per our
requirements)
Reset Pin: Used to reset our whole board and takes it to initial stage of running program. For
instance, our board gets hang in the middle of our running program then we can make use of
this pin and this pin will clear everything up and starts program from beginning
ICSP connector (Used to bypass USB port and interfacing our board directly as serial device.
This port is essential to reboot load our chip if it gets corrupted and we are not able to talk to
computer)
\
Fig 4.14: Arduino Uno components and Pin Configuration
To program the Arduino, you need to install the Arduino Integrated Development
Environment (IDE) on your computer.
To install the IDE on your computer you must first download it from arduino.cc. Then, you
will follow the installation process that depends on the operating system that is running on
your computer.
84
Fig 4.15: Arduino IDE
In the download page, scroll down to find the latest available version, and click on the
download file link that matches your operating system. Allow some time for the download to
complete. The, look for the installation file in your download folder.
85
How to install the Arduino IDE on Windows
On Windows, start by double-clicking on the installation file. Be ready for a long series of
confirmation dialogue boxes. In all of them, it is safe to accept the defaults.
A pop-up will ask you for permission to run the program, click on Yes to continue:
86
Accept the default installation location, and the file copy will begin:
You may be asked to install device drivers a couple of times. Click on “Install” to accept the
installation.
87
When the file copy process finishes, click “Close” to close the installer:
When the file copy process finishes, click “Close” to close the installer:
You can start the Arduino IDE just like any other Windows program. If you accepted the
default installation options, then you should be able to find the Arduino shortcut on the
desktop (see screenshot example below).
88
Upload your first sketch
Start the Arduino IDE. A few seconds later, you should see a new IDE window with a blank
sketch. It will look like the example below:
Continue to connect your Arduino to your computer via the USB cable. When connected, the
power LED on the Arduino should light up.
89
Fig 4.16: Arduino USB Interface
The Arduino is connected to your computer via a USB cable, and the power LED is lit
Go back to the Arduino IDE and load one of the examples, you can do this by clicking on
File, Examples, 01.Basics, Blink.
90
The Blink sketch will appear.
Before you can upload this sketch to your Arduino, there are two things you should check and
set. The Arduino board model, and the port to which it is connected. To check for the correct
board model, click on Tools, Board, and Arduino/Genuino Uno.
91
Next, check the port. Click on Tools, Port, /dev/cu/usbmodem7101 (Arduino/Genuino Uno)
or COM3. The port names may vary, but the name of the board should also appear in the
menu to help you identify the correct one.
With the settings verified, go ahead to upload. Click on the icon with the right arrow to start
the upload. When you click on this button, the button will turn yellow, and the IDE will first
compile and then upload the sketch to your connected Arduino.
92
Installing Library
Libraries are a collection of code that makes it easy for you to connect to a sensor, display,
module, etc. For example, the built-in Liquid Crystal library makes it easy to talk to character
LCD displays. There are hundreds of additional libraries available on the Internet for
download. The built-in libraries and some of these additional libraries are listed in the
reference. To use the additional libraries, you will need to install them.
93
Then the Library Manager will open and you will find a list of libraries that are already
installed or ready for installation. In this example we will install the Bridge library. Scroll the
list to find it, click on it, then select the version of the library you want to install. Sometimes
only one version of the library is available. If the version selection menu does not appear,
don't worry: it is normal.
94
Finally click on install and wait for the IDE to install the new library. Downloading may take
time depending on your connection speed. Once it has finished, an Installed tag should appear
next to the Bridge library. You can close the library manager.
You can now find the new library available in the Sketch > Include Library menu. If you want
to add your own library to Library Manager, follow these instructions.
In the Arduino IDE, navigate to Sketch > Include Library > Add .ZIP Library. At the top of
the drop down list, select the option to "Add .ZIP Library''.
You will be prompted to select the library you would like to add. Navigate to the .zip file's
location and open it.
Return to the Sketch > Include Library menu. You should now see the library at the bottom of
the drop-down menu. It is ready to be used in your sketch. The zip file will have been
expanded in the libraries folder in your Arduino sketches directory.
95
Manual installation
When you want to add a library manually, you need to download it as a ZIP file, expand it and
put in the proper directory. The ZIP file contains all you need, including usage examples if the
author has provided them. The library manager is designed to install this ZIP file
automatically as explained in the former chapter, but there are cases where you may want to
perform the installation process manually and put the library in the libraries folder of your
sketchbook by yourself.
You can find or change the location of your sketchbook folder at File > Preferences >
Sketchbook location.
Go to the directory where you have downloaded the ZIP file of the library
Extract the ZIP file with all its folder structure in a temporary folder, then select the main
folder, that should have the library name
96
Copy it in the “libraries” folder inside your sketchbook.
Start the Arduino Software (IDE), go to Sketch > Include Library. Verify that the library you
just added is available in the list.
97
The Arduino language
The Arduino language is C++. Most of the time, people will use a small subset of C++, which
looks a lot like C. If you are familiar with Java, then you will find C++ easy to work with, and
to recognize. The most important “high level” characteristic of C++ is that it is object-
oriented. In such a language, an object is a construct that combines functional code (the code
that does things like calculations and memory operations), with "state" (the results of such
calculations, or simply values, stored in variables).
Object orientation made programming much more productive in most types of applications
when compared with earlier paradigms because it allowed programmers to use abstractions to
create complicated programs.
For example, you could model an Ethernet adaptor as an object that contains attributes (like
it’s IP and MAC addresses) and functionality (like asking a DHCP server for network
configuration details). Programming with objects became the most common paradigm in
programming, and most modern languages, like Java, Ruby, and Python, have been
influenced heavily by C++.
Much of the sketch code you will be writing, and reading will be referencing libraries
containing definitions for objects (these definitions are called “classes”). Your original code,
to a large extent, will consist of “glue” code and customizations. This way, you can be
productive almost right away, by learning a small subset of C++.
The code that makes up your sketch must be compiled into the machine code that the
microcontroller on the Arduino can understand. This compilation is done by a special
98
program, the compiler. The Arduino IDE ships with an open-source C++, so you don’t have
to worry about the details. Imagine: every time you click the “Upload” button, the IDE starts
up the compiler which converts your human-readable code into ones and zeros, and then
sends it to the microcontroller via the USB cable.
As every useful programming language, C++ is made up of various keywords and constructs.
There are conditionals, functions, operators, variables, constructors, data structures, and many
other things.
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
This code contains two functions in it.
The first one is “setup()”. Anything you put in this function will be executed by the Arduino
just once when the program starts.
The second one is “loop()”. Once the Arduino finishes with the code in the setup() function, it
will move into a loop(), and it will continue running it in a loop, again and again, until you
reset it or cut off the power.
Notice that both setup() and loop() have open and close parenthesis? Functions can receive
parameters, which is a way by which the program can pass data between its different
functions. The setup and loop functions don’t have any parameters passed to them. If you add
anything within the parenthesis, you will cause the compiler to print out a compilation error
and stop the compilation process.
Every single sketch you write will have these two functions in it, even if you don’t use them.
In fact, if you remove one of them, the compiler again will produce an error message. They
are two of the few expectations of the Arduino language.
These two functions are required, but you can also make your own. Let’s look at this next.
Custom functions
99
A function is merely a group of instructions with a name. The Arduino IDE expects that the
setup() and loop() functions will be in your sketch, but you can make your own. Group
instructions inside functions is a good way of organizing your sketches, especially as they
tend to get bigger in size and complexity as you become a more confident programmer.
To create a function, you need a definition and the code that goes inside the curly brackets.
a return type
a name
a list of parameters
Here’s an example
The name (also known as the “identifier”) of the function is “do_a_calc”. You can name your
functions anything you like as long as you don’t use a reserved word (that is, a word that the
Arduino language already uses), it has no spaces or other special characters like “%”, “$” and
“#”. You can’t use a number as the first character. If in doubt, remember to only use letters,
numbers, and the underscore in your function names.
The first line of the body, we create a new variable, “c”, of type integer (“int”). We add a and
b and then assign the result to c.
And finally, in the second line of the body of the function, we return the value stored in “c” to
the caller of do_a_calc.
Let’s say that you would like to call do_a_calc from your setup function. Here’s a complete
example showing how to do that:
void setup() {
int number1=50;
int number2=100;
addition(number1,number2)
100
}
void loop() {
// put your main code here, to run repeatedly:
}
int addition(int a,int b)
{
return a+b
}
Comments
Any line that starts with “//” or multiple lines that start with “/*” and finish with “*/” contain
comments.
Comments are ignored by the compiler. They are meant to be read by the programmer.
Comments are used to explain the functionality of code or leave notes to other programmers
(or to self).
Scope
In the setup() function there is a definition of a variable with an identifier “a”. In function
do_a_calc there is also a definition of a variable with the same identifier (it makes no
difference that this definition is in the function definition line).
Having variables with the same name is not a problem as long as they are not in the same
scope. A scope is defined by the curly brackets. Any variable between an open and close curly
bracket is said to be within that scope. If there is a variable with the same name defined within
another scope, then there is no conflict.
Be careful when you choose a name for your variables. Problems with scopes can cause
headaches: you may expect that a variable is accessible at a particular part of your sketch,
only to realize that it is out of scope.
Also be careful to use good descriptive names for your variables. If you want to use a variable
to hold the number of a pin, call it something like:
101
int digital_pin = 1;
instead of
int p = 1;
Variables
A variable is a place to store a piece of data. It has a name, a value, and a type
creates a variable whose name is pin, whose value is 13, and whose type is int
Types of variable
void
The void keyword is used only in function declarations. It indicates that the function is expected
to return no information to the function from which it was called.
Example
Void Loop ( ) {
// rest of the code
}
Boolean
A Boolean holds one of two values, true or false. Each Boolean variable occupies one byte of
memory.
Example
Char
A data type that takes up one byte of memory that stores a character value. Character literals are
written in single quotes like this: 'A' and for multiple characters, strings use double quotes:
"ABC".
102
However, characters are stored as numbers. You can see the specific encoding in the ASCII
chart. This means that it is possible to do arithmetic operations on characters, in which the ASCII
value of the character is used. For example, 'A' + 1 has the value 66, since the ASCII value of
the capital letter A is 65.
Example
unsigned char
Unsigned char is an unsigned data type that occupies one byte of memory. The unsigned char
data type encodes numbers from 0 to 255.
Example
Unsigned Char chr_y = 121 ; // declaration of variable with type Unsigned char and initialize it
with character y
byte
Example
byte sensor_value = 25 ;
int
Integers are the primary data-type for number storage. int stores a 16-bit (2-byte) value. This
yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) -
1).
Example
int new_var = 32 ;
Unsigned int
Unsigned ints (unsigned integers) are the same as int in the way that they store a 2 byte value.
Instead of storing negative numbers, however, they only store positive values, yielding a useful
range of 0 to 65,535 (2^16) - 1). The Due stores a 4 byte (32-bit) value, ranging from 0 to
4,294,967,295 (2^32 - 1).
Example
103
Unsigned int new_var =100 ;
Word
On the Uno and other ATMEGA based boards, a word stores a 16-bit unsigned number. On the
Due and Zero, it stores a 32-bit unsigned number.
Example
Long
Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from
-2,147,483,648 to 2,147,483,647.
Example
short
A short is a 16-bit data-type. This yields a range of -32,768 to 32,767 (minimum value of -2^15
and a maximum value of (2^15) - 1).
Example
short new_var = 13 ;
Float
Data type for floating-point number is a number that has a decimal point. Floating-point
numbers are often used to approximate the analog and continuous values because they have
greater resolution than integers.
Floating-point numbers can be as large as 3.4028235E+38 and as low as -3.4028235E+38. They
are stored as 32 bits (4 bytes) of information.
Example
double
Double precision floating-point number occupies four bytes. That is, the double implementation
is exactly the same as the float, with no gain in precision.
Example
104
double new_var = 45.352
Programs are useful when the process data. Processing data is what programs do, all the time.
Programs will either get some data to process from a user (perhaps via a keypad). From a
sensor (like a thermistor that measures temperature), the network (like a remote database), a
local file system (like an SD Card), a local memory (like an EEPROM), and so many other
places.
THere is an example:
byte sensor_A_value;
This line defines a variable named “sensor_A_value”, which will hold a single byte in
memory. You can store a value in it like this:
sensor_A_value = 196;
You can print out this value to the serial monitor like this:
Serial.print(sensor_A_value);
The serial monitor is a feature of the Arduino IDE that allows you to get a text from the
Arduino displayed on your screen. More about this later, here I want to show you how to
retrieve the value stored in a variable. Just call its name. Also, remember the earlier
discussion about scope: the variable has to be within scope when it is called.
Another beautiful thing about a variable is that you can change the value stored in it. You can
take a new reading from the sensor and update the variable like this: sensor_A_value = 201;
sensor_A_value = 201;
No problem, the old value is gone, and the new value is stored.
array
An array is a consecutive group of memory locations that are of the same type. To refer to a
particular location or element in the array, we specify the name of the array and the position
number of the particular element in the array. Arrays in the C++ programming language
Arduino sketches are written in can be complicated, but using simple arrays is
relatively straightforward.
int myInts[6];
int myPins[] = {2, 4, 8, 3, 6};
int mySensVals[6] = {2, 4, -8, 3, 2};
char message[6] = "hello";
Accessing an Array
Arrays are zero indexed, that is, referring to the array initialization above, the first
element of the array is at index 0, hence
It also means that in an array with ten elements, index nine is the last element. Hence:
For this reason you should be careful in accessing arrays. Accessing past the end of an
array (using an index number greater than your declared array size - 1) is reading from
memory that is in use for other purposes. Reading from these locations is probably not
going to do much except yield invalid data. Writing to random memory locations is
definitely a bad idea and can often lead to unhappy results such as crashes or program
malfunction. This can also be a difficult bug to track down.
mySensVals[0] = 10;
106
x = mySensVals[4];
Constants
If there is a value that will not be changing in your sketch, you can mark it as a constant.
Constants have benefits regarding memory and processing speed, and it is a good habit to use
these.
Operators
Operators are special functions that operate one or more pieces of data.
Most people are familiar with the basic arithmetic functions, = (assignment), +, -, * and /, But
there are a lot more.
OPERATOR FUNCTION
Modulo operator. It returns the remainder
% of a division.
107
OPERATOR FUNCTION
!= → un-equality
Conditionals are useful when you want to change the flow of executing in your sketch. Loops
are useful when you want to repeat a block of code multiple times.
Let’s start with a conditional. Imagine you have a red light and a green light. You want to turn
the green light on when you press a button and the red light on when you leave the button not
pressed.
conditional: “if..else”
The most common of these is the if...else statement. Using pseudo code (that is, a program
written in English that looks a bit like a real program), you would implement this
functionality like this:
if (button == pressed)
{
green_light(on);
red_light (off);
} else
{
108
red_light(on);
green_light(off)
}
Code
1) void setup() {
2) int a;
3) int b;
4) int c;
5) a=10
6) b=7
7) c=8
8)
9) if (a>b)
10) {
11) if (b>c)
12) {
13) Serial.print("we are learning arduino");
14) }
15) else
16) {
17) serial.print("we don't want to learn arduino")
18) }
19) }
20)
21) }
22) else
23) {
24) Serial.print("we are learning pyton");
25) }
26)
27) void loop() {
28)
29)
30) }
109
loop: “while”
If you need to repeat a block of code based on a Boolean condition, you can use the while
conditional expression. For example, let’s say that you want to make a noise with a buzzer for
as long as you press a button. Using pseudo code again, you can do it like this:
while(button_is_pressed)
{
make_annoying_noise;
}
loop: “do_while”
You can do the same thing but do the check of the condition at the end of the block instead of
the start. This variation would look like this:
do
{
make_annoying_noise;
} while(button_is_pressed)
Example
void setup() {
byte sensor_value=100;
do
{
Serial.print(sensor_value);
sensor_vaule - = 1
delay(1000);
}while(sensor_value>50)
}
void loop() {
// put your main code here, to run repeatedly:
}
loop: “for”
If you know how many times you want to repeat code in a block, you can use the “for”
structure. Let’s say you can to blink a light 5 times.
110
Here’s how to do it:
for (n = 1 to 5)
{
Turn light on;
Turn light off;
}
Your light will turn on and then off 5 times. Inside the curly brackets, you will also have
access to the “n” variable which contains the number of a repeat at any given time. With is,
you could insert a conditional so that you leave the lights on before the last loop ends:
for (n = 1 to 5)
{
Turn light on;
if (n < 5) then Turn light off;
}
In this variation, the light will only turn off if the “n” variable is less than 5.
Example
Void setup()
Serial.begin(9600);
Generates: 2,3,4,6,9,13,19,28,42,63,94
Arrays are often manipulated inside for loops, where the loop counter is used as the
index for each array element. For example, to print the elements of an array over the
serial port, you could do something like this:
Conditional: “switch”
Another useful conditional is the Switch. If you have a variable, like button_pressed, that can
take a few valid values; you can do something like this with it:
int button_pressed;
switch (button_pressed)
{
case 1:
Blink light one time;
break;
case 2:
Blink light two times;
break;
case 3:
Blink light three times;
break;
default:
Don’t blink light;
}
The switch statement will check the value stored in the button_pressed variable. If it is “1”, it
will blink the light once, if it is “2”, it will blink the light twice, and if it is “3”, it will blink
three times. If it is anything else, it won’t blink the light at all (this is what the “default” case
is).
112
Classes and objects
You now know that the Arduino language is actually C++ with a lot of additional support
from software, the libraries which were mentioned earlier, that makes programming easy. It
was also said that C++ is an object-oriented programming language.
Let’s have a closer look at this feature and especially how it looks like in Arduino code.
Object-orientation is a technique for writing programs in a way that makes them easier to
manage as they grow in size and complexity. Essential, a software object is a model of
something that we want the computer (or an Arduino) to be able to handle programmatically.
Let’s take an example. Imagine that you have a robotic hand. The arm only has one finger and
can rotate by 360 degrees. The finger can be open or closed. You can model this hand in an
object-oriented way like in this pseudo-code:
class robotic_hand
{
//These variables hold the state of the hand
bool finger;
int rotation;
Inside the class, I define three kinds of components for the model (=class). First, a couple of
variables to hold the current state of the hand. If the hand is in an open position, the Boolean
variable “finger” will be “true”. If the hand is rotated at 90 degrees, the integer variable
“rotation” will contain “90”.
The second set of components are special functions that allow me to change the status of the
hand. For example, if the hand is currently open and I want to close it so that it can pick up an
object, I can call the “close_finger()” function. If I want to rotate it at 45 degrees, I can call
“rotate(45)”.
113
Finally, the third set of components are functions that allow me to learn about the status of the
hand. If I want to know if the hand is opened or closed, I can call “get_finger_position()”, and
this function will respond with “true” or “false”.
The names are up to me to choose so that their role is clear. A class hides within it
components such as these so that the programmer can think more abstractly about the thing
they are working with instead of the implementation details.
Let’s say now that you would like to use this class in your sketch. Here is an example of how
you would do it in Arduino:
#include <Robot_hand.h>
Robot_hand robot_hand();
void setup(){
}
void loop(){
robot_hand.open_finger();
robot_hand.rotate(45);
robot_hand.close_finger();
}
You would start by importing the Robot_hand library which contains the class you just
created into your Arduino sketch. You do this with the include statement in the first line of
your sketch.
In the second line, you create an object based on the Robot_hand class. Think about this for a
few moments: a class contains the blueprints of an object but is not an object. It is the
equivalent of a blueprint for a house, and the house itself. The blueprint is not a house, only
the instructions for building a house. The builder will use the blueprint as the instructions to
build a house.
Similarly, the robot hand class definition is only the instructions that are needed for building
the robot hand object in your sketch. In the second line of this example sketch, we are
defining a new object build based on the instructions in the Robot_hand class, and we give it
the name “robot_hand()”. The name of the object cannot be the same as the name of the class,
that is why it starts with a lowercase “r”.
In the loop() function, we can call the object’s functions to make the robot hand move. We
can open it using robot_hand.open_finger() and close it using robot_hand.close_finger().
Notice that these instructions start with the name of the object, “robot_hand”, followed by a
dot, then followed by the name of the function we want to call, “close_finger()”.
114
This is called “dot notation”, and is very common throughout most object-oriented
programming languages.
Inputs and output are a fundamental feature of the microcontroller. You can connect devices
to special pins on your Arduino, and read or change the state of these pins through special
instructions in your sketch.
There are two kinds of input and output pins on an Arduino: digital and an analog.
Digital pins
Digital pins are useful for reading the state of devices like buttons and switches or controlling
things like relays and transistors or LEDs. These examples have one thing in common: they
only have two possible states.
Digital Input
Digital pins can be used to take inputs from a input devices. digitalRead function can be used
to read the input inserted from the device and it will be stored store in some variable.
A button can be either pressed on not pressed. A switch can be on or off. A relay can be
energized or not.
If in your sketch you want to know the state of a button, you can connect it to a digital pin.
You can wire it up so that when the button is pressed, a 5V voltage is read by the connected
digital pin, and that is reported as “high” to your sketch.
When you press the button, the voltage conveyed by the yellow wire to digital pin 2 is 5V,
equivalent to “logical high”. This happens because when the button is pressed, internally the
red wire coming from the 5V source on the Arduino is connected electrically to the yellow
wire that goes to pin 2.
When the button is not pressed, the voltage at pin 2 is 0V, equivalent to “logical low”. This
happens because of the resistor in the schematic. When the button is not pressed, the yellow
wire is connected to the GND pin on the Arduino which is at 0V, and thus this level if
transmitted to pin 2.
You can read the state of the button in your Arduino sketch like this:
115
int buttonState = 0;
void setup() {
pinMode(2, INPUT);
}
void loop(){
buttonState = digitalRead(2);
if (buttonState == HIGH)
{
//Do something when the button is pressed
} else
{
//Do something else when the button is not pressed
}
}
First, create a variable to hold the state of the button.
Then, in the setup() method, tell the Arduino that you will be using digital pin 2 as an input.
Finally, in the loop(), take a reading from digital pin 2 and store it in the buttonState variable.
We can get the Arduino to perform a particular function when the button is in a particular
state by using the “if” conditional structure.
Digital Output
Digital pins can be used to change the state of any output device. Digital Write function will
be used to change the state of device connected on any digital pin.
We need to pass two parameters to the digitalWrite function. One is the number of the pins
whose state need to be changes and the other will be the state. There are only two finite state
in which a digital pin can be set-HIGH and LOW.
In this example we have a 5mm red LED connected to digital pin 13. We also have a small
resistor to prevent burning out the LED (it is a “current limiting resistor”). To turn the LED
on and off, we can use a sketch like this:
void setup()
{
pinMode(13, OUTPUT);
}
116
void loop()
{
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Just like the button example, first, we must tell the Arduino that we wish to use digital pin 13
as an output. We do this in the setup() function with pinMode(13,OUTPUT). In the loop()
function, we use the digitalWrite function to write logical “HIGH” and “LOW” to digital pin
13. Each time we change the state, we wait for 1000ms (=1 second). The Arduino has been
configured to translate logical HIGH to a 5V signal, and logical LOW to a 0V signal.
Analog I/0
The signals from sensors that measure surrounding natural factors such as temperature,
pressure, and flow rate are often analog signals, and most control actuators move according to
analog signals. On the other hand, only digital signals can be handled by computers. For this
reason, in order to input a signal from a sensor using a computer, or to output a signal to an
actuator, it's necessary to have a device that can bridge the analog signal and the digital signal
handled by the computer. That bridge is called an analog I/O interface.
Analog Input
As Arduino has inbuilt ADC of 10 bit, whatever analog value we read at analog input port will be
converted to a discrete value ranging from 0 to 1023
Let’s see an example where an LDR is connected to analog pin A0 and values are read
Serial.begin(9600);
pinMode(ldrPin, INPUT);
void loop(){
ldrStatus = analogRead(ldrPin);
println(ldrStatus)
}
Analog Output
PWM
Pulse Width Modulation, or PWM, is a technique for getting analog results with digital means.
Digital control is used to create a square wave, a signal switched between on and off. This on-
off pattern can simulate voltages in between full on (5 Volts) and off (0 Volts) by changing the
portion of the time the signal spends on versus the time that the signal spends off. The duration
of "on time" is called the pulse width. To get varying analog values, you change, or modulate,
that pulse width. If you repeat this on-off pattern fast enough with an LED for example, the
result is as if the signal is a steady voltage between 0 and 5v controlling the brightness of the
LED.
In the graphic below, the green lines represent a regular time period. This duration or period is
the inverse of the PWM frequency. In other words, with Arduino's PWM frequency at about
500Hz, the green lines would measure 2 milliseconds each. A call to analogWrite() is on a scale
of 0 - 255, such that analogWrite(255) requests a 100% duty cycle (always on), and
analogWrite(127) is a 50% duty cycle (on half the time) for example.
118
We have to switch the controlling pin because we want to simulate an analog signal through
the use of Pulse Width Modulation (PWM). Only a few of the pins on an Arduino can do this.
One of these pins is 9, which we are using in this example.
void setup() {
pinMode(ledPin,OUTPUT);
}
void loop() {
119
for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
analogWrite(ledPin, fadeValue);
delay(50);
}
In the middle of the loop() function, you will find a reference to the “analogWrite” function.
This function takes two arguments: the pin number, and an 8-bit PWM value.
In the example, the variable fadeValue contains a number that changes between 0 and 255 in
hops of 5 each time it is analogWrite is called because it is inside a “for” loop. When
fadeValue is at 0, then the analogWrite function keeps the output at pin 9 to 0V. When
fadeValue is at 255, then analogWrite keeps the output at pin 9 to 5V. When fadeValue is at
127, then analogWrite keeps the output at pin 9 at 0V for half of the time and 5V for the other
half.
Because the ATMEGA is a fully digital IC, it simulates analog by just switching between
digital high and low very quickly. For the LED to be brighter we give analogWrite a larger
value which simply increases the amount of time that the pin stays at logical high versus
logical low.
Arduino Interfacing
LED
A Light Emitting Diode (LED) is one of the latest inventions and is extensively used these
days. From your cell phone to the large advertising display boards, the wide range of
applications of these magical light bulbs can be witnessed almost everywhere. Today their
popularity and applications are increasing rapidly due to some remarkable properties they
have. Specifically, LEDs are very small in size and consume very little power. The
magnificent, beautiful, dazzling colors involved with LEDs may be quite picturesque, but do
120
you really know how these effects are actually created in them or rather how do LED light
bulbs work?
As is evident from its name, LED (Light Emitting Diode) is basically a small light emitting
device that comes under “active” semiconductor electronic components. It’s quite comparable
to the normal general purpose diode, with the only big difference being its capability to emit
light in different colors. The two terminals (anode and cathode) of a LED when connected to a
voltage source in the correct polarity, may produce lights of different colors, as per the
semiconductor substance used inside it.
Working Principle:
A light-emitting diode is a two-lead semiconductor light source. It is a p–n junction diode that
emits light when activated. When a suitable voltage is applied to the leads, electrons are able
to recombine with electron holes within the device, releasing energy in the form of photons.
This effect is called electroluminescence, and the color of the light (corresponding to the
energy of the photon) is determined by the energy band gap of the semiconductor.
By adding an impurity, which is known as doping, extra atoms are introduced, effectively
disturbing the balance of the material.
These impurities in the form of additional atoms are able either to provide free electrons (N-
type) into the system or suck out some of the already existing electrons from the atoms (P-
Type) creating “holes” in the atomic orbits. In both ways the material is rendered more
conductive. Thus in the influence of an electric current in N-type of material, the electrons are
able to travel from anode (positive) to the cathode (negative) and vice versa in the P-type of
121
material. Due to the virtue of the semiconductor property, current will never travel in opposite
directions in the respective cases.
From the above explanation, it’s clear that the intensity of light emitted from a source (LED in
this case) will depend on the energy level of the emitted photons which in turn will depend on
the energy released by the electrons jumping in between the atomic orbits of the
semiconductor material.
We know that to make an electron shoot from lower orbital to higher orbital its energy level is
required to be lifted. Conversely, if the electrons are made to fall from the higher to the lower
orbitals, logically energy should be released in the process.
In LEDs, the above phenomena is well exploited. In response to the P-type of doping,
electrons in LEDs move by falling from the higher orbitals to the lower ones releasing energy
in the form of photons i.e. light. The farther these orbitals are apart from each other, the
greater the intensity of the emitted light.
Different wavelengths involved in the process determine the different colors produced from
the LEDs. Hence, light emitted by the device depends on the type of semiconductor material
used.
Infrared light is produced by using Gallium Arsenide (GaAs) as a semiconductor. Red or
yellow light is produced by using Gallium-Arsenide-Phosphorus (GaAsP) as a semiconductor.
Red or green light is produced by using Gallium-Phosphorus (GaP) as a semiconductor.
Advantages of LEDs:
1. Very low voltage and current are enough to drive the LED.
4. The device does not need any heating and warm up time.
This example shows the simplest thing you can do with an Arduino to see physical output: it
blinks the on-board LED.
Hardware Required
Arduino Board
122
LED
220-ohm resistor
Circuit
This example uses the built-in LED that most Arduino boards have. This LED is connected to
a digital pin and its number may vary from board type to board type. To make your life easier,
we have a constant that is specified in every board descriptor file. This constant
is LED_BUILTIN and allows you to control the built-in LED easily.
If you want to light an external LED, you need to build this circuit, where you connect one
end of the resistor to the digital pin correspondent to the LED_BUILTIN constant. Connect the
long leg of the LED (the positive leg, called the anode) to the other end of the resistor.
Connect the short leg of the LED (the negative leg, called the cathode) to the GND. In the
diagram below we show an UNO board that has D13 as the LED_BUILTIN value.
The value of the resistor in series with the LED may be of a different value than 220 ohm; the
LED will lit up also with values up to 1K ohm.
CODE
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
123
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Button
Electrical circuits need to be complete to work. The electricity must be able to flow
uninterrupted through the various wires and components. But circuits that are complete all the
time aren't as useful as ones that work only when we want them to. This is what a switch does.
Some switches are hidden inside machinery; others are where we can see and use them. The
push button switch has thousands of familiar uses, from elevators to car stereos. It comes in
two basic kinds: momentary and non-momentary.
Construction
A push button switch is a small, sealed mechanism that completes an electric circuit when you
press on it. When it's on, a small metal spring inside makes contact with two wires, allowing
electricity to flow. When it's off, the spring retracts, contact is interrupted, and current won't
flow. The body of the switch is made of non-conducting plastic.
Momentary Contact
Momentary switches work only as long as you press on them, like the buttons on a phone,
calculator or door buzzer. They can be subdivided into normally-on and normally-off types.
124
Normally-Off
With the normally-off switch, there's no connection till you push the button. Most push button
switches are used this way. Examples include doorbell buttons, cell phone keys and garage
door openers.
Normally-On
Here the switch conducts normally, but interrupts the circuit when you press on it. This is
more specialized, and may be used in conjunction with a wiring trick. For example,
connecting a normally-on switch in parallel with a light bulb will light the bulb when the
button's pushed; otherwise, current will flow through the switch, leaving the bulb off.
Pushbuttons or switches connect two points in a circuit when you press them. This example
turns on the built-in LED on pin 13 when you press the button.
Hardware
Arduino Board
Momentary button or Switch
10K ohm resistor
hook-up wires
breadboard
Circuit
125
When the pushbutton is open there is no connection between the two legs of the pushbutton,
so the pin is connected to ground (through the pull-down resistor) and we read a LOW. When
the button is closed (pressed), it makes a connection between its two legs, connecting the pin
to 5 volts, so that we read a HIGH.
You can also wire this circuit the opposite way, with a pullup resistor keeping the input
HIGH, and going LOW when the button is pressed. If so, the behavior of the sketch will be
reversed, with the LED normally on and turning off when you press the button.
If you disconnect the digital I/O pin from everything, the LED may blink erratically. This is
because the input is "floating" - that is, it will randomly return either HIGH or LOW. That's
why you need a pull-up or pull-down resistor in the circuit.
Code
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
In this circuit, we are making a Light Sensor using LDR with Arduino to control a LED as
per light condition of the room or outside area.
Material Required
126
Arduino UNO
LDR (Light Dependent Resistor)
Resistor (100k-1;330ohm-1)
LED
Connecting wires
Breadboard
First, you need to connect the LDR to the analog input pin 0 on the Arduino. You have to use
a voltage divider configuration to do this. The connection diagram for the Arduino is as given
below.
Code
127
int sensorPin = A0;
int sensorValue = 0;
void setup() {
Serial.begin(9600); //sets serial port for communication
}
void loop() {
sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);
delay(100);
Result
After uploading the code, click the button on the Arduino IDE called “Serial monitor". This
will open a new window, which prints different values on the screen. Now, test out the sensor
by blocking its surface from light and see what values you get on the serial monitor. This is
how the serial monitor looks:
128
Working of LDR controlled LED using Arduino
As per the circuit diagram, we have made a voltage divider circuit using LDR and 100k resistor.
The voltage divider output is feed to the analog pin of the Arduino. The analog Pin senses the
voltage and gives some analog value to Arduino. The analog value changes according to the
resistance of LDR. So, as the light falls on the LDR the resistance of it get decreased and hence
the voltage value increase.
Intensity of light ↓ - Resistance↑ - Voltage at analog pin↓ - Light turns ON
As per the Arduino code, if the analog value falls below 700 we consider it as dark and the light
turns ON. If the value comes above 700 we consider it as bright and the light turns OFF.
129
Circuit
Connect the 3.3v output of the Arduino to the positive rail of the breadboard
- Connect the A0 pin of the Arduino to the same column where the LDR and resistor is
connected (Since the LDR gives out an analog voltage, it is connected to the analog input pin
on the Arduino. The Arduino, with its built-in ADC (Analog to Digital Converter), then
converts the analog voltage from 0-5V into a digital value in the range of 0-1023). - Now
connect the other end of the 10K resistor to the negative rail - And the the second leg of the
LDR to the positive rail
Now, as we want our circuit to do something in the real world other than just displaying the
values on the computer screen we will be attaching a LED to the circuit. The LED will turn on
when it’s dark and will go off when it’s bright. To achieve this we will:
- Connect the 220ohm resistor to the long leg (+ve) of the LED
- Then we will connect the other leg of the resistor to pin number 13 (digital pin) of the
Arduino
130
Fig 4.22: Circuit Diagram for Controlling LED through LDR
Code
const int ledPin = 13;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(ldrPin, INPUT);
void loop() {
131
int ldrStatus = analogRead(ldrPin);
digitalWrite(ledPin, HIGH);
Serial.println(ldrStatus);
} else {
digitalWrite(ledPin, LOW);
Serial.println(ldrStatus);
}
Potentiometer Interfacing with Arduino
132
Fig 4.23: Interfacing potentiometer with Arduino
int value=0;
void setup(){
pinMode(pot,INPUT);
Serial.begin(9600);
void loop(){value=analogRead(pot);
Serial.println(value);
Code
int value=0;
int Led=9;
void setup(){
133
pinMode(pot,INPUT);
Serial.begin(9600);
pinMode(Led,OUTPUT);
void loop(){
value=analogRead(pot);
Serial.println(value);
digitalWrite(Led,HIGH);
else
digitalWrite(Led,LOW);
134
Fig 4.24: Controlling a LED through Potentiometer
135
As analog pin reads value in the range of 0 to 1023 and PWM pins can provide analog output
Code
int LED_PIN = 3;
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// reads the input on analog pin A0 (value between 0 and 1023)
int analogValue = analogRead(A0);
To establish a good communication between human world and machine world, display units
play an important role. And so they are an important part of embedded systems. Display units
- big or small, work on the same basic principle. Besides complex display units like graphic
displays and 3D displays, one must know working with simple displays like 16x1 and 16x2
units. The 16x1 display unit will have 16 characters and are in one line. The 16x2 LCD will
have 32 characters in total 16in 1st line and another 16 in 2nd line. Here one must understand
that in each character there are 5x10=50 pixels so to display one character all 50 pixels must
work together. But we need not to worry about that because there is another controller
(HD44780) in the display unit which does the job of controlling the pixels.
Unlike normal development boards interfacing a LCD to a ARDUINO is quite easy. Here we
don’t have to worry about data sending and receiving. We just have to define the pin numbers
and it will be ready to display data on LCD
Hardware Required
136
Arduino Board
LCD Screen
pin headers to solder to the LCD display pins
10k ohm potentiometer
220-ohm resistor
hook-up wires
breadboard
Circuit
In 16x2 LCD there are 16 pins over all if there is a back light, if there is no back light there
will be 14 pins. One can power or leave the back light pins. Now in the 14 pins there are 8
data pins (7-14 or D0-D7), 2 power supply pins (1&2 or VSS&VDD or GND&+5v), 3rd pin
for contrast control (VEE-controls how thick the characters should be shown), and 3 control
pins (RS&RW&E).
137
Fig 4.26: Interfacing LCD Module to Arduino
Code
#include <LiquidCrystal.h>
lcd.print("hello, world!");
}
void loop() {
// Turn off the display:
lcd.noDisplay();
delay(500);
// Turn on the display:
lcd.display();
138
delay(500);
}
Result
Connections:
Mount LCD on the I2C LCD backpack as shown above. Then make the following
connections with Arduino Board. The potentiometer on the LCD backpack is to adjust LCD
contrast.
139
Go to manage library and install Liquid Crystal I2C Library by Frank de brabander
Code
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
void setup() {
lcd.print("Hello, world!");
lcd.print("NIELIT Patna");
void loop()
DHT11 is an electronic device which is used to measure the temperature and humidity in real
environment. It consists of two part capacitive humidity sensor and thermistor. It is a low cost
device but provides excellent and precise results. It has an internal small chip used for analog
to digital conversions and to provide digital output. We can read this digital output easily
through any of the micro-controller.
DHT11 temperature sensor has total four pins, each of them has different tasks to perform.
140
As we know DHT11 can measure both temperature and humidity.
In order to measure temperature DHT11 uses a thermistor also known as NTC (Negative
Temperature Coefficient) temperature sensor.
Thermistor is basically a variable resistors, which changes its resistance with respect to the
temperature.
Humidity part consists of two electrodes having moisture holding substrate in between them.
As the humidity level changes, the resistance between both of the electrodes or conductivity
also changes correspondingly.
And hence a micro-controller becomes able to read this value and provides us the precise value.
Components Required
Circuit
141
Fig 4.28: Interfacing DHT11 to Arduino
Code
include<DHT.h>
#define dhtpin A0
DHT dht(dhtpin,dhtpin);
dht DHT;
void setup(){
Serial.begin(9600);
void loop(){
float h;
142
float t;
h=dht.readHumidity();
t=dht.readTemprature();
DHT.read11(dht_apin);
Serial.print(h);
Serial.print("% ");
Serial.print("temperature = ");
Serial.print(t);
Serial.println("C ");
delay(5000);
Result
MQ135Interfacing
In chapter two we discussed about MQ135 Sensor
Required Components:
Following Components are required for this project:
Arduino UNO
Breadboard
143
MQ-135 Gas sensor module
Interfacing of MQ-135 gas sensor with Arduino
Wire the circuit as follows:
Arduino A0 pin with Sensor A0
Arduino 5Vpin with Sensor Vcc
Arduino GND with sensor GND
Code
int airquality = 0;
void setup()
Serial.begin(9600);
void loop()
Serial.print(sensorValue);
Serial.print("*PPM");
Serial.println();
delay(1000);
Result
145
Keypad
Keypads allow users to input data while a program is running. A keypad is often needed to
provide input to an Arduino system, and membrane-type keypads are an economical solution
for many applications. They are quite thin and can easily be mounted wherever they are
needed.
A 12-button keypad has three columns and four row. Pressing a button will short one of the
row outputs to one of the column outputs. From this information, the Arduino can determine
which button was pressed. For example, when key 1 is pressed, column 1 and row 1 are
shorted. The Arduino will detect that and input a 1 to the program.
How the rows and column are arranged inside the keypad is shown in the figure below.
Hardware Required:
Arduino
3x4 hex keypad
146
jumpers (optional)
breadboard (optional)
long pin connectors
Circuit:
Keypad consist of 7 pin- in which 3 from keypad columns and 4 from keypad rows.
COLUMNS:-
ROW:-
When you press keypad button respective key value will display in virtual terminal
In order to determine which key was pressed, we need to continuously scan rows & columns.
Fortunately, Keypad.h was written to hide away this unnecessary complexity so that we can
issue simple commands to know which key was pressed.
To install the library navigate to the Sketch > Include Library > Manage Libraries…Wait
for Library Manager to download libraries index and update list of installed libraries.
147
Filter your search by typing ‘keypad’. There should be a couple entries. Look
for Keypad by Mark Stanley, Alexander Brevig. You have to scroll a little bit. Click on that
entry, and then select Install.
148
Code
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 4, 3}; //connect to the column pinouts of the keypad
//Create an object of keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup(){
Serial.begin(9600);
}
void loop(){
char key = keypad.getKey();// Read the key
// Print if key pressed
if (key){
Serial.print("Key Pressed : ");
Serial.println(key);
}
}
Result
149
Relay Module interfacing with Arduino
we are going to control an Arduino relay module. We will control two different devices using
it. First we will control a simple LED then we will control a light bulb using it. The Arduino
can control the devices which runs on up to 5V so if we want to control the devices which runs
on more than 5V or the A.C devices then we will have to use a relay module through which we
can control A.C as well as DC devices.
In the first part, we will control a led using the relay and in the second part we will control a
high voltage device using the relay. Controlling a DC device is easy as compared to the AC
device. For controlling the DC device, you do not require an external supply until you are
controlling a small voltage device like LED which runs on up to 5V.
On the other side of the relay module, we will use the common pin and the normally open pin
because we are going to connect the relay in the normally open state. So, connect the pin 13 of
Arduino to the common of relay module and the normally open (NO) of the relay module to the
positive pin of the LED. Connect the other pin of LED to the ground of Arduino.
150
Fig 4.31: Relay module Interfacing to Arduino
Code
int relay_pin = 8;
void setup(){
pinMode(relay_pin,OUTPUT);
pinMode(led_pin,OUTPUT);
digitalWrite(led_pin,HIGH);}
void loop(){
digitalWrite(relay_pin,HIGH);
delay(5000);
digitalWrite(relay_pin,LOW);
delay(5000);
151
}
Controlling AC Device using Arduino Relay Module
For the control of AC device, you need to take the necessary precautions because the AC is
dangerous and it can cause damage to you. So, to avoid any danger, follow the below tutorial
correctly.
Code
int relay_pin = 8;
void setup(){
pinMode(relay_pin,OUTPUT);
void loop(){
digitalWrite(relay_pin,HIGH);
delay(5000);
digitalWrite(relay_pin,LOW);
152
delay(5000);
}
Interfacing DC motor with Arduino using L298 motor driver
Controlling a DC Motor
In order to have a complete control over DC motor, we have to control its speed and rotation
direction. This can be achieved by combining these two techniques.
The speed of a DC motor can be controlled by varying its input voltage. A common technique
for doing this is to use PWM (Pulse Width Modulation)
PWM is a technique where average value of the input voltage is adjusted by sending a series of
ON-OFF pulses.
The average voltage is proportional to the width of the pulses known as Duty Cycle.
The higher the duty cycle, the greater the average voltage being applied to the dc motor(High
Speed) and the lower the duty cycle, the less the average voltage being applied to the dc
motor(Low Speed).
The DC motor’s spinning direction can be controlled by changing polarity of its input voltage.
A common technique for doing this is to use an H-Bridge.
An H-Bridge circuit contains four switches with the motor at the center forming an H-like
arrangement.
At the heart of the module is the big, black chip with chunky heat sink is an L298N.
153
The L298N is a dual-channel H-Bridge motor driver capable of driving a pair of DC motors.
That means it can individually drive up to two motors making it ideal for building two-wheel
robot platforms.
Power Supply
The L298N motor driver module is powered through 3-pin 3.5mm-pitch screw terminals. It
consists of pins for motor power supply(Vs), ground and 5V logic power supply(Vss).
Output Pins
The L298N motor driver’s output channels for the motor A and B are broken out to the edge of
the module with two 3.5mm-pitch screw terminals.
154
You can connect two DC motors having voltages between 5 to 35V to these terminals.
Control Pins
For each of the L298N’s channels, there are two types of control pins which allow us to control
speed and spinning direction of the DC motors at the same time viz. Direction control pins &
Speed control pins.
Using the direction control pins, we can control whether the motor spins forward or backward.
These pins actually control the switches of the H-Bridge circuit inside L298N IC.
The module has two direction control pins for each channel. The IN1 and IN2 pins control the
spinning direction of the motor A while IN3 and IN4 control motor B.
The spinning direction of a motor can be controlled by applying either a logic HIGH(5 Volts)
or logic LOW(Ground) to these inputs. The below chart illustrates how this is done.
The speed control pins viz. ENA and ENB are used to turn the motors ON, OFF and control its
speed.
Pulling these pins HIGH will make the motors spin, pulling it LOW will make them stop. But,
with Pulse Width Modulation (PWM), we can actually control the speed of the motors.
155
Before diving into hookup and example code, let’s first take a look at its Pinout.
VCC pin supplies power for the motor. It can be anywhere between 5 to 35V. Remember, if
the 5V-EN jumper is in place, you need to supply 2 extra volts than motor’s actual voltage
requirement, in order to get maximum speed out of your motor.
GND is a common ground pin.
5V pin supplies power for the switching logic circuitry inside L298N IC. If the 5V-EN jumper
is in place, this pin acts as an output and can be used to power up your Arduino. If the 5V-EN
jumper is removed, you need to connect it to the 5V pin on Arduino.
ENA pins are used to control speed of Motor A. Pulling this pin HIGH(Keeping the jumper in
place) will make the Motor A spin, pulling it LOW will make the motor stop. Removing the
jumper and connecting this pin to PWM input will let us control the speed of Motor A.
Now that we know everything about the module, we can begin hooking it up to our Arduino!
Start by connecting power supply to the motors. In our experiment we are using DC Gearbox
Motors(also known as ‘TT’ motors) that are usually found in two-wheel-drive robots. They are
rated for 3 to 12V. So, we will connect external 12V power supply to the VCC terminal.
Considering internal voltage drop of L298N IC, the motors will receive 10V and will spin at
slightly lower RPM. But, that’s OK.
Next, we need to supply 5 Volts for the L298N’s logic circuitry. We will make use of the on-
board 5V regulator and derive the 5 volts from the motor power supply so, keep the 5V-EN
jumper in place.
Now, the input and enable pins(ENA, IN1, IN2, IN3, IN4 and ENB) of the L298N module are
connected to six Arduino digital output pins(9, 8, 7, 5, 4 and 3). Note that the Arduino output
pins 9 and 3 are both PWM-enabled.
Finally, connect one motor to terminal A(OUT1 & OUT2) and the other motor to terminal
B(OUT3 & OUT4). You can interchange your motor’s connections, technically, there is no
right or wrong way.
When you’re done you should have something that looks similar to the illustration shown
156
Code
// Motor A connections
int enA = 9;
int in1 = 8;
int in2 = 7;
// Motor B connections
int enB = 3;
int in3 = 5;
157
int in4 = 4;
void setup() {
pinMode(enA, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
void loop() {
directionControl();
delay(1000);
speedControl();
delay(1000);
}
158
// This function lets you control spinning direction of motors
void directionControl() {
analogWrite(enA, 255);
analogWrite(enB, 255);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(2000);
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(2000);
digitalWrite(in1, LOW);
159
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
void speedControl() {
// Turn on motors
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
analogWrite(enA, i);
analogWrite(enB, i);
delay(20);
analogWrite(enA, i);
analogWrite(enB, i);
160
delay(20);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
161
Chapter 5
IoT Connectivity Solution
5.1 Introduction
The Internet constitutes the largest heterogeneous network and infrastructure in existence. It is
estimated that over 3 billion people had access to the Internet in 2014. Also, there are as many
mobile subscriptions (6.8 billion) as there are people on earth. Global mobile data traffic was
estimated at 2.5Exabyte per month in 2014. This figure is estimated to rise to 24.3 Exabyte per
month at a compound annual growth rate of 57 percent in 2019. This can be attributed to a
number of technological factors including the proliferation of touch screen devices
(smartphones, tablets, and the like), and, significantly, the evolvement and technological
advancement of wireless and mobile technologies. On the other hand, the Internet of Things
(IoT) is a fast growing heterogeneous network of connected sensors and actuators attached to a
wide variety of everyday objects. Mobile and wireless technologies in their assortment of low,
ultra-power, short and long range technologies continue to drive the progress of
communications and connectivity in the IoT. The future will foresee smart and low-power
networked devices connecting to each other and to the Internet using, mostly, reliable low-
power wireless transmissions.
The IoT covers a broad range of applications and devices. The 802.11 protocol with its
802.11a/b/g/n/ac variants is among the first obvious technology candidates for the IoT. Today,
almost every house, workplace, cafe, and university has a Wi-Fi network. Wi-Fi has become
the de-facto term when referring to connecting to the Internet via a wireless access point. The
widespread adoption of Wi-Fi makes it a first technology choice for many IoT applications.
However, in some IoT applications, the choice of technology is limited to the devices hardware
capabilities, low-power consumption requirements, and the overall cost. Many IoT devices
require the use of a low-cost and low-power wireless technology when connecting to the
Internet. Traditionally, energy consumption has always been a limiting factor in many wireless
sensor network applications. This limiting factor will continue as a major challenge facing the
development of many applications in the IoT. In fact, for the growth of the IoT, low-power
consumption is an essential requirement that needs to be met. In addition to low-power
consumption, other associated requirements need to be considered as well. For instance, the
cost of technology, security, simplicity (easy to use and manage), wireless data rates and
ranges, among others are essential requirements that require attention. Many evolving wireless
technologies such as ZigBee and Bluetooth are competing to provide the IoT with a low-power
wireless connectivity solution.
162
A personal area network (PAN) is a computer network used for communication among computer
devices, including telephones and personal digital assistants, in proximity to an individual's body.
The devices may or may not belong to the person in question. The reach of a PAN is typically a
few meters. PANs can be used for communication among the personal devices themselves
(intrapersonal communication), or for connecting to a higher level network and the Internet (an
uplink) Personal area networks may be wired with computer buses such as USB and FireWire.
A wireless personal area network (WPAN) can also be made possible with network technologies
such as IrDA, Bluetooth, UWB, Z-Wave and ZigBee.
A WPAN (wireless personal area network) is a personal area network - a network for
interconnecting devices centered on an individual person's workspace - in which the connections
are wireless. Typically, a wireless personal area network uses some technology that permits
communication within about 10 meters - in other words, a very short range. One such technology
is Bluetooth, which was used as the basis for a new standard, IEEE 802.15.
A WPAN could serve to interconnect all the ordinary computing and communicating devices
that many people have on their desk or carry with them today - or it could serve a more
specialized purpose such as allowing the surgeon and other team members to communicate
during an operation.
The technology for WPANs is in its infancy and is undergoing rapid development. Proposed
operating frequencies are around 2.4 GHz in digital modes. The objective is to facilitate seamless
operation among home or business devices and systems. Every device in a WPAN will be able
to plug in to any other device in the same WPAN, provided they are within physical range of one
another. In addition, WPANs worldwide will be interconnected.
5.2.2.1 Bluetooth
Bluetooth Technology was developed to solve the simple problem of eliminating the connector
cable. The idea is to replace the cables that are needed to accompany portable devices carried by
many mobile travelers with a low-cost, secure, robust RF link. Originally Bluetooth marketed to
small handheld devices such as cell phones and laptops. As the Bluetooth standard emerged
successfully into society, the world demanded more. Bluetooth is so efficient, effective, and
secure that even the IEEE approved the 802.15.1 Standard for Wireless Person Area Networks
based on the Bluetooth specification.
Bluetooth is defined as a wireless technology that provides short-range communications intended
to replace the cables connecting portable and/or fixed devices while maintaining high levels of
security. There are three key features of Bluetooth; robustness, low power, and low cost. The
Bluetooth standard provides a uniform structure enabling a wide variety of devices to seamlessly,
and wirelessly, connect and communication with each other. Bluetooth devices connect and
communicate via RF link through short-range piconets. Bluetooth devices have the ability to
connect with up to seven devices per piconet. Each of these devices can also be simultaneously
connected to other piconets. The piconet itself is established dynamically and automatically as
Bluetooth enables devices enter and leave the range in which its radio operates. The major pro
of Bluetooth is the ability to be full duplex and handle both data and voice transmission
simultaneously. The differentiation of Bluetooth from other wireless standards such as Wi-Fi is
163
that the Bluetooth standard gives both link layer and application layer definitions which support
data and voice applications.
Bluetooth technology operates in the unlicensed industrial, scientific and medical (ISM) band at
2.4 to 2.485 GHz, using a spread spectrum, frequency hopping, full-duplex signal at a nominal
rate of 1600 hops/sec. Bluetooth is modulated using adaptive frequency hopping (AFH). This
modulation has the capability to reduce interference between wireless technologies sharing the
ISM band. It does this by having the ability to detect other devices using the ISM band and use
only frequencies that are free. The signal itself hops between ranges of 79 frequencies at 1
Megahertz intervals to minimize interference.
The Technology
Fundamentally Bluetooth operates within the Industrial, Scientific and Medical (ISM) band at
2.4 GHz. It is a short-range wireless communication standard defined as cable replacement for a
Personal Area Network (PAN).
A cable replacement standard has been defined because cables limit mobility of the consumer;
they are cumbersome to carry around, are easily lost or broken. Often connectors are prone to
difficult to diagnose failures; or are proprietary. To counteract these limitations Bluetooth is
designed to be light and portable. It includes standards and protocols to make it mobile, robust,
reliable and not limited to one manufacturer.
The operating band also fits the goals of Bluetooth, imposing requirements as a cable
replacement. The ccost needs to be comparable with cable. Rreductions can be achieved by
operating in the licence free 2.4 GHz ISM band, keeping backward compatibility wherever
possible lowers the cost of ownership by avoiding upgrades and having a relaxed radio
specification enables single chip integrated circuit solutions. It also needs to be as reliable and
resilient as cable and cope with errors and degradation caused by interference. For mobile devices
it must be compact, lightweight, low power and easy to use.
Frequency Hopping.
We have addressed the reasons for the Bluetooth without delving into the ‘nuts and bolts’ of the
technology to discover how it operates. For the majority of countries, the ISM band used by
Bluetooth is available from 2.40-2.4835 GHz, although some countries impose restrictions. In
this band Bluetooth uses Frequency Hopping Spread Spectrum (FHSS) techniques in order to
improve its immunity from interference.
In unrestricted countries the radios hop in pseudo random sequences around all available
channels, this equates to 79 RF channels with a channel spacing of 1 MHz Starting at a base
frequency of 2402 MHz then the frequency of the channels, f, can be expressed as:
f =2402 + n MHz
164
where, n, is the channel number with an integer value in the range of 0 to 78.
Master and Slave Operation.
Bluetooth devices exist in small ad-hoc network configuration with the ability to operate as either
master or the slave; the specification also allows a mechanism for master and slave to switch
their roles. The configurations can be single point, which is the simplest configuration with one
master and one slave. Multipoint, called a Piconet, based on up to 7 slaves clustered around a
single Master. And a third type called a Scatternet, this is a group of Piconets effectively hubbed
via a single Bluetooth device acting as a master in one Piconet and a slave in the other Piconet.
The Scatternet permits either larger coverage areas or number of devices than a single Piconet
can offer. Below Figure outlines the different master and slave topologies permitted for networks
in the standard.
165
1) The master enters inquiry mode and sends out an inquiry to discover devices available to connect
to.
2) Potential slaves make themselves discoverable by entering inquiry scan mode and listen for an
inquiry from a master.
3) On receiving an inquiry, the slave responds to the master with a Frequency Hop Synchronization
packet (FHS). The FHS contains information that is needed to create a connection to the device;
this information includes its Bluetooth address and class of device.
4) The master collects the FHS information from each device discovered. To connect to one of these
devices the master goes into page mode and will page the device using the corresponding
Bluetooth address.
5) The slave being paged by a master will need to be in page scan mode to be able to connect to a
master
166
ENABLE:
When enable is pulled LOW, the module is disabled which means the module will not turn
on and it fails to communicate. When enable is left open or connected to 3.3V, the module is
enabled i.e. the module remains on and communication also takes place.
Vcc:
Supply Voltage 3.3V to 5V
GND:
Ground pin
TXD & RXD:
These two pins acts as an UART interface for communication
STATE:
It acts as a status indicator. When the module is not connected to / paired with any other
Bluetooth device, signal goes Low. At this low state, the led flashes continuously which
denotes that the module is not paired with other device. When this module is connected
to/paired with any other Bluetooth device, the signal goes High. At this high state, the led
blinks with a constant delay say for example 2s delay which indicates that the module
is paired.
BUTTON SWITCH:
This is used to switch the module into AT command mode. To enable AT command mode,
press the button switch for a second. With the help of AT commands, the user can change the
parameters of this module but only when the module is not paired with any other BT device. If
the module is connected to any other Bluetooth device, it starts to communicate with that
device and fails to work in AT command mode.
Modes of Operation
The HC-05 Bluetooth Module can be configured in two modes of operation: Command Mode
and Data Mode. In Command Mode, you can communicate with the Bluetooth module through
AT Commands for configuring various settings and parameters of the Module like get the
firmware information, change UART Baud Rate, change module name, set it as either Master
or slave etc.
An important point about HC-05 Module is that it can be configured as Master or Slave in a
communication pair. In order to select either of the modes, you need to activate the Command
Mode and sent appropriate AT Commands.
Coming to the Data Mode, in this mode, the module is used for communicating with other
Bluetooth device i.e. data transfer happens in this mode.
HC05 in AT mode
By default, all HC05 modules are Slaves. Using AT commands the module can be
configured as per requirement.
To configure the SLAVE, we make use of an Arduino UNO board. Not much of
configuration needed for slave. We can leave it to defaults. But to know the ADDRESS of
the slave you’ve to follow this procedure.
167
FIG 5.3: Bluetooth HC05 Interfacing to Arduino for AT mode
Before connecting the HC05 module, upload an empty sketch to Arduino. This bypasses
the Boot loader of UNO & the Arduino is used as USB-UART converter.
void setup() {}
void loop() {}
After uploading this empty sketch, remove USB power from Arduino & do the following
connections with HC05 Slave:
——————————————-
ARDUINO HC05
Rx(pin0 ) —> Rx Remember it is one to one connection here & not cross
connection Tx (pin1) —-> Tx
+5v ——-> VCC
GND ——-> GND
+3.3V ——–> KEY
Now provide the USB cable power to Arduino. The HC05 module enters the Command
mode with Baud Rate 38400.
Open the Serial Monitor of Arduino
Ensure to select “BOTH NL & CR” & Baud Rate as 38400 at the bottom of the
serial monitor.This is very important as the Bluetooth module HC05 expects both
168
Carriage Return and Line Feed after every AT command.
If you type in AT & click on SEND button, you should get an OK confirmation from the
HC05 module.
If you get ERROR(0) try again to enter the Command mode. If there is no response then
check whether correct COM port has been assigned in Arduino IDE & confirm Baud Rate
is 38400, “Both NL & CR” selected.
Type in AT+NAME? to get the name of the module. You can change the name
typing AT+ROLE?
You can change it by AT+ROLE=0 0 for SLAVE & 1 for Master. Leave it as 0
as we want this module to be SLAVE.
You should know the Address of this module to make it PAIR with another.
Type in AT+ADDR?
like 14,2,110007
Now remove the KEY connection from the HC05 module & disconnect the power.
Again provide the power to see STATUS LED on the module blinking fast indicating that
it is looking for a PAIR. When it gets connected to any other Bluetooth device, its blinking
slows down to two seconds.
Send data from Smartphone terminal to HC-05 Bluetooth module and see this data on PC
serial terminal and vice versa.
So, when we want to communicate through smartphone with HC-05 Bluetooth module,
connect this HC-05 module to the PC via Arduino
Before establishing communication between two Bluetooth devices, 1st we need to pair HC-05
module to smartphone for communication.
1. Search for new Bluetooth device from your phone. You will find Bluetooth device with “HC-
05” name.
2. Click on connect/pair device option; default pin for HC-05 is 1234 or 0000.
use pins 10 and 11 of the Arduino to connect the HC-05 and use the Software Serial library to
communicate with the module. The Hardware serial port on Arduino is used to send/receive
messages from the computer to the Arduino.
170
Fig 5.4: Interfacing HC05 to Arduino
Code
1. #include <SoftwareSerial.h>
2. SoftwareSerial EEBlue(10, 11); // RX | TX
3. void setup()
4. {
5. Serial.Begin(9600);
6. EEBlue.Begin(9600);
7. Serial.println("The bluetooth gates are open.\n Connect to HC-05 from any other bluetooth
device with 1234 as pairing key!.");
8.
9. }
10. void loop()
11. {
12.
13. if (EEBlue.available())
14. Serial.write(EEBlue.read());
15.
16. // Feed all data from termial to bluetooth
17. if (Serial. Available())
18. EEBlue.write(Serial.read());
19. }
171
After pairing two Bluetooth devices, open terminal software in PC, and select the port where
we have connected USB to serial module. Also select default baud rate of 9600 bps.
In smart phone, open Bluetooth terminal application and connect to paired device HC-05.
172
Chapter 6
IoT Security
6.1 INTRODUCTION
The rapid proliferation of the Internet of Things (IoT) into diverse application areas such as
building and home automation, smart transportation systems, wearable technologies for
healthcare, industrial process control and infrastructure monitoring and control is changing the
fundamental way in which the physical world is perceived and managed. It is estimated that
there will be about 30 billion IoT devices by 2020. Most of these IoT devices are expected to
be of low-cost and wireless communication technology based, with limited capabilities in
terms of computation and storage. As IoT systems are increasingly being entrusted with
sensing and managing highly complex eco-systems, questions about the security and
reliability of the data being transmitted to and from the IoT devices are quickly becoming a
major concern. It has been reported in several studies that IoT networks are facing several
security challenges including authentication, authorization, information leakage, privacy,
verification, tampering, jamming, eavesdropping etc. IoT provides a network infrastructure
with interoperable communication protocols and software tools to enable the connectivity to
the internet for handheld smart devices (smart phones, personal digital assistants (PDA) and
tabs), smart household apparatus (smart TV, AC, intelligent lighting systems, smart fridge,
etc.), automobiles and sensory acquisition systems. However, the improved connectivity and
accessibility of devices presents major concerns for security of all the parties connected to the
network regardless of whether they are humans or machines. Moreover, the cyber-attack
launched at Ukrainian power grid in 2015 that targeted the Supervisory Control and Data
Acquisition (SCADA) and caused a blackout for several hours is a prime exemplification on
the gravity of devastation that could be resulted by modern day attacks. The main reasons for
the security challenges of current information centric automated systems is their insecure
unlimited connectivity with the internet and the non-existent access control mechanisms for
providing secure and trustful communication. Further, the problem of vulnerabilities in IoT
systems arises due to the physical limitations of resource constrained IoT devices (in terms of
computing power, on-board storage and battery-life), lack of consensus/standardization in
security protocols for IoT, and widespread use of 3rd party hardware, firmware and software.
These systems are often not sufficiently secure, especially when deployed in environments
that cannot be secured/isolated through other means. The resource constraints on typical IoT
devices make it impractical to use very complex and time-consuming encryption/decryption
algorithms for secure message communication. This makes IoT systems highly susceptible to
various types of attacks. Furthermore, addressing the security vulnerabilities in the protocols
designed for communication is critical to the success of IoT. This chapter focuses on security
threats, attacks and authentication in the context of the IoT and the state of-the-art IoT
security.
Privacy Issues
173
Protecting consumer privacy becomes increasingly difficult as the IoT becomes more
prevalent. More devices are connected to different types of devices and this increase in
connectivity and data collection results in less control. Both control of data and control of the
very devices that are connected are at stake.
Control can be lost if someone hacks into the smartphone or computer acting as a remote for
the other devices. In the case of computers and smartphones, this hacking can be done
remotely and often undetected. Smartphones, just like computers, carry an enormous amount
of personal information about their owners. They often link to bank accounts, email accounts,
and in some cases household appliances. Stolen data can result in serious problems. Vehicles
contain many computers that control their function. Initially, these computers could not be
hacked into. With the increased connectivity of the IoT, however, vehicles are now at
risk due to being connected to the Internet.
In another sense, control can be lost as more and more companies collect data about users.
This data often paints a detailed picture of individual users through the collection of activities
online. Everything you search, all of your activities online, are being tracked by companies
that use that data. These companies often use the data to improve the user's experience, but
they also use this data to sell users products or sell to other companies who sell users products.
Security Issues
Because IoT devices are connected to the Internet, they are vulnerable to the same kinds of
cyber-attacks that can afflict consumer, commercial, industrial, and governmental computer
systems. In September 2016, weak security in IoT devices was exploited on a massive scale by
the “Mirai” botnet, which gained control of hundreds of thousands of such devices, and
subsequently used them to launch massive distributed denial of service attacks, capable of
effectively shutting down targeted websites. Because IoT devices rely on connectivity to
function, they create a common attack vector for hackers to gain access to an entire network.
Many IoT devices are built using very similar underlying hardware and software, and are
frequently not designed with cybersecurity in mind, which increases the risks they pose.
There are also unique security risks posed by IoT devices’ use of cloud services. Storing data
on remote servers necessarily increases the possibility that the data will be compromised.
Splitting control over the device and the data reduces the ability of any one provider to limit
access, and consistent security becomes dependent on harmonization of data security practices
among the various parties responsible for its collection, transmission, and storage. The most
promising response to the increasing complexity of these systems would be a widespread
adoption of a single, consistent set of standards. The NIST Cybersecurity Framework, which
is one of the most important standards at the federal level, was recently updated in January
2017.
Depending on the functions of various IoT devices, weak cybersecurity can lead to serious
consequences, including physical damage and injury. Perhaps the most visceral example is the
hacking of an automobile by a bad actor, which could lead to vehicular homicide. Researchers
have already demonstrated the ability to access and control vital functions of a car, including
its brakes, by compromising its connected features. Another category of IoT devices that could
be hacked with horrific consequences are personal medical devices, such as defibrillators,
pacemakers, and insulin pumps; hacking of any of these devices could lead to physical injury
or death. Other vulnerable devices include IoT cameras, which can surreptitiously record
174
audio and video, HVAC systems that control heating and cooling levels, and alarm systems
that can provide access to user’s homes and other secure areas.
IoT devices tend to differ from traditional computers and computing devices in important
ways that challenge security: —
Many Internet of Things devices, such as sensors and consumer items, are designed to be
deployed at a massive scale that is orders of magnitude beyond that of traditional Internet
connected devices. As a result, the potential quantity of interconnected links between these
devices is unprecedented. Further, many of these devices will be able to establish links and
communicate with other devices on their own in an unpredictable and dynamic fashion.
Therefore, existing tools, methods, and strategies associated with IoT security may need new
consideration.
Many IoT deployments will consist of collections of identical or near identical devices. This
homogeneity magnifies the potential impact of any single security vulnerability by the sheer
number of devices that all have the same characteristics. For example, a communication
protocol vulnerability of one company’s brand of Internet-enabled light bulbs might extend to
every make and model of device that uses that same protocol or which shares key design or
manufacturing characteristics.
Many Internet of Things devices will be deployed with an anticipated service life many years
longer than is typically associated with high-tech equipment. Further, these devices might be
deployed in circumstances that make it difficult or impossible to reconfigure or upgrade them;
or these devices might outlive the company that created them, leaving orphaned devices with
no means of long-term support. These scenarios illustrate that security mechanisms that are
adequate at deployment might not be adequate for the full lifespan of the device as security
threats evolve. As such, this may create vulnerabilities that could persist for a long time. This
is in contrast to the paradigm of traditional computer systems that are normally upgraded with
operating system software updates throughout the life of the computer to address security
threats. The long-term support and management of IoT devices is a significant security
challenge.
Many IoT devices are intentionally designed without any ability to be upgraded, or the
upgrade process is cumbersome or impractical. For example, consider the 2015 Fiat Chrysler
recall of 1.4 million vehicles to fix a vulnerability that allowed an attacker to wirelessly hack
into the vehicle. These cars must be taken to a Fiat Chrysler dealer for a manual upgrade, or
the owner must perform the upgrade themselves with a USB key. The reality is that a high
percentage of these autos probably will not be upgraded because the upgrade process presents
an inconvenience for owners, leaving them perpetually vulnerable to cybersecurity threats,
especially when the automobile appears to be performing well otherwise.
Many IoT devices operate in a manner where the user has little or no real visibility into the
internal workings of the device or the precise data streams they produce. This creates a
security vulnerability when a user believes an IoT device is performing certain functions,
when in reality it might be performing unwanted functions or collecting more data than the
175
user intends. The device’s functions also could change without notice when the manufacturer
provides an update, leaving the user vulnerable to whatever changes the manufacturer makes.
If both manufacturers and users begin to implement better practices in these technologies’
nascent stages, a great deal of future damage can be avoided. While achieving total security
for all IoT devices probably isn’t realistic, the overall scope of damage can be avoided by
implementing the right tools and best practices, such as the ones listed below.
Create Accountability
must be a specific person or team in charge of security. They must ensure that security
measures are being implemented thoroughly and throughout every stage of the development
and product lifecycle. This includes ensuring that there are no bugs before shipping and that
An end-to end approach to security incorporates encryption, cloud security practices, and
application/access security measures to fully protect the product and its pathway. It extends
security from the device to the cloud and then to the application.
Rather than allowing security to be a tacked-on afterthought, it should be baked in from the
procedures along with following best practices for programming throughout all stages.
176
Send Updates to Registered Users Regarding Security Issues
This should be an integral part of any security plan. An alternative to this is to follow the Nest
model, which charges their users a $10 monthly fee for upkeep services. These services
Never use default passwords, and make sure that each strong password uses a mix of upper
Manufacturers issue patches for vulnerabilities as they are discovered. However, if you’re not
checking for those patches, you can’t update your devices with them. Make sure to check
manufacturers’ websites regularly to see if patches have been released. If you find any, update
your device ASAP. This is one of the easiest, most proven ways to protect your devices.
Use 2FA
Two-factor authentication is another protective layer of security that requires the user to enter
a one-time code after entering their password. Not all devices offer 2FA, but if you have one
If devices are on their own network and a device on that network is breached, there will be
178
Attacks: Identity management, heterogeneity which is inaccessible to an authentic node, data
access controls, system complexity, physical security, encryption, infrastructure security and
misconfiguration of software
Solution: Identity privacy - Pseudonym, group signature , connection anonymization
Location privacy - Pseudonym ,game theory , population dynamic model Layer
removing/adding attack - Packet transmitting witness , aggregated transmission evidence
Forward and backward security - Cryptographic one-way hash chain Semi-trusted/malicious
cloud security - (Fully) homomorphic encryption
2.3. APPLICATION LAYER
Attacks Data privacy, Tampering Privacy, Access control, disclosure of information
Solution Authentication, key agreement and protection of user privacy across heterogeneous
networks, Datagram Transport Layer Security (DTLS) for end-to-end security, Information
Flow Control
6.3 Securing IoT
We will discuss about various aspects of securing IoT based devices and IoT ecosystem
1. Network security: The network is now the focal point for IoT security. The devices connect to
the network and the network touches all data and workloads. This is how hackers can move
laterally to compromise whatever systems and data are on the network. Through the network,
users and devices can be authenticated, policies and rules put in place to control access and
behavior and visibility can be increased to detect anomalies.
There’s a lack of visibility and security into the devices in what’s an increasingly distributed
enterprise IT environment. Often the devices are deployed on the interior of the network, and,
while some may be talking externally to a public cloud or other Internet-based systems, many
only communicate internally to other systems on the network.
The top IoT issue is that you shouldn’t rely on physical security to keep things off a network.
There are many places in the wired network that are wide open, and there’s little network
access control. There’s more control and authentication on the wireless side, but, even there,
devices that are authenticated often get dropped into an internal VLAN and from there are
uncontrolled.
179
1. Determine what the “thing” should be allowed to do on the network: IoT devices are static
in nature; they do the same thing repeatedly and talk only to a single protocol or two.
2. Monitor for abnormal behavior: If an enterprise sees a device operating outside of what’s
normal, something’s probably wrong. Fortunately, because you followed step 1, you know
3. Outlaw anonymous connections. Enterprises must know every device that’s connected,
4. Use the network to enforce those rules. Many people don’t take this last step, but, without
enforcement, polices mean little. If the cameras need to talk only to the network DVR, then
The network plays a critical role in two areas: first, detecting when an attack is taking place,
and second, responding to the attack by shutting down the device, limiting it or slowing it
down. There’s much you can do with the network infrastructure. IT personnel will almost
always want to depend on network firewalls for solving security problems, but don’t tend to
use a firewall for every single switch port. The security capabilities must be built into the
network itself.
2. Authentication:
The ability to secure data and limit it to only those with the correct permissions is not a new
idea and is used extensively in many industries. IoT devices must be authenticated by all
legitimate users. Methods to achieve such authentication range from static passwords to two-
180
An effective authentication and identity framework for IoT devices should be able to provide
appropriate protection against cyber threats. Authentication for the devices in IoT is different
and considerably lighter weight than people authentication methods prevalent today due to the
potential resource constraints of devices, the bandwidth of networks they operate within, and
A lack of established industry standards for IoT authentication has led vendors to develop
proprietary authentication methods. Since many IoT devices can be resource-constrained with
low computing power and storage capacity, existing authentication methods are not a good
growing need to evaluate and streamline the methods adopted for device and service
3. Encryption: Encryption will be needed to prevent unauthorized access to data and devices.
This will be difficult to ensure due to the variety of IoT devices and hardware profiles.
The single biggest area of use of cryptography in the internet of things is in securing the
communication channels. IoT-centric communication protocols like MQTT and AMQP allow
developers to use Transport Layer Security (TLS) to ensure all data sent over the network is
unreadable to outside parties. TLS is the rightful heir to the better known standard known as
Secure Sockets Layer (SSL), which was the long-time standard for web encryption (see
HTTPS) but is now considered insecure. TLS ensures that data between two entities is not
181
There is a well-known adage that states that the most secure systems are those with nothing to
steal. Storing hashed passwords is one way to accomplish this. A hash is a cryptographic
function that will take any input and create a unique, irreversible, yet consistent set of bits.
Good hash algorithms are nearly impossible to reverse. In other words, once a password is
hashed, you shouldn’t be able to reverse the hash to determine what the password was.
However, the hash can still be used to validate submitted passwords because the same input to
a hashing function will return the same output or hash. Some examples of hashing functions
are MD5 (popular but no longer considered secure), SHA-256 and Blowfish
Private key cryptography is asymmetric encryption which provides two keys, one public and
one private. If data is encrypted with the private key, it can only be decrypted with the public
key, and vice versa. Keeping the private key private then allows a single machine to securely
communicate with the outside world or authenticate with remote machines. This bit of
infrastructure.
182
REFRENCES
[1] Mahmoud Elkhodr. EMERGING WIRELESS TECHNOLOGIES IN THE INTERNET OF
THINGS: A COMPARATIVE STUDY. International Journal of Wireless & Mobile Networks
(IJWMN) Vol. 8, No. 5, October 2016
[2] Intel White paper Internet of Things: Developing solutions for internet of things
[3] “An introduction to internet of things” by mick Conley. https://legacy-uploads.ul.com/wp-
content/uploads/sites/40/2016/02/Internet-of-Things-white-paper_final.pdf.pdf
[4] Tara Salman. Networking Protocols and Standards for Internet of Things.
http://www.cse.wustl.edu/~jain/cse570-15/ftp/iot_prot/index.html
[5] Pallavi Sethi and Smruti R. Sarangi. Internet of Things: Architectures, Protocols, and
Applications. Journal of Electrical and Computer Engineering Volume 2017.
[6] Pradyumna Gokhale, Omkar Bhat, Sagar Bhat. Introduction to IOT. International Advanced
Research Journal in Science, Engineering and Technology, Vol. 5, Issue 1, January 2018
[7] Adrian McEwen, Hakim Cassimally. Designing the Internet of Things. Wiley and sons 2014
[10] Bhumi Nakhuva and Prof. Tushar Champaneria, STUDY OF VARIOUS INTERNET OF
THINGS PLATFORMS. International Journal of Computer Science & Engineering Survey
(IJCSES) Vol.6, No.6, December 2015
[12] Ali Al Dahoud and Mohamed Fezari, NodeMCU V3 for Fast IoT Application
Development.
[13] https://www.electronicwings.com/sensors-modules/bluetooth-module-hc-05-
[14] https://learn.sparkfun.com/tutorials/internet-of-things-experiment-guide/experiment-1-
temperature-and-humidity-logging
[15] https://lastminuteengineers.com/l298n-dc-stepper-driver-arduino-tutorial/
[16]https://internetofthingsagenda.techtarget.com/definition/microcontroller#:~:text=A%20micr
ocontroller%20is%20a%20compact,peripherals%20on%20a%20single%20chip.
[17] “The internet of Things reference model” DRAFT-Controlled distribution by CISCO
183
[18] https://techbeacon.com/enterprise-it/4-stages-iot-architecture
[19] https://logz.io/blog/the-importance-of-security-in-iot/
[20] https://www.iotforall.com/securing-iot-solution-start-with-network-layer/
[21] https://www.electronicdesign.com/industrial-automation/article/21805420/8-critical-iot-security-
technologies
[22] Anca D. Jurcut, Pasika Ranaweera, Lina Xu. Introduction to IoT security. School of Computer
Science University College Dublin, Ireland
[23] https://www.tutorialspoint.com/arduino
184