0% found this document useful (0 votes)
16 views254 pages

E Book EmbeddedSystemsandIoT

The document is a publication titled 'Embedded Systems and IoT' authored by Dr. J. Sylvia Grace, Mr. Pradeep Sharma, Dr. Aaquil Bunglowala, and Dr. Sandeep Sharma, set to be released in December 2024. It covers various aspects of embedded systems, microcontroller architecture, programming in Embedded C, IoT devices, communication protocols, and applications in smart technologies. The book aims to serve as a comprehensive resource for understanding and developing embedded systems and IoT applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views254 pages

E Book EmbeddedSystemsandIoT

The document is a publication titled 'Embedded Systems and IoT' authored by Dr. J. Sylvia Grace, Mr. Pradeep Sharma, Dr. Aaquil Bunglowala, and Dr. Sandeep Sharma, set to be released in December 2024. It covers various aspects of embedded systems, microcontroller architecture, programming in Embedded C, IoT devices, communication protocols, and applications in smart technologies. The book aims to serve as a comprehensive resource for understanding and developing embedded systems and IoT applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 254

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/387455806

EMBEDDED SYSTEMS AND IoT

Book · December 2024


DOI: 10.59646/embedsysiot/115

CITATIONS READS

0 396

2 authors, including:

Sandeep Sharma
Bharati Vidyapeeth College of Engineering, Delhi
43 PUBLICATIONS 52 CITATIONS

SEE PROFILE

All content following this page was uploaded by Sandeep Sharma on 27 December 2024.

The user has requested enhancement of the downloaded file.


EMBEDDED SYSTEMS AND IoT
Authors
Dr. J. Sylvia Grace
Assistant professor
Department of Computer Science and Engineering
K. C. G College of Technology
Karapakkam, Chennai, Tamil Nadu, India.

Mr. Pradeep Sharma


Assistant professor
Department of Computer Science
Gyan Ganga college of Excellence
Jabalpur, Madhya Pradesh, India.

Dr. Aaquil Bunglowala


Professor and Associate Dean
STME, NMIMS University, Indore, India.

Dr. Sandeep Sharma


Assistant Professor
Department of Electrical and Electronics Engineering
Bharati Vidyapeeth’s College of Engineering
New Delhi, India

i
EMBEDDED SYSTEMS AND IoT
(Author: Dr. J. Sylvia Grace, Mr. Pradeep Sharma, Dr. Aaquil
Bunglowala and Dr. Sandeep Sharma)

ISBN: 978-81-969431-4-1
DOI: https://doi.org/10.59646/embedsysiot/115
Edition 1: January 2024
Published by
San International Scientific Publications
Email: [email protected]
Website: sanpublications.nobelonline.in

All rights reserved

No part of this publication maybe reproduced,


stored in a retrieval system, or transmitted,
in any form or by any means, electronic, mechanical,
photocopying, recording or otherwise,
without the prior permission of the publishers.

Publisher’s Disclaimer
The Publisher of this book states that the
Editors and Authors of this book has taken
the full responsibility for the content of this book,
any dispute and copyright violation arising
based on the content of this book
will be addressed by the editor(s), furthermore,
the authors indemnify the publisher from damages
arising from such disputes and copyright
violation as stated above.

ii
ACKNOWLEDGEMENTS

We want to express our heartfelt gratitude to our family for


playing a crucial role in the realization of this academic
achievement. We extend our deep appreciation to our colleagues
and mentors who generously shared their knowledge and expertise.
Their guidance has been a motivating force in the creation of this
book.

We also acknowledge the publishers for their immense


support and dedication in bringing this book to fruition. Finally, we
extend our appreciation to everyone who has been a part of this
academic journey, contributing to its success with their collective
support.

iii
CONTENTS

PAGE
UNIT TITLE
NUMBER
UNIT I 8-BIT EMBEDDED PROCESSOR 1
1.1 Bit Microcontroller 1
1.2 Microcontroller Architecture 3
1.2.1 Types of Interrupts 6
1.2.2 Data Types 8
1.2.3 Addressing Modes 9
1.2.4 Applications of 8051 Microcontroller 13
Architecture
1.3 8051 Instruction Set 14
1.3.1 Data moving or handling Instructions 15
1.3.2 Loop and Jump Instructions 18
1.3.3 Shifting Operators 19
1.3.4 Bit-Oriented Instructions 20
1.4 Programming Parallel Ports 22
1.4.1 Crystal Oscillator 23
1.4.2 Configuring ports 27
1.5 Timers and Serial Port 29
1.5.1 Timer Mode 29
1.5.2 Counter Mode 29
1.5.3 TMOD Register 30
1.5.4 Mode 0 of Timer/Counter 32
1.5.5 Mode 1 of Timer/Counter 33
1.5.6 Mode 2 of Timer/Counter 34
1.5.7 Mode 3 of Timer/Counter 35
1.5.8 Serial Port 36
1.6 Interrupt Handling 38
1.6.1 Types of interrupt in 8051 38
Microcontroller
1.6.2 Interrupt programming in 8051 41

iv
UNIT II EMBEDDED C PROGRAMMING 45
2.1 Programming Embedded System 45
2.1.1 Embedded C Programming Language 45
2.1.2 Basics of Embedded C Program 46
2.1.3 Data Types in Embedded C 47
2.1.4 Basic Structure of an Embedded C 48
Program
2.1.5 Different Components of an Embedded 49
C Program
2.2 Memory And I/O Devices Interfacing 49
2.2.1 Memory Interfacing 50
2.2.2 I/O interfacing 51
2.2.3 8279 Programmable Keyboard 51
2.2.4 8257 DMA Controller 52
2.2.5 Intel 8257 53
2.2.6 8257 Architecture and Pin Description 53
2.3 Programming Embedded Systems in C 56
2.3.1 Embedded C Programming with Keil 56
Language
2.3.2 Basic Embedded C Programming Steps 58
2.4 Real-Time Operating System (RTOS) 64
2.4.1 RTOS scheduling 64
2.4.2 Zephyr RTOS 65
2.5 Multiple Tasks and Processes 66
2.5.1 OS and RTOS 66
2.5.2 Task and process 66
2.5.3 Release time and deadline 66
2.5.4 Process State and Scheduling 69
2.5.5 Task Characteristics for a single CPU 73
in a system
2.6 RTOS Task Context Switching 73
2.6.1 Context Switching Basics 74
2.6.2 Implementation Details 75
2.6.3 Memory Allocation 75
2.6.4 Context Switching Flow 76
v
2.7 Priority Based Scheduling Policies 78
2.7.1 Earliest-Deadline-First Scheduling 78
2.7.2 EDF properties 80
2.7.3 Rate Monotonic Scheduling 80
2.7.4 Priority Inversion 82
2.7.5 Wait for graph 83

UNIT III IoT AND ARDUINO PROGRAMMING 85


3.1 Introduction to the Concept of IoT Devices 85
3.1.1 IoT 85
3.1.2 Types of IoT 85
3.1.3 IoT Devices 87
3.1.4 Examples of IoT Devices 88
3.2 IoT Devices Versus Computers 89
3.3 IoT Configurations 90
3.3.1 Device configuration 90
3.3.2 Configuration versions 92
3.4 IoT Components 93
3.5 Introduction to Arduino 97
3.6 Types of Arduino 99
3.6.1 Arduino UNO 99
3.6.2 LilyPad Arduino 100
3.6.3 Arduino Mega 101
3.6.4 Arduino Leonardo 101
3.6.5 Arduino Red Board 102
3.6.6 Arduino Shields 102
3.7 Arduino Toolchain 103
3.8 Arduino Programming Structure 106
3.8.1 Overview 106
3.8.2 Arduino Program structure 109
3.9 Sketches 111
3.9.1 Comments 111
3.9.2 Variables 112
3.9.3 Functions 113
vi
3.10 Pins 117
3.10.1 Properties of Pins Configured as 118
INPUT
3.10.2 Pullup Resistors with pins configured 118
as INPUT
3.10.3 Properties of Pins Configured as 119
INPUT_PULLUP
3.10.4 Properties of Pins Configured as 120
OUTPUT
3.11 Input/Output from Pins Using Sketches 121
3.11.1 Step-By-Step Instructions 121
3.11.2 Analog input, analog output, serial 123
output
3.12 Introduction to Arduino Shields 127

UNIT IV IoT COMMUNICATION AND OPEN 135


PLATFORMS
4.1 IoT Communication Models and APIs 135
4.1.1 Types of Communication Models in 136
IoT
4.1.2 REST-based Communication APIs 140
4.1.3 WebSocket based communication API 142
4.2 IoT Communication Protocols 143
4.2.1 AMQP 143
4.2.2 Bluetooth and BLE 144
4.2.3 Cellular 144
4.2.4 CoAP 145
4.2.5 DDS 145
4.2.6 LoRa and LoRaWAN 146
4.2.7 LWM2M 146
4.2.8 MQTT 146
4.2.9 Wi-Fi 147
4.2.10 XMPP 148
4.2.11 Zigbee 148
4.2.12 Z-Wave 148

vii
4.3 Bluetooth 149
4.4 Wi-Fi 152
4.4.1 Working 153
4.4.2 Types of Wi-Fi Connections 154
4.5 ZigBee 156
4.5.1 ZigBee Frequency 158
4.5.2 ZigBee vs Wi-Fi 158
4.5.3 ZigBee vs Bluetooth 159
4.5.4 System Structure 159
4.5.5 Topologies 160
4.5.6 ZigBee Architecture 162
4.5.7 ZigBee Applications 163
4.6 GPS 164
4.7 GSM modules 167
4.7.1 GSM/GPRS Module 167
4.7.2 AT commands for GPRS Module 168
4.7.3 IoT using GSM/GPRS Module 169
4.8 Open Platform 169
4.9 Raspberry Pi Architecture 171
4.10 Programming 172
4.10.1 Basics of the Python Programming 173
language
4.10.2 Programming Raspberry Pi using the 176
terminal
4.11 Interfaces 176
4.12 Accessing GPIO Pins 177
4.12.1 Pin Numbering 179
4.12.2 Control LED with Push Button using 180
Raspberry Pi
4.12.3 Control LED using Python 181
4.12.4 Functions Used 181
4.13 Sending and Receiving Signals Using GPIO 184
Pins
4.14 Connecting to the Cloud 186

viii
UNIT V APPLICATIONS DEVELOPMENT 190
5.1 Complete Design of Embedded Systems 190
5.1.1 Embedded Systems Design Cycle 190
5.1.2 Analysis of Requirements 191
5.2 Development of IoT Applications 193
5.2.1 Define the requirements for the 194
application
5.2.2 Choosing the right hardware 195
5.2.3 Find the right connectivity protocols 195
5.2.4 Ensure the firmware is well equipped 196
5.2.5 Pick the right cloud platform 197
5.2.6 Embedded System Design Examples 197
5.2.6 Design Metrics 199
5.3 Home Automation 202
5.3.1 Home Automation System 205
Components
5.3.2 Cloud Computing with Home 208
Automation
5.3.3 Home Automation 512
5.4 Smart Farm 215
5.4.1 The IoT-Based Smart Farming Cycle 217
5.4.2 IoT Solutions to Agricultural Problems 218
5.4.3 Third Green Revolution 220
5.5 Smart Cities 221
5.5.1 Benefits of IoT in Smart Cities 226
5.5.2 Smart City Implementation Model 228
5.6 Smart Healthcare 228
5.6.1 IoT for Patients 229
5.6.2 IoT for Physicians 229
5.6.3 IoT for Hospitals 230
5.6.4 IoT for Health Insurance Companies 230
5.6.5 Simple Healthcare System Architecture 232
5.7 Layers of IoT Architecture 236

ix
Embedded Systems and IoT

UNIT I

8-BIT EMBEDDED PROCESSOR

1.1 8-Bit Microcontroller

In the 1980s, Intel was the company that developed the 8051
microcontroller. It was constructed on top of Harvard Architecture,
and its primary objective from the beginning was to make it easier to
integrate embedded devices. In order to reduce the amount of power
required for operation, Intel updated the Microcontroller 8051 to
make use of CMOS technology rather than NMOS technology. In
order to accommodate this modification, a new version of the chip,
known as the 80C51, was made available. The NMOS technology was
first used for its design, despite the fact that it consumes more power
than other available choices. When compared to their predecessors,
modern microcontrollers are able to perform their functions with a
much lower amount of power consumption. An 8051 microprocessor
may be used in a wide variety of different ways. As a result, the
engineering projects that students do in their final year employing
8051 microcontrollers are quite important. The purpose of this article
is to provide an introduction to the 8051 microcontroller and its inner
workings. One kind of integrated circuit is known as a
microcontroller. A dual inline package, sometimes known as a DIP
for short, is the housing for the 40-pin device. Additionally, it has two
16-bit timers, 128 bytes of random access memory (RAM), and 4
kilobytes of read/write memory. In order to fulfil the criteria, it is
equipped with four programmable 8-bit ports that are addressable
and operate in parallel. The system bus is an essential component of
the architecture of the 8051 microprocessor. The primary purpose of
this device is to establish connections between the various devices
and the primary computer. This bus is comprised of a multitude of
components, including control signals, an 8-bit data bus, and a 16-bit
address bus, amongst others. A number of additional devices,
including memory, interrupt control, timers, the central processing
unit (CPU), and the serial interface, may also be connected to the
system bus. The data bus and the programme bus are two distinct
interfaces on the 8051 microcontroller.

1
Embedded Systems and IoT

Along with its 8-bit processor unit, the microcontroller also has an 8-
bit accumulator. Not only that, but the 8051 microcontroller is
programmed using the Keil software package and embedded C
language, and it contains an 8-bit B register as one of its main
functional blocks. It also has many more registers that are 8-bit or 16-
bit in size. An integral built-in RAM makes the internal processing
and operation of the 8051 microcontroller much easier. For storing
information that is only needed temporarily, this is called prime
memory. Because the microcontroller's power source is always on, the
contents of its volatile memory may be corrupted at any moment.
The design and instruction set of this microcontroller are quite
simple, making it a breeze to work with. Furthermore, its processing
power is somewhat limited.

Features

The following is a list of the primary characteristics of the architecture


of the 8051 microcontroller.

• 8-bit Central Processing Unit with two Registers A and B.


• 8K Bytes – An example of a flash memory that provides
support for the system while it is being programmed is known
as internal read-only memory (ROM).
• 256 Bytes – The internal random access memory (RAM) is
divided into four banks of eight registers each. The
addressable registers have a width of 16 bits while the general-
purpose registers have an 80-bit width. The basic RAM has 128
bytes running from 00H to 7FH.
• SFRs, or special function registers, take up the remaining 128
bytes of RAM, starting at address 80H and going all the way
up to address FFH. These registers are responsible for
controlling a variety of peripherals, including the Serial Port,
Timers, and all I/O Ports, amongst others.
• * Interruptions such as External-2 and Internal-3
• Oscillator and Clock (CLK) Circuit.
• Control Registers, which include PCON, SCON, TMOD,
TCON, IE, and IP.
• 16-bit Timers or Counters -2 like T0 & T1.

2
Embedded Systems and IoT

• Program Counter with a resolution of 16 bits and DPRT (Data


Pointer).
• There are 32 I/O pins, which are organized in the form of four
ports and are labeled P0, P1, P2, and P3.
• Stack Pointer (SP) - 8 bits and the PSW (Processor Status
Word).
• Transmission and Reception of Serial Data for Full-Duplex
Operation

1.2 8051 Microcontroller Architecture

The architecture of the 8051 microcontrollers may be seen in the


following diagram. Let's take a more in-depth look at the
characteristics of the design of the 8051 microcontroller:

Figure 1.1: 8051 Microcontroller

CPU (Central Processor Unit):

The Central Processing Unit, sometimes known as the CPU, is the


"brain" of any processing system. You may already be acquainted

3
Embedded Systems and IoT

with this term. It is responsible for monitoring and managing all of


the operations that take place inside the microcontroller. The user has
no control over how the central processing unit (CPU) operates. It
analyzes the program that is written in the storage space known as
ROM, then it executes all of the instructions and performs the task
that was anticipated. The central processing unit (CPU) of an 8051
microcontroller is responsible for managing the various register
types.

Interrupts:

The headline states that an interrupt is a call to a subroutine that


scans the microcontroller's principal function or duty and allows it to
execute another programme that is more important at that moment.
Because it helps in emergency situations, the 8051 chip's "Interrupt"
capability is quite helpful. Interrupts provide us a way to postpone or
delay the process that we are now working on, carry out a job that is
part of a subroutine, and then resume the regular program
implementation. When an interrupt occurs, the core program of the
Microcontroller 8051 may be temporarily halted or broken if the
microcontroller was built in such a way that allows for this
possibility. When the work that is part of the sub-routine has been
completed, the implementation of the main program will start up
automatically as per the norm. Within the 8051 Microcontroller, there
are a total of five interrupt supplies. Out of these five, two are timer
interrupts, two are peripheral interrupts, and one is a serial port
interrupt.

Memory:

In order for the microcontroller to do its job, a programming


containing instructions is required. With the help of this programme,
the microcontroller can now carry out certain operations with
extreme precision. These programmes need a place to store and
analyse data in order for the microcontroller to do any task.

Program memory, also known as code memory, is the term given to


the portion of the microcontroller's memory that is activated so that it
may begin amassing its program. It is also known as ROM, which
stands for read-only memory, in common parlance.

4
Embedded Systems and IoT

Memory is another thing that the microcontroller requires so that it


may temporarily store data or operands. Data Memory refers to the
storage space that temporarily stores data for the purpose of working,
and the storage medium that we use for the most part, known as
Random Access Memory or RAM, was developed specifically for this
purpose. The microcontroller 8051 has a code memory or program
memory of 4 kilobytes, making it a device that has 4 kilobytes of rom,
and it also has a data memory (RAM) of 128 bytes.

Bus

In its most basic form, a bus is made up of a collection of wires that


act as a channel for communication or a mechanism for the
transmission of data. These buses have eighteen or more wires
altogether. As a consequence of this, a bus may accommodate 8 bits,
for a total of 16 bits. There are two categories of buses, as follows:

• Address Bus: The address bus of a microcontroller 8051 has 16


bits of resolution. It is brought into action so that memory
locations may be addressed. In addition to this, it is used to
send the address from the central processing unit to the
memory.
• Data Bus: The data bus of the microcontroller 8051 consists of
8 bits. It is used for the purpose of data carting.

Oscillator

Because the microcontroller is a piece of digital circuitry equipment,


we can all agree that it requires a timer in order for it to do its
purpose. An on-chip oscillator, which serves as a time source for the
Central Processing Unit (CPU) and is part of the Microcontroller 8051,
is responsible for performing this function. Because of this, the
productivity thumps of the oscillator remain stable, which makes it
easier to use all of the components of the 8051 Microcontroller in a
synchronized manner. Port for Input and Output: Because we are
aware of the fact that microcontrollers are used in embedded systems,
we know that these systems are used to handle the functionality of
various devices.

5
Embedded Systems and IoT

In order to gather it and transmit it to other devices, machines, or


peripherals, the microcontroller must have I/O (input/output)
interface ports. A number of peripherals may be connected to the four
input/output ports on the Microcontroller 8051, which allow it to
carry out this function. Timer and Counter: The 8051 microcontroller
has its own set of timers and two 16-bit counters. The counters'
registers are eight bits in size. Interval measurement, pulse width
determination, and many more applications are possible with the
help of a timer.

1.2.1 Types of Interrupts

The following are the sources of the interrupts that are generated by
the 8051 microcontrollers:

There is both program memory and data memory in the 8051


microcontroller design.

• Program Memory is where the computer keeps its instructions.


It is often designed as Read-Only Memory (ROM), so any
program stored in it will be accessible even after a power cycle
or reset.
• Values of variables, temporary data, interim results, and other
data necessary for the correct execution of the program are all
stored in the Microcontroller's Data Memory.

Timer and Control Unit

A delay or a time gap must be created between two occurrences in


order for a timer to fulfill its primary purpose. This microcontroller
has two timers, each of which is 16 bits in size. Because of this, the
system is able to create two delays simultaneously, allowing it to
provide the appropriate delay. In general, each and every
microcontroller makes use of hardware delays.

6
Embedded Systems and IoT

These are instances in which the processor makes use of a physical


device to produce a certain delay. This kind of device is known as a
timer. The processor may specify the amount of delay that should be
created by the timer, and the timer will send a signal to the processor
at the appropriate moment whenever the specified amount of delay is
generated. This processor also allows us to create a delay that is
specific to the system requirements. However, as it will be unable to
do any other activities inside that certain time range, this will result in
the CPU being engaged constantly. Consequently, the
microcontroller's built-in timer is a great feature since it frees up the
processor to work on other tasks. The microcontroller has a number
of components, such as a programme counter, data pointer, stack,
stack pointer, instruction registers (including latches), temporary
registers, and I/O port buffers.

Registers

The primary purpose of registers in microcontrollers is to store data


as well as short-term instructions. These instructions are mostly used
to process addresses in order to retrieve data. This microcontroller
has 8-bit registers, and the starting addresses for those registers are
D0 through D7. The least significant bit, or LSB, in this context is D7,
whereas the most significant bit, or MSB, is D0 to D7. In order to
handle the data in a manner that is superior than 8 bits, it first has to
be segmented into eight distinct bit portions. It comes with a number
of registers, although programmers most often have access to general-
purpose type registers. They are divided into two categories, namely
general purpose and special purpose, respectively. The majority of
registries that may be used for a variety of purposes are detailed
below.

• The primary function of an accumulator is to carry out


instructions pertaining to arithmetic and logic.
• Registers such as B, R0 through R7 are used for the purpose of
storing data as well as instruction addresses.
• Data Pointers, also known as DPTR, are what are used to
enable and process data in a variety of addressing modes. This
register has a DPH, which stands for "high byte," and a DPL,
which stands for "low byte," and its primary use is to store a
16-bit address. As a result, it is possible to make use of it as a

7
Embedded Systems and IoT

base register inside non direct jumps, lookup table


instructions, and external data transfer.
• The program counter, sometimes known as the PC, is a 16-bit
register that is used to hold the location of the next instruction
that will be carried out.
• Aside from the program counter register and the data pointer
register, each of these registers consists of 8 bits.

1.2.2 Data Types

There is only one data type on this microcontroller, and it uses an 8-


bit capacity for each register. In cases when the data quality exceeds 8
bits, it is the developer's obligation to reduce the data to 8 bits before
processing. Among the several data directives available in assembly
language, the DB directive sees the most use.

PSW Register

PSW is an abbreviation that stands for "Program status word," and it


refers to a kind of register that may be found in microcontrollers. It is
also known as a flag register and serves the purpose of demonstrating
the location of arithmetic logic instructions such as carry bit, zero
carry bit, and so on. The PSW register, sometimes known as the flag
register, is an 8-bit register that only uses 6-bits. This register has
eight flags, and those flags are referred to as conditional flags. These
flags are included. If the requirement is met, these flags will carry out
the command without any further processing. Overflow, parity,
auxiliary carry and carry are the conditional flags that are used here.
The bit numbers of the program status word registers, such as 3 and
4, are the ones that are used to change the bank registers. In contrast,
bit numbers 1 and 5 are not utilized, but the programmer might use
them to carry out a particular operation.

Register Banks

The RAM that is utilized for stacks and register banks has a capacity
of 32 bytes, and this memory is partitioned into four distinct kinds of
banks.

8
Embedded Systems and IoT

Therefore, each back has eight registers that go from R0 all the way
up to R7. In this context, R0 and R7 signify the locations of RAM,
namely the zeroth and seventh positions, respectively. The second
bank register may be found starting at spot 8 and continuing all the
way to 05H. The 10H site is where the third bank register is started,
and the 17H location is where it is finished. The last bank may go
anywhere between the 18H-1FH.

Stack

The portion of random access memory known as the stack is mostly


used by the CPU for the storing of data that is otherwise temporarily
addressed. Due to the fact that there are only a relatively limited
number of registers available in a microprocessor for the purpose of
storing addresses and data, it is a highly important component. The
stack in 8051 microcontrollers has a width of 8 bits and may store
values ranging from 00 to FFH in its memory. Through the usage of
the CPU, the stack pointer may be manipulated to allow for its
utilization. This particular microcontroller has an 8-bit stack pointer,
which indicates that it is able to accommodate values ranging from
00H to FFH. Once it has been triggered, then the value 07 will be
included in the stack pointer.

Organization of Memory

The memory structure of the microcontroller is rather complicated,


and it comes with a distinct address bus that may be utilized for
program memory, external RAM, and data memory respectively. The
Harvard architecture that was established via Harvard in the year
1944 is an important factor in this.

1.2.3 Addressing Modes

There are several ways that microprocessors may get data. In most
cases, the data that has been saved in the memory, register, and
elsewhere may be utilized immediately. These many approaches of
gaining access to data are collectively referred to as addressing
modalities. There are several varieties of microcontrollers, each with
its own unique way of addressing that is determined by the
manufacturer's design.

9
Embedded Systems and IoT

The term for the manner in which data is accessed is addressing


mode. Using multiple addressing modes allows for a variety of access
methods to the data by the CPU. The 8051 microcontroller has five
different addressing modes, including the following:

Immediate Addressing Mode:

When using this style of addressing, the source must be a value that
may be followed by the '#' character, and the destination can be either
SFR registers, general purpose registers, or an address. It is used for
instantly saving the value in the memory registers as soon as it is
acquired.

10
Embedded Systems and IoT

Register Addressing Mode:

Both the source and the destination of the address in this mode must
be registers; however, general purpose registers cannot be used. This
prevents the data from being transferred around inside the general-
purpose bank registers.

Direct Addressing Mode

When using this style of addressing, either the source or the


destination (or both the source and the destination) must be
addresses, but the value cannot be used.

11
Embedded Systems and IoT

Indirect Addressing Mode:

In this manner of addressing, either the source or the destination (or


the source or the destination) must be an indirect address, but they
cannot be a value. This way of addressing is compatible with the idea
of pointers. A variable known as the pointer is one that is used for
the purpose of storing the address of another variable. This idea of a
pointer is only ever applied to the R0 and R1 registers.

Indirect Addressing Mode

Base Index Addressing Mode:

This addressing method is used whenever the data are to be read


from either the ROM memory or the external memory. The data
stored in the code memory is inaccessible to any of the addressing
modes. In order to read the code, the DPTR register has to be used.
The data in the code or external memory may be pointed to with the
help of the DPTR.

12
Embedded Systems and IoT

1.2.4 Applications of 8051 Microcontroller Architecture

The microcontroller 8051 has a wide variety of applications, the


majority of which are machines. This is mostly due to the fact that it is
easy to include it into a project or to construct a machine with it as the
center of attention. The following are some of the most important foci
of attention:

Figure 1.2: Applications of 8051 microcontroller

• Energy Management: In both residential and industrial


settings, accurate measuring device systems are helpful in
determining the amount of energy that is being used.
Integrating microcontrollers into these metering systems
enables them to be prepared effectively.

13
Embedded Systems and IoT

• Touch screens: Touch sensing capabilities are included into


the designs of the majority of microcontrollers by their
manufacturers. Microcontrollers that are combined with touch
sensing displays are used in a variety of portable devices,
including media players, gaming devices, and mobile phones,
to name a few examples.
• Automobiles: The 8051 microcontroller is becoming more
popular in the field of providing solutions for automobiles.
They play a significant role in the hybrid automobile industry
as a means of controlling engine fluctuations. In addition,
functions such as cruise control and an anti-lock braking
system have been included thanks to the integration of
microcontrollers, which has resulted in the vehicle having
increased functionality.
• Medical Devices: The use of micro-controllers in portable
medical devices such as glucose and blood pressure monitors
makes it possible to display the measures and, as a
consequence, provides a better level of reliability in terms of
providing accurate medical findings.
• Medical Devices: The use of micro-controllers in portable
medical devices such as glucose and blood pressure monitors
makes it possible to display the measures and, as a
consequence, provides a better level of reliability in terms of
providing accurate medical findings.

1.3 8051 Instruction Set

The process of developing a program for the microcontroller mostly


entails providing instructions (commands) in the precise sequence in
which they should be carried out in order to carry out a certain
activity. This is done in order to accomplish a particular goal. Because
electronics are unable to "understand," for instance, what a command
like "if the push button is pressed - turn the light on" implies, a
specific number of simpler and more clearly defined instructions that
can be recognized by a decoder are required. The collection of all
commands is referred to as the INSTRUCTION SET. All
microcontrollers that are compatible with the 8051 have a total of 255
instructions, which translates to 255 unique words that may be used
in the programming of the device.

14
Embedded Systems and IoT

At first glance, it seems to be a daunting quantity of strange


indications that need to be committed to memory. However, despite
appearances, it is not as difficult as it seems. There are only 111
commands that are actually distinct from one another due to the fact
that several instructions are regarded to be "different" despite the fact
that they carry out the same task. For instance, the instructions ADD
A,R0, ADD A,R1,... ADD A,R7 all carry out the identical operation,
which is known as the addition of the accumulator and the register.
Because there are 8 registers of this kind, it is necessary to keep track
of each instruction individually. Taking into consideration the fact
that all instructions can only execute 53 operations (including
addition, subtraction, copying, and so on), and that the majority of
these operations are used seldom in real practice, there are actually
20–30 abbreviations that need to be taught, which is adequate. An
instruction is a directive that is sent to the microcontroller in order for
it to carry out a particular action on the data that is being presented.
A microcontroller's instruction set is a collection of instructions that
the microcontroller is programmed to carry out in order to complete
various tasks.

1.3.1 Data moving or handling Instructions

Mnemonics Operational descriptions

Mov a,#num This directive requires you to enter the current


data in to acc

Mov Rx,a The data from acc will be copied to Rx per this
command.

Mov a,Rx This command tells you to transfer information


from Rx to acc.

Mov Rx,#num This instruction should be copied into Rx with the


immediate data num.

15
Embedded Systems and IoT

Mov a,add This command will copy the information from the
direct address location and add it to the acc.

Mov add,a The data should be copied from acc and added to
direct address add per this command.

Mov add,#num These are the instructions The instant data number
should be copied into the direct address.

Mov add1,add2 The data should be copied from add2 to add1


according to this command.

Mov Rx,add The data should be copied from straight this


command.

Mov add,Rx This instruction will copy the data from Rx and
add it to the direct address.

Mov @Rp,a These are the instructions Make a copy of the


information in acc and paste it into Rp.

Mov a,@Rp The data located at the location in Rp should be


copied over to acc per this command.

Mov add,@Rp These are the instructions Make a copy of the


information that is located at address in Rp and add

Mov @Rp,add These are the instructions Make a copy of the


information in the add to address box in Rp.

Mov @Rp,#num These are the instructions The immediate byte


number should be copied to the address in Rp.

Movx a,@Rp The instruction is to copy the contents of the


external add-on into the acc file.

16
Embedded Systems and IoT

Movx a,@DPTR The directive is to copy the content of the external


add-on into the DPTR to acc.

Movx @Rp,a These are the instructions Make a copy of the


information found in acc and paste it into the
external add in Rp.

Movx @DPTR,a Following these instructions, copy the contents of


acc into the DPTR external add.

Movc Acc and DPTR are added together to generate the


a,@a+DPTR address of the instruction in this case, and the
contents of both are transferred into acc.

Movc a, @a+PC The address of the instruction is created by


combining acc and PC together in this method, and
the body of the instruction is transferred to acc.

Push add During this instruction, the Stack Pointer (SP) will be
incremented, and then the data will be copied from the
source and added to the location stored in the SP.

Pop add This instruction copies the data from a location in


SP that is held in internal RAM and sends it to the
add and decrement destination in SP.

Xch a, Rx The data are to be exchanged between acc and Rx


according this instruction.

Xch a, add The data between acc and provided add are to be
exchanged per this command.

Xch a,@Rp The data between acc and address will be


exchanged in this instruction in Rp.

17
Embedded Systems and IoT

1.3.2 Loop and Jump Instructions

Looping operation in the 8051:

The development of a loop may be accomplished by performing a


series of instructions for a certain number of times in a row. The
looping action allows the same collection of subroutines to be
executed inside a program an adjustable number of times, according
to the needs of the application. Take into consideration the instruction
DJNZ register; the label is what's used when carrying out the loop
operation. This instruction decreases the value of the register by one,
and if the register's value is not zero, the 8051 computer moves on to
the destination address that is specified by the label.

Example: Perform the calculation of 15 times 10 using the strategy of


a repeated addition.

Solution: The operation of multiplication may be accomplished by


continually adding the multiplicand up to the same number of times
as the multiplier.

18
Embedded Systems and IoT

Conditional Jump Instruction:

The following table provides a listing of the conditional jumps


instruction that may be found in 8051.

1.3.3 Shifting Operators

The shift operators are put to use in order to transmit and receive
data in the most effective manner. The 8051 microcontroller is made
up of four shift operators, which are as follows:

19
Embedded Systems and IoT

1.3.4 Bit-Oriented Instructions

Rotate Right (RR):

During this shifting process, the most significant bit (MSB) moves to
the least significant bit (LSB), and all of the bits shift bit-by-bit,
serially, towards the right side.

Syntax:

MOV A, #25h
RR A

20
Embedded Systems and IoT

Rotate Left (RL):

During this shifting process, the most significant bit (MSB) moves to
the least significant bit (LSB), and all of the bits shift bit-by-bit,
serially, toward the left side.

Syntax:

MOV A, #25h
RL A

RRC Rotate Right through Carry:

During this shifting operation, the least significant bit (LSB) will
become the carry, and the most significant bit (MSB) will become the
LSB. Additionally, all of the bits will be pushed towards the right side
bit by bit.

RLC Rotate Left through Carry:

During this process of shifting, the most significant bit (MSB)


becomes the carry, and the least significant bit (LSB) becomes the
carry. Additionally, all of the bits shift to the left in a location that is
bit-by-bit.

21
Embedded Systems and IoT

1.4 Programming Parallel Ports

Diagram of the ports and pins on the 8051 Members of the 8051
family are available in a variety of IC packages, including DIP (duo
in-line packaging), QFP (quad flat package), and LLC (leadless chip
carrier), but they all contain the same number of pins—40—that are
devoted to a variety of purposes, including I/O (input/output), RD
(reset), WR (write), address, data, and interrupts. For less demanding
applications, several vendors provide 20-pin variants of the 8051
microcontroller, which have a lower number of input and output
ports. Since the 40-pin chip is used by the vast majority of developers,
we will focus on it.

Figure 1.3: 8051 microcontroller (40 pins Ic)

22
Embedded Systems and IoT

Each of the four ports, P0, P1, P2, and P3, need a total of eight pins,
thus a group of 32 pins has been reserved for them. The chip receives
its supply voltage via the pin 40. The source of the electricity is +5V.
The ground is located at pin 20. The remaining pins have the
following designations: XTAL1, XTAL2, RST, EA, PSEN, and ALE.
The microcontroller receives its clock pulse via the oscillator, which is
controlled by the XTAL2/XTALI inputs. The port0 (AD0/AD7) is
formed by the pins from 32 to 39 on the board. Multiplexed pins P0.0
to P0.7 are utilized for both address and data communications. The
pins numbered 1 through 8 correspond to port 1 (P1.0 to P1.7), and
pins numbered 21 through 28 correspond to port 2. The transmission
of addresses into memory requires (P2.0 to P2.7), which is utilized.
The 8051 microcontroller may be restarted by using the RST pin,
which is located on the ninth position. The tenth through the
seventeenth pins are for port3, which is a specialized port that serves
many purposes. The address latch enable function is located on the
30th pin. When the pin is switched to the 1 position, the address is
sent via the pins AD0 through AD7. If the value of the pin is 0, data
will be sent across the pins AD0 through AD7 when the transfer takes
place. PSEN stands for "Program Strobe Enable" and is located on the
29th pin. This pin is used to enable reading the program from
external memory.

1.4.1 Crystal Oscillator

While the 8051 does have an oscillator integrated into the chip, it
cannot operate without an external clock. A quartz crystal oscillator is
often connected to the inputs XTAL (pin 19) and XTAL (pin 18). The
quartz crystal oscillator connected to XTAL1 and XTAL2 inputs also
need two 30-pF capacitors. One terminal of every capacitor is linked
to the earth as seen in Figure 1.2. Keep in mind that the 8051 family as
a whole operates at varying speeds. As used above, "speed" means
the maximum oscillator frequency that may be achieved via the
XTAL connection. Such a crystal must also have a frequency of 12
MHz or lower in order to be linked to a chip that runs at that
frequency. Similarly, a crystal must not exceed 20 MHz in order for a
microcontroller running at that frequency to function properly.

23
Embedded Systems and IoT

Figure 1.4: XTAL connection to an external clock source

The frequency on the XTAL2 pin is connected using the oscilloscope


once the 8051 has been powered up and linked to a crystal oscillator.

RST

The reset button is located on pin 9. It takes incoming data and has an
active high state. When an excessive amount of voltage is provided to
the pin, the microcontroller will reset and then shut down.

EA

Members of the 8051 family will be equipped with ROM that is on-chip for
the purpose of storing programs. In situations like these, the EA pin is wired
up to the VCC supply. Because there is no ROM on-chip for family
members like the 8031 and 8032, the program code must be saved in
external ROM, from whence it is then retrieved by the 8031 and 8032. The
fact that the EA pin is linked to GND indicates that the code is stored on an
external device. External Access, sometimes known as EA, is represented by
the DIP package pin number 31. It is a pin that is used for input and may be
connected to either ground or Vcc. This pin, in conjunction with PSEN, is
used by the 8031 to access programs that are stored in ROM memory that is
situated outside of the 8031. The following two pins are mostly used in
systems that are based on the 8031.

PSEN

This particular pin is an output. ''Program store enable'' is what


''PSEN'' stands for. This pin is linked to the ROM's OE pin, which
stores the program code; the external ROM is where the code is
stored.

24
Embedded Systems and IoT

ALE

It is a pin for output and has an active high state. When an 8031 is
connected to external memory, port 0 is responsible for providing
both the address and the data. Through a connection to the G pin of
the 74LS373 chip, the address and data may be demultiplexed using
the ALE pin.

Ports 0,1,2 and 3

Figure 1.5 Port 0 with Pull-Up Resistors

Each of the four ports on the 8051 can handle bidirectional data
transfer. Built into the design of each one are input buffers, output
drivers, and latches. P0, P2, and P3 will not only be responsible for
information and operations, but also for specialised tasks. As seen in
the figure below, there are four ports numbered P0, P1, P2, and P3.
We call them 8-bit ports because there are eight pins used by each
port. Because FFH is printed on each of the three ports (P0-P3), they
are immediately configured to function as inputs upon system reset.
To access the external memory, the procedure makes use of the Port 0
input buffers and the Ports 0 and 2 output drivers. For this
programme to work, Port 0 must time-multiplex the current byte's
output with the low byte of the address of the external memory. Port
2 will output the highest byte of an address when reading it from
external memory that is 16 bits wide. See figure 1.5 for an illustration
of how port 0 may be labelled as AD0-AD7; this provides it the
versatility to transmit both data and addresses.

25
Embedded Systems and IoT

The address and data for an external memory connection to the 8051
are provided via port 0. Using port 0 to multiplex address and data
allowed the 8051 to save pins. You can find out whether P0 contains
data or an address by using ALE. Data in the range D0-D7 is sent
when ALE is set to 0, while the address range A0-A7 is supplied
when ALE is set to 1. Therefore, in order to demultiplex the address
and data, ALE is used. In the absence of an external memory
connection, a ten thousand ohm pull-up resistor must be connected
externally to the P0 pins. This is due to the fact that PO is an open-
ended drain, unlike P1, P2, and P3. The term "open drain" describes
MOS chips in the same manner that "open collector" describes TTL
chips. The phrase "open drain" may also be used to describe an open
collector. Unlike Port 0, which requires a pull-up resistor, Ports 1, 2,
and 3 already have one on the circuit board, so there's no need to add
another one. At reset, all three of the device's ports—P1, P2, and P3—
are configured to accept input signals.

P1 and P2

If an 8051-based system does not have access to an external memory


device, then P1 and P2 are considered simple input and output. Port 2
and P0 must be used together to deliver the 16-bit address for the
external memory in systems that contain a connection to external
memory and are based on the 8031 or 8051. The designation A8-A15
for Port 2 suggests that it has a dual duty. Due to its usage for the
upper 8 bits of the 16-bit address, P2 cannot be used for input or
output when the 8051 is connected to an external memory source.

Port 3

A set of eight pins, numbered 10–17, are required. You may use it as
an input or an output, depending on your preference. None of the
three ports (P1, P2, and P3) need pull-up resistors. Along with its
principal function, Port 3 is in charge of sending many critical signals,
including interrupts. P3.0 and P3.1 represent the RxD and TxD serial
communication signals, respectively. So, you may use the 8051 with
either serial or parallel connections. For usage with external
interrupts, P3.2 and P3.3 are reserved.

26
Embedded Systems and IoT

Bits P3.4 and P3.5 are used by Timers 0 and 1, correspondingly.


While the other pins of port3 are usually used for various
purposes, P3.6 and P3.7 are used to give the WR and RD signals
for external memory connections. These signals are sent via P3.6
and P3.7.

Table 1.1: Port 3 Alternate functions

1.4.2 Configuring ports

Upon receiving the value '0', the port is configured to act as an


output. To change the port's configuration to an input, a '1' must be
typed to it. Putting "1" into Port0 prepares the port to accept data as
an input, so it may be used as an input in the future. For example, if
you want to change the value of Port0 from its default state to that of
an input port, you may do the following: MOV A,#0FFH; A is the hex
equivalent of FF; MOV P0,A; write '1' to port; MOV P2,A; P2 is the
same as A; MOV A,P2; P2 is the same as A. First, all of the port pins
in P0 are set to 1, and the accumulator is filled with the hexadecimal
value FFH using the immediate addressing method. You may specify
that port P0 will be used as the input port going forward with this
line. Port P0 seems to be occupied by an additional input device.

27
Embedded Systems and IoT

Port 2 is the output port, where the data kept in the accumulator is
sent from port2, after having been supplied to the accumulator by
port P0. Port 0 also performs the functions AD0-AD7. It has the
address and info as well. Port 0 is used to transmit the address and
data of the external memory to an 8051/31. Through Port 1, data is
entered and outputted. An input configuration will be applied to port
1 after the reset. Through port 2, data may be inputted and outputted.
An input configuration will be applied to port 2 after the reset. Using
Port 2 and P0, you may get the device's 16-bit address from the
external memory. Pins A8–A15 from port 2 and AD0-AD7 from port 0
must be linked if 16 bits are needed to access the external memory.
Port 2 will hold the higher-order byte and port 0 will hold the lower-
order byte as a consequence of this.

Table 1.2: Instructions used in single bit operations

JB and JNB are the instructions that are utilized when operating with
a single bit. These instructions keep track of a bit and act accordingly
according on whether or not that bit is set to 0 or 1. These two
instructions may be used for any bit on I/O ports 0 through 3,
including zero, one, and three. The instructions for functioning with a
single bit are detailed in Table 1.2. The single bit operations are
broken out in Table 1.2.

28
Embedded Systems and IoT

Access 1 or 2 bits

You may use these steps to access either one or two bits of the port.
Complement P0.4 with SETB P1.4, set P1.4 to CLR P2.2, clear P2.2
with SETB P1.0, and set just bit 0 of port 1 as high CPL P0.4. Clear
P2.2 with SETB P1.0. I will begin by making the following claim:
Along with the P0.4 bit, the CPL bit operates. It is changed to 0 if the
P0.4 bit is set to 1, and to 1 if it is set to 0 otherwise. The above
example uses SETB routines to convert the bit values P1.0 and P1.4 to
1. The CLR command will clear this particular bit.

1.5 Timers and Serial Port

There are two timer registers that are each 16 bits in size on an Intel
8051. Timer 0 and Timer 1 are the names given to these registers.
There are two different ways that the timer registers may be utilized.
Timer mode and Counter mode are the names of these two modes.
The only distinction that can be made between these two modes is
the origin of the incrementing signals for the timer registers.

1.5.1 Timer Mode

Counting the machine's internal cycles may be done while in the


timer mode. Therefore, throughout each cycle of the machine, this
register is advanced by one. Therefore, if the clock frequency is 12
MHz, the timer register will be increased once for every millisecond.
When it is in this mode, the external timer input pin is not taken into
consideration.

1.5.2 Counter Mode

Counting the happenings of the outside world is what the counter


mode does. In this mode, the value of the timer register is increased
whenever the external input pin goes from 1 to 0. In other words,
this mode is the default. The passage of time is seen as an event in
this context. The external input pins are sampled only once during
each machine cycle, and a further machine cycle will be necessary in
order to ascertain if a transition from 0 to 1 occurred.

29
Embedded Systems and IoT

This setting needs a minimum of two machine cycles. The highest


possible count frequency, given a frequency of 12 MHz, is 500 kHz,
which is obtained by dividing 12 MHz by 24. Hence, two seconds is
the duration for event counting. With the Timer or Counter, you may
choose between four different modes. The Timer and the Counter are
both affected by the Mode 0–Mode 2 parameters. What Mode 3 really
implies varies from timer register to timer register. The acronym
TMOD describes a register. It is possible to configure one of these
counters or timers using this programmable register. In modes 1 and
3, the Serial port is used for serial communication, respectively. The
baud rate is generated by the component known as timer1.
Consequently, every task requiring the usage of timers or counters
must make use of Timer0.

1.5.3 TMOD Register

TMOD, often known as Timer Mode, is an SFR. This registration may


be found at the location 89H. This cannot be addressed with bits.

Figure 1. 6: Timer Mode

Figure 1.7: Controls the running of the timers.

30
Embedded Systems and IoT

In the table that follows, we shall examine the intricacies of the bits
and the many operations associated with their high or low values.

hen the timer or counter is in mode 0 to 2, the Gate bit will be set to
the high state.

Examples

We may use the bit pattern 0 0 1 0 0 1 0 1 to set Timer0 as a 16-bit


event counter and Timer1 as an 8-bit auto reload counter.
Alternatively, we could use the bit pattern 0 0 1 0 0 1 0 1 to do the
same thing. It is comparable to the value of 25H. We can use this
instruction to program the TMOD register with this bit pattern if
that's what we want to do.

MOVTMOD, #25H

31
Embedded Systems and IoT

After the above command has been carried out, the program will
proceed to take control of the timer and the counter. If you want to
setup the system such that it operates in hardware controlled mode,
then you must set the gate bits to 1. Therefore, the bit patterns will be
1 0 1 0 1 1 0 1 = ADH, and the following command may be used:

MOVTMOD, #0ADH

1.5.4 Mode 0 of Timer/Counter

The 8-bit timer or counter with a 5-bit prescaler is used in the Mode 0
functioning of the microcontroller. Therefore, it is a timer/counter
that has 13 bits. It makes use of 5 bits of either TL0 or TL1, in
addition to all 8 bits of either TH0 or TH1.

Figure 1.8: Mode 0 of Timer/Counter

32
Embedded Systems and IoT

In the software that was just described, the Timer1 is set to operate in
timer mode 0. In this scenario, Gate equals 0. After that, the value
F0H will be stored into TH1, and the Timer1 interrupt will be
enabled. At long last, initialize the timer by setting the TR1 bit in the
TCON register.

1.5.5 Mode 1 of Timer/Counter

The timer or counter with 16 bits is used for the Mode 1 operation. In
the accompanying diagram, the Timer0 component is represented by
Mode 1.

Figure 1.9: Mode 1 of Timer/Counter

In the software that was just described, the Timer0 is set to operate in
timer mode 1. In this scenario, Gate equals 0. After that, the TL0
register will be filled with F0H, and the TH0 register will be loaded

33
Embedded Systems and IoT

with FFH. Finally, the Timer0 interrupt will be enabled. At long last,
initialize the timer by setting the TR0 bit in the TCON register.

1.5.6 Mode 2 of Timer/Counter

The 8-bit auto reload timer or counter is used in the Mode 2


functioning of the microcontroller. The following figure illustrates
how we are operating Timer1 in Mode 2.

Figure 1.10: Mode 2 for Timer1

34
Embedded Systems and IoT

In the software that was just described, the Timer1 is set to run in
timer mode 2. In this scenario, Gate equals 0. After that, the F0H is
loaded into the TL1 and the TH1. then turn on the interrupt for the
Timer1. At long last, initialize the timer by setting the TR1 bit in the
TCON register. When the serial port is operating in Mode 1 or Mode
3, the required baud rate is generated by Timer1 in Mode 2, which is
the default mode.

1.5.7 Mode 3 of Timer/Counter

The behavior of Timer0 and Timer1 in Mode 3 is distinct. If the


Timer0 is operating in mode 3, the TL0 will function as an 8-bit
timer/counter throughout that period. The standard will serve as the
governing factor for it.

Figure 1.11: Timer0 in Mode 3

Timer0 controls the bits, T0, and INT0 inputs. On the other hand, the
TH0 isn't a counter but an 8-bit timer. The TR1-labeled Timer1
Control bit is in charge of this. Set the TF1 counter to 1 if the TH0
counter overflows from FFH to 00H. Here is a visual representation
of what is shown: In Mode 3, Timer1 only keeps track of the count
and does not actually do any counting.

Depending on the scenario, Timer1 is programmed to function in


either mode 0 or 1 while Timer0 is in mode 3. The microcontroller
will remain unaffected by the Timer1 signal in this case. Use of the
TF1 by the TH0 timer transforms Timer1 into a Baud Rate Generator.

35
Embedded Systems and IoT

The following describes the significance of the gate bit for mode 3 in
both Timer0 and Timer1:

• Controlling the operation of an 8-bit timer/counter TL0 as


Mode 0, 1, or 2 is the responsibility of this component. The
only thing that can regulate the operation of TH0 is the TR1
bit. Therefore, the gate bit for Timer0 does not serve any
particular purpose while operating in this manner.
• Mode 3 is available for use by programs that need an
additional timer or counter that has 8 bits of resolution. The
8051 has three timers when it is set to Mode 3 of Timer0. One
timer of 8 bits controlled by TH0, another timer/counter of 8
bits controlled by TL0, and one timer/counter of 16 bits
controlled by Timer1.
• If Timer0 is in mode 3 and Timer1 is set to either 0 or 1, then a
high value on the gate bit or INT1 will activate the gun control
of Timer1. When Timer0 is in its third mode, this happens.
Unusual behaviour of the run control is seen when the gate is
high and INT1 is low.

1.5.8 Serial Port

TxD:

In most modes, this pin performs the function of a transmitter (that is,
it sends data), however in other modes, it does not perform the
function of a transmitter. Due to the fact that it is a serial connection,
the data is sent one bit at a time. The CPU delivers 8 bits at a time,
and those 8 bits are saved in a register that is called SBUF. The
processor sends one byte of data that is going to be conveyed to the
SBUF, and from there, the data is sent bit by bit, beginning with the
LSB of the byte that is stored in the SBUF and ending with the MSB.
After the whole byte has been transferred, an interrupt is generated
and sent to the processor by setting some flag to 1, allowing the CPU
to submit further data for transmission as soon as it receives the
interrupt. Following the transmission of each bit, there is a necessary
wait before moving on to the next bit.

36
Embedded Systems and IoT

Figure 1.12: SBUF

Because of this, SBUF requires a trigger, which is given by

• Timer T1 (in this context, T1 simply needs to trigger; it is not


necessary for T1 to have its overflow flag, which is mode 3 in
timers). Here, we have the ability to change the delay, which
also means that the data transmission delay may be changed
(the frequency can be changed). It features a baud rate that
may be adjusted.
• There is a predetermined trigger delay since the 8051 has a
built-in clock with a frequency of 1 MHz (fosc divided by 12),
and this delay cannot be changed. Therefore, the frequency
cannot be adjusted.It operates at a predetermined baud rate.

When SBUF sends 8 bits of data, the Ti flag is set to 1 in every


instance. In contrast to other interruptions, where the flag is
automatically cleared anytime a CPU enters an ISR state, the Ti flag
does not get cleared here when a processor enters an ISR state.

RxD:

This pin is mostly used for the receiving of data. It received the data
one bit at a time, beginning with the least significant bit (LSB) since
that is the order in which the transmitter delivers it. Additionally,
there is a register known as SBUF that saves all 8 bits that were
received.

37
Embedded Systems and IoT

Once the 8 bits have been received, rather than immediately issuing
an interrupt, it does a check for errors (errors that occurred as a result
of the transmission; the method by which error checking is performed
will be covered in forthcoming lessons). Once it has been determined
that the information that was received has no errors, the Ri flag will
be set, and the processor will be interrupted. After that, the processor
will enter ISR; similarly, Ri will not be cleaned automatically during
this phase. Data is sent from the processor to the SBUF storage area in
TxD's SBUF. When data is processed in RxD's SBUF, it is transmitted
from SBUF to the processor. The CPU is able to discern between the
two registers in this manner. There is a byte termed SM2; if the value
of SM2 is 1, then an error check will be performed after the SBUF of
RxD has been filled. And if that doesn't happen, there won't be any
kind of error check; instead, as soon as the SBUF in RxD is full, an
interrupt will be delivered immediately to the CPU.

1.6 Interrupt Handling

When another program with a higher priority than the one that is
now running requests access to the system buses, the microcontroller
will instead issue a call to a function rather than interrupting the
program that is currently being executed. Interrupts provide a way to
postpone or delay the operation that is now being carried out, carry
out a job that is part of a subroutine, and then begin the regular
program once more.

1.6.1 Types of interrupt in 8051 Microcontroller

Let's have a look at the five different interrupts that may occur in an
8051 Microcontroller:

Internal interrupts are those that are generated by the microcontroller


itself, such as the timer and serial interrupts. External interrupts, on
the other hand, are generated by extra interfacing devices or switches

38
Embedded Systems and IoT

that are linked externally to the microcontroller. These outside


disturbances could be set off by the signal's level or its edge. When an
interrupt occurs, the microcontroller runs the code that is known as
the interrupt service routine. In order for it to function, the interrupt-
corresponding memory address has to be enabled. Look at the
following interrupt vector table to get the interrupt that goes with the
memory location.

Table 1.3: Interrupt vector

Interrupt Structure of 8051 Microcontroller

When 'RESET' is executed, each of the interrupts is turned off, and as


a result, each of the interrupts must be turned on manually by the
program. If any of the five interrupts out of a total of five are made
active, the relevant interrupt flags will be set, as shown in the picture
below, which corresponds to the interrupt structure of an 8051
microcontroller. In order to set or clear any of the interrupts, a specific
function register called interrupt enabled (IE) must be used; the
priority of this register is determined by the interrupt priority
register.

Interrupt Enable (IE) Register

The IE register is what's utilized to enable and disable the interrupt as


necessary. This is a bit addressable register, and in order to enable
interrupts, the EA value in this register has to be set to one. The
specific interrupt, such as the timer, serial, or external inputs, may be
enabled by setting the appropriate bits in this register. Consider that
in the IE register shown below, the bit that corresponds to 1 activates
the interrupt, while the bit that corresponds to 0 disables the interrupt.

39
Embedded Systems and IoT

Figure 1.13: Interrupt Structure of 8051

Figure 1.14: IE register bit

40
Embedded Systems and IoT

Interrupt Priority Register (IP)

You may modify the interrupt priority levels using an IP register by


clearing or modifying the individual bit in the register, as shown in
the picture. The use of an IP register allows for this to be achieved.
Although one low-priority interrupt may legitimately interrupt
another high-priority interrupt, this does not mean that two such low-
priority interrupts may coexist. Without interrupt priority configured
into the microcontroller, the instructions will be executed in a
predetermined sequence: INT0, TF0, INT1, TF1, and SI. The failure to
set the interrupt priority causes this to happen.

Figure 1.15: Interrupt Priority Register (IP)

1.6.2 Interrupt programming in 8051

• Programming Timer Interrupts In microcontrollers, the time


register bits TF0 AND TF1 are responsible for generating the
Timer 1 and Timer 0 interrupts. The following are the
components of this timer interrupts programming using C
code:
o Choosing the setup of the TMOD register and the mode
in which it will function.
o Makes the IE registers and the timer bits that
correspond to them active in it.

41
Embedded Systems and IoT

o Select the mode of operation that is suitable and load


the starting values for TLx and THx after making your
selections.
o Before beginning the timer, make sure the run bit has
been set.
o Compose the code for the timer and ensure that the
value of TRx is reset at the conclusion of the timer's
subroutine.

• Let's have a look at the programming for the timer interrupt


using the Timer0 model in order to make the LED flash using
the interrupt method:

Programming for Interrupts Generated by External Hardware

As was mentioned before, the Microcontroller 8051 has two external


hardware interrupts that are referred to as INT0 and INT1. Pin 3.2
and pin 3.3 are responsible for enabling these interrupts. There are
two ways that it might be triggered: level or edge.

42
Embedded Systems and IoT

When using level triggering, a low signal at pin 3.2 activates the
interrupt. On the other hand, an edge triggered interrupt requires a
transition from high to low at pin 3.2. First, let's have a look at the
programmable features of the 8051 microcontroller, which are as
follows:

Programming for the Interrupts of Serial Communication When there


is a need to transmit or receive data, it is used in certain situations.
Because the same interrupt bit is utilized for both the Transfer
Interrupt (TI) flag and the Receiver Interrupt (RI) flag, the Interrupt
Service Routine (ISR) has to inspect both of these flags in order to
determine which interrupt is really occurring. The interrupt is caused
by the logical OR operation of the RI flag and the TI flag, and it may
be cleared by the program by itself. Consider the following stages
that are involved in the programming of serial communication
interrupts:-

• Enable serial interrupt by configuring the Interrupt Enable


register with the appropriate settings.
• Adjust the settings in the SCON register so that you may carry
out actions involving transmitting and receiving.
• Create a procedure for the interrupt that has the proper
function and write it down.

43
Embedded Systems and IoT

Let's have a look as the software that uses Serial Interrupt to transmit
the letter 'E' across a serial port at a baud rate of 9600:

i. void main()
ii. {
iii. TMOD = 0x20:
iv. TH1= 0xFD; // baud rate for 9600 bps
v. SCON = 0x50;
vi. TR1=1;
vii. EA=l;
viii. while(l);
ix. }
x. void ISR_Serial(void) interrupt 4
xi. {
xii. if(TI==l)
xiii. {
xiv. SBUF= ?E?;
xv. TI=0;
xvi. }
xvii. else
xviii. RI =0;
xix. }

44
Embedded Systems and IoT

UNIT II

EMBEDDED C PROGRAMMING

2.1 Programming Embedded System

The easiest way to explain what an embedded system is would be to


say that it is a system that is built to do a certain job and has both the
hardware and software necessary to do so. An embedded system is
best shown by a washing machine, which is present in many
households. Embedded systems consist of both hardware and
software. In a simple embedded system, the CPU is the most crucial
piece of hardware. A microprocessor, microcontroller, digital signal
processor (DSP), complex programmable logic device (CPLD), or field
programmable gate array (FPGA) may all serve as the processor, the
central component of an embedded system. A piece of hardware can
keep tabs on the world around it using its inputs and sensors, and
then control other devices using its outputs, all thanks to some
embedded software or a programme. At this stage, the embedded
system's software may need to make direct changes to the structure of
the embedded hardware (often the CPU), which includes its interrupt
handling, I/O ports, serial communications interface, timing, and
other internal components.

2.1.1 Embedded C Programming Language

In order to prepare ourselves for the embedded C programming


language and its underpinnings, we will first have a quick
introduction of the C programming language. C, which was
developed by Dennis Ritchie in the late 1960s and early 1970s, is the
programming language that is considered to be the most popular and
extensively used. If you are seeking for this language, you need not go any
further. The C programming language made it feasible to access memory at
a low level and achieve effective mapping to machine instructions. This was
accomplished via the use of a simple compiler, which is software that
provides the capability to translate programmes into machine code. The
programming language known as C has had a phenomenal boom in
popularity, which has resulted in its use in a broad range of applications,
ranging from embedded devices to supercomputers.

45
Embedded Systems and IoT

When creating embedded systems, many developers turn to the


Embedded C Programming Language, which goes by many names.
The C Programming Language has been enhanced with this addition.
There is no difference between the C programming language and its
embedded C programming language in terms of syntax or semantics.
The main function, datatype declaration, variable definition, loops,
functions, statements, and so on are all features that fall under this
category. Some of the features that have been added to the Standard
C programming language by Embedded C include I/O hardware
addressing, fixed point arithmetic operations, accessing address
spaces, and other extensions. Other capabilities have been added to
the ordinary C programming language via embedded C.

Difference between C and Embedded C

The main differences between C and Embedded C, two programming


languages that are quite similar, are the operating system and a
handful of extensions. There are many similarities between the two
ISO standards C and Embedded C, including almost identical syntax,
data types, and function names. To put it simply, Embedded C is just
Standard C with certain extensions. Addressing I/O, multiple
memory addressing, and fixed-point arithmetic are just a few of the
additional features it brings. Desktop applications written in C are
common, but applications built using microcontrollers are the domain
of the Embedded C programming language.

2.1.2 Basics of Embedded C Program

After a quick overview of embedded systems and programming


languages, we'll dive into the basics of embedded C programming. To
get things off, we'll go over the two most important parts of an
embedded C programme: keywords and data types.

Keywords in Embedded C

One example is a C compiler, which is a programme that converts C


code to Machine Code. However, the C compiler assigns unique
meaning to some terms called keywords.

46
Embedded Systems and IoT

Here are a few examples of keywords used by Keil's Cx51 Compiler, a


popular C compiler for microcontrollers based on the 8051
architecture:

• bit
• sbit
• sfr
• small
• large

2.1.3 Data Types in Embedded C

Data Types in the C programming language allow for the declaration


of variables. A large number of data types are available in the C
programming language. These include signed and unsigned integers,
char, float, double, and signed and unsigned char. Along with these,
Embedded C additionally includes a handful of other data types. You
can see some of the data types supported by Cx51 Compiler in the
table below.

Table 2.1: Data types in Cx51 Compiler

47
Embedded Systems and IoT

The following is a list of the additional data types that may be used in
Embedded C when using the Keil's Cx51 Compiler.

• bit
• sbit
• sfr
• sfr16

2.1.4 Basic Structure of an Embedded C Program

Next up in the Basics of Embedded C Programme series is the


Template of Embedded C Programme, which provides the
framework for the rest of the programme. Following this, you will
learn the fundamentals of embedded C programming. This will be
really helpful in shedding light on the development process of an
embedded C programme. An introduction to the basic structure of an
embedded C programme is given in the next section.

48
Embedded Systems and IoT

Before seeing a working example of the 8051 Microcontroller. First,


we shall examine the many parts that make up the structure shown
above.

2.1.5 Components of an Embedded C Program

Comments: Code comments are a kind of understandable language


created to make the code easier to understand for the reader. After
compilation is complete, the compiler does not handle them, and the
final code does not include any memory-intensive functions.
Commenting in Python may be done in two ways: first, as a single-
line remark (//), and second, as a multiline comment (/*....*/). One
way to tell the compiler to look at a certain file for symbols that aren't
specified elsewhere in the programme is via a Preprocessor Directive
in Embedded C. In C and Embedded C, the character # is often used
to indicate a Preprocessor Directive. The directives #include and
#define are examples of this kind. A microcontroller-specific header
file is often designated using the preprocessor directive in embedded
C programming. All SFRs and the bits contained within them are
provided in this header file.

• Global Variables: As their name indicates, global variables are


accessible across the whole of the program. This means that
you may use them no matter where you are in the code.
• Local Variables: In contrast to global variables, local variables
are only accessible inside the context of their respective
functions.
• Main Function: Each C and Embedded C program contains a
single primary function, which is the point at which the actual
execution of the program starts.

2.2 Memory And I/O Devices Interfacing

A microprocessor is coupled to a number of memory chips as well as


input/output devices. The CPU may be interfaced with memory
chips and I/O devices using the schematic design that is shown in the
accompanying image.

49
Embedded Systems and IoT

Figure 2.1: Memory and I/O Interfacing

2.2.1 Memory Interfacing

The address of a memory region or an input/output device is sent by


the microprocessor whenever one of the instructions is being carried
out by the computer. A decoding circuit will determine which
memory chip or I/O device corresponds to a given code and then
choose it. Memory needs certain signals in order to read from and
write to registers, and processors also need to send some signals in
order to read or write data. As part of the process of interfacing, you
will need to match the memory needs with the signals from the
microprocessor.

50
Embedded Systems and IoT

For this reason, the circuit that interfaces the two devices should be
constructed in such a manner that it accommodates the signal needs
of the memory while also accommodating the signals of the CPU.

2.2.2 I/O interfacing

As is well knowledge, a communication connection with the outside


world is established via the employment of screens and keyboards.
Therefore, it is essential that we establish a connection between the
microprocessor and the display as well as the keyboard. This process
is known as "I/O interfacing." When it comes to this kind of interface,
we make use of latches and buffers in order to connect the keyboards
and displays to the CPU. The fact that the microprocessor can only
carry out a single task is the most significant disadvantage of this
connecting method.

2.2.3 8279 Programmable Keyboard

A programmable keyboard interface device is provided by Intel in the


form of the 8279. Both the input and presentation of data are essential
components of microprocessor kits and systems that are based on
microprocessors. The 8279 instruction set was developed specifically
for use in 8-bit Intel microprocessors. The 8279 is divided into two
pieces, namely the display area and the keyboard section.

• The microprocessor takes input via the usage of the keyboard,


hence the purpose of the keyboard section is to provide an
interface for the keyboard. Additionally, it is able to interface
toggle switches or thumb switches.
• The display portion is responsible for driving any
alphanumeric displays or indication lights that may be present.
It has an unmediated connection to the bus that the CPU
uses.It is no longer necessary for the microprocessor to scan
the keyboard or update the display, therefore this frees up
some of its processing time.

The following are some essential characteristics:

• Simultaneous keyboard display operations


• Scanned sensor mode

51
Embedded Systems and IoT

2.2.4 8257 DMA Controller

The accumulator-based data transfer process from memory to fast


I/O devices or vice versa is a time-consuming operational method.
Direct Memory Access (DMA) is the preferred option in this specific
case. The Data Message Access (DMA) protocol allows for the direct
transmission of data. This transfer might happen either in the other
direction, from RAM to an I/O device, or vice versa. Using a data-
multiplexing adapter (DMA), the device requests the central
processing unit (CPU) to store its address, data, and control bus.
Because of this, the device may bypass the CPU and transfer data
straight to and from memory. Upon receipt of the HLDA signal from
the CPU, the DMA data transfer commences. Among the many
functions performed by a DMA are the following:

• At the outset, the device is required to transmit a DMA


request, also known as a DRQ, to the DMA controller in order
to begin the process of sending data between the device and
the memory.
• The DMA controller will first send a Hold request (HRQ) to
the CPU, after which it will wait for the CPU to deliver the
HLDA.
• When the CPU receives the HLDA signal, it then accepts the
HOLD request via the HLDA signal. This causes the CPU to
relinquish control over the bus.

52
Embedded Systems and IoT

• While the CPU is now in the HOLD state, the DMA controller
is responsible for managing the actions that take place on the
buses that connect the CPU, memory, and I/O devices.

2.2.5 Intel 8257

• A programmable Direct Memory Access (DMA) controller


may be found in the Intel 8257.
• It is a Direct Memory Access (DMA) controller that has four
channels and may be programmed.
• It comes in an integrated circuit package with 40 pins and
functions with a +5V power supply.
• It is capable of reading, writing, and checking the information
that it has received.
• The DMA address register and the byte count register are both
comprised of 16 bits, and they are both included in each
channel.
• It is possible to separately program each channel, and each
channel has the capacity to carry data of up to 64 kilobytes.
• It may function in two distinct modes: the Master mode and
the Slave mode.

2.2.6 8257 Architecture and Pin Description

The architecture of the Intel 8257 may be shown in the following


diagram:

The DMA protocol's acknowledgment lines are located between


DACK0 and DACK3. To notify an I/O device that it has been selected
for direct memory access (DMA) data transmission, the Intel 8257
uses one of these lines to transmit an acknowledge signal. The I/O
device receives a LOW acknowledgment signal on the line. The
address lines are A0 through A7. Bidirectionality is maintained by the
lines from A0 to A3. During its master mode operation, the 8257
generates a 16-bit memory address, which consists of four least
significant bits (LSBs) stored on these lines. When the slave mode is
enabled, these lines are all that are used as inputs. Which register is
read or programmed depends on which one of the inputs selects.

53
Embedded Systems and IoT

Each of the A4–A7 lines produces a tri-state output while the master
mode is active. The Intel 8257 generates a 16-bit memory address, and
these outputs (D0–D7) relay bits 4–7 of that address. Here are the data
lines. Here you may find the bidirectional boundaries of three states.
Whenever the controller is being programmed, the central processing
unit (CPU) will use these data lines to communicate with the DMA
address register, the byte count register, and the mode set register.

Figure 2.2: 8257 Architecture

• AEN: Activate the address latch.


• ADSTB: When a HIGH is asserted on this line, the 8MSBs of
the address that are being sent on D-bus are latched onto the
Intel 8212 that is attached for this purpose.
• CS: It uses a chip select system.

54
Embedded Systems and IoT

Figure 2.3: 8257 Pin Description

• (I/OR): I/O read out. It is a line that may go in both directions.


During the DMA write cycle, it is used to get access to data
from the I/O device when the mode is set to output.

55
Embedded Systems and IoT

• (I/OW): I/O notation. It is a line that may go in both directions.


During the DMA read cycle, it enables the flow of data to the
I/O device when the mode is set to output. The data is read
from the memory and then transmitted.

2.3 Programming Embedded Systems in C

2.3.1 Embedded C Programming with Keil Language

When it comes to the development of electrical devices, the most


common programming language used in the software industry is
embedded C. Embedded software is connected to each individual
processor that is used in electronic systems. The performance of
certain tasks by the CPU is greatly aided by the use of embedded C
programming. We make extensive use of a variety of technological
equipment in our day-to-day lives, including mobile phones, washing
machines, digital cameras, and many more. The functionality of each
of these devices is achieved via the use of microcontrollers that are
programmed using embedded C. The LED that is connected to Port0
of the microcontroller may be made to blink with the help of the
Embedded C code that is written in the block diagram that was just
shown. The following is a depiction of embedded system
programming in the form of a block diagram: When programming
embedded systems, the use of C code is recommended above the use
of other languages. As a result of the following factors:

• Easy to understand
• High Reliability
• Portability
• Scalability

56
Embedded Systems and IoT

Figure 2.4: Embedded C Programming

Embedded System Programming:

Let's have a look at the block diagram of the evolution of embedded C


programming:

Figure 2.5: Embedded C Programming development

One definition of a function is "a collection of statements that is used


for performing a specific task," while another definition of a
programming language is "a collection of one or more functions."
Grammatical principles and fundamental components are the
building blocks of any language. The programming language known
as C was developed for functions such as those involving variables,

57
Embedded Systems and IoT

character sets, data kinds, keywords, expressions, and so on that are


needed while building C programs. Embedded C programming
language is the name given to the expansion of the C programming
language. The embedded programming in C also has certain extra
capabilities, such as data types, keywords, and header files, among
other things, which are represented by

#include<microcontroller name.h>

2.3.2 Basic Embedded C Programming Steps

First, let's have a look at the block diagram that represents the
Embedded C Programming Steps:

Figure 2.6: Embedded C Programming Steps

There are many different kinds of operating systems, and


programming a microcontroller for each of them is different. While
there are several operating systems to choose from (Windows, Linux,
RTOS, etc.), RTOS has some advantages that make it a good choice for
developing embedded systems.

LED Blinking using 8051 Microcontroller

LEDs are a kind of semiconductor device that may be found in a wide


variety of electronic equipment, and its primary function is to serve as
an indicator. It is commonly used as an indication during tests to
assess the validity of the findings at various stages at various points
in the process. It may be acquired at a low cost and is readily
accessible in a wide range of forms, hues, and dimensions.
Additionally, LEDs are used in the construction of message display
boards, traffic control signal lights, and other such applications.

58
Embedded Systems and IoT

Consider the simulation of an LED flashing that was created using


Proteus Software and an 8051 microcontroller, which is depicted
below:-.3882

Figure 2.7: LED Blinking

In the Proteus-based simulation that was just shown, the 8051


microcontroller's PORT0 was used to interact with the LEDs. Let's
have a look at the embedded C program that's going to be responsible
for creating the LED output sequence:

1. 00000001
2. 00000010

59
Embedded Systems and IoT

3. 00000100.....
4. .... And so on up to 10000000.

1. #include<reg51.h>
2. void main()
3. {
4. unsigned int k;
5. unsigned char l,b;
6. while(1)
7. {
8. P0=0x01;
9. b=P0;
10. for(l-0;l<3000;l++);
11. for(k=0;k<8;k++)
12. {
13. b=b<<1;
14. P0=b;
15. }
16. }
17. }

Take into consideration the Embedded C Program, which, in order to


generate the LED output sequence, looks like this:

1. 00000001
2. 00000011
3. 00000111.....
4. .... And so on up to 11111111.

1. #include<reg51.h>
2. void main()
3. {
4. unsigned int i;
5. unsigned char j,b;
6. while(1)
7. {
8. P0=0x01;
9. b=P0;
10. for(j-0;j<3000;j++);
11. for(j=0;j<8;j++)

60
Embedded Systems and IoT

12. {
13. bb=b<<1;
14. b=0x01;
15. P0=b;
16. }
17. }
18. }

Displaying Number on 7-Segment Display using 8051 Microcontroller

The 7-Segment display is a kind of electronic display that may be


used to show alphanumeric characters. It is used in a variety of
systems for the purpose of information presentation.

Figure 2.8: Displaying Number on 7-Segment Display

Built using eight sequentially connected LEDs, it can display the


numerals 0 to 9 when certain combinations of LEDs are switched on.
The screen can only show a single number at a time. Consider the
following method of operation of the Proteus software-based
simulation of displaying numbers on a 7-segment display using an
8051 microcontroller:

Consider the following as the software for showing the number range
'0 to F' on a seven-segment display:

61
Embedded Systems and IoT

62
Embedded Systems and IoT

63
Embedded Systems and IoT

2.4 Real-Time Operating System (RTOS)

A real-time operating system, or RTOS, is a piece of software that was


developed specifically to handle the time of a central processing unit
(CPU) in an effective manner. This is particularly important for
embedded systems, which often operate under strict time constraints.
The speed with which an operating system like Windows responds to
events from the outside world is the primary distinction between it
and the real-time operating systems (RTOS) that are often used in
embedded devices. An average operating system offers a non-
deterministic reaction to events and makes no guarantees about when
those events will be handled, despite the fact that it makes an effort to
remain responsive. It is more critical to ensure that the user has a
positive experience with the operating system than it is to do the
underlying duties. On the other hand, the purpose of a real-time
operating system (RTOS) is to achieve a quicker and more predictable
response. The properties of an embedded real-time operating system
are going to seem quite similar to software developers who are
accustomed to working with operating systems like Windows or
Linux. They are developed to function on computer systems that have
a limited amount of memory and to continue their operations forever
without requiring a reboot. It is possible for an RTOS to be slower at
large tasks than other operating systems as compared to those that
are intended to react rapidly to events and function well under high
loads.

2.4.1 RTOS scheduling

An RTOS is valued for how rapidly it can react, and the most
important component of this is the advanced scheduling
algorithm.The time-criticality of embedded systems may range from
soft-real time control systems like those found in washing machines
to hard-real time safety systems like those found in airplanes. In
circumstances such as the latter, the essential demand to satisfy real-
time requirements can only be made if the behavior of the OS
scheduler can be properly anticipated. This is necessary in order to
meet the criteria. There are a lot of operating systems out there that
offer the idea that they can run numerous applications at the same
time, but this multi-tasking is mostly an illusion.

64
Embedded Systems and IoT

One and only one execution thread is capable of being operated by a


single processor core at any one moment. The scheduler of an
operating system makes the decision as to which application or
thread will execute at what time. It gives the appearance of being able
to do many tasks at once by swiftly switching between different
threads. Although an RTOS is often designed to cater to a relatively
specific group of applications, the adaptability of its scheduler makes
it possible to take a more general approach to the prioritization of
processes. A real-time operating system (RTOS) scheduler ought to
provide minimum interrupt delay and little thread switching
overhead. Because of this, a real-time operating system (RTOS) is a
very useful component for time-sensitive embedded devices.

The use of RTOS in embedded designs

Many embedded programmers avoid adopting real-time operating


systems (RTOS) because they believe that doing so would add an
excessive amount of complexity to their application or because they
see it as uncharted terrain. In order to carry out its functions, an RTOS
normally needs anywhere from 0 to 5 percent of the resources made
available by the CPU. Even while there will always be some resource
penalties, an RTOS may be able to make up for them in other areas,
such as simpler determinism, simplicity of use via HW abstraction,
decreased development time, and easier debugging. If you use an
RTOS, you will be able to perform numerous jobs simultaneously,
bringing in the fundamental connection, privacy, and security
features as and when you need them. You are able to develop a
solution that is optimized to meet the particular needs of your project
if you use an RTOS.

2.4.2 Zephyr RTOS

There is a wide variety of RTOS software available nowadays. A


significant number of software engineers in Nordic countries are
concentrating on developing low-power embedded systems. If this
describes you, we recommend that you have a look at Zephyr, which
is an excellent option for connection solutions that must adhere to
stringently low-power standards. Because the modular Zephyr RTOS
is compatible with a variety of architectures, developers have the

65
Embedded Systems and IoT

ability to simply build a solution to match the specific requirements


of their projects. Zephyr is an open-source platform in every sense of
the word. In contrast to other real-time operating systems (RTOS),
such as Zephyr, which is managed by the Linux Foundation and is
consequently an open source collaborative effort, other RTOS that
purport to be open source are in fact driven by private enterprises. In
the committees and working groups, when Nordic representatives
are present, they are, however, co-located with representatives from a
broad variety of other enterprises, both big and small.

2.5 Multiple Tasks and Processes

2.5.1 OS and RTOS

One OS that provides the features needed to meet real-time


requirements is the Real-Time Operating System, or RTOS for short.
With the use of real-time algorithms, it also allocates resources while
considering real-time constraints. In contrast, the resource allocation
process of the general operating system (OS) takes factors like equity
into account. Not only that, but it doesn't take time into account when
assigning processes, which greatly increases the likelihood that they
will miss their due dates.

2.5.2 Task and process

A single iteration of a computer program is referred to as a process.


When one and the same process are carried out at various periods, we
are dealing with two distinct processes. Every process is in its own
unique state, and every state has its own unique memory and
registers. Memory management units in many different operating
systems place each every process in its own distinct address space.
Processes are known as threads, and they all use the same address
space. On the other hand, a job is made up of several processes or
threads, each of which has its own address space.

2.5.3 Release time and deadline

Timing constraints could be necessary for some procedures,


depending on the application. A scheduling policy that specifies how
processes are picked to move from the ready state to the running state
after having been promoted from the ready state. It is necessary for it

66
Embedded Systems and IoT

to establish the timing constraints that it utilizes regardless of whether


or not the timetable is accurate. The release time and the deadline are the
two primary components that make up the timing requirements.

• Aperiodic and periodic: The amount of time that elapses


between each iteration of a process is referred to as the period.
The arrival timings and completion dates of periodic
procedures are strictly adhered to. Aperiodic processes are
characterized by erratic arrival timings and either flexible or
rigid deadline requirements. An event, such as the arrival of
data from the outside world or the completion of computations by
another process, might trigger the beginning of an aperiodic process.
• Process Rate: It is the opposite of the time that it belongs to.
• Release time: It is at this point in time that the procedure will
become ready to be carried out. An incident serves as the
catalyst that kicks off the process initially. The length of time
before the next aperiodic release begins to be calculated
beginning with that event.

Within the framework of the periodic procedure, the time of release


will be decided in two distinct ways. To keep things simple, the
procedure will be finished at the beginning of the time period. In
more advanced computer systems, the release time will be
determined as soon as the data are received. The "Deadline" refers to
the period at which the procedure has to be completed. When it
comes to a procedure that runs on a periodic basis, the deadline is
determined by the release time. In the case of processes that repeat on
a periodic basis, it may take place at a point in the cycle other than the
cycle's conclusion. Figure provides an illustration of the release time
and the deadline. There will be two distinct patterns of deadline
frequency, namely periodic and aperiodic. The following is a list of
the three different kinds of deadlines:

• Hard: The inability to achieve a deadline will result in the


breakdown of the system.
• Soft: The quality of the answer is diminished when deadlines
are not met.
• Firm: It is pointless to respond late, yet it is acceptable to
tolerate occasional late answers.

67
Embedded Systems and IoT

Figure 2.9: Release times and deadline

Timing requirements on processes

A multirate system is one in which each individual process operates


at its own unique rate. The situation in which the start interval is the
same as the period occurs in periodic processes the vast majority of
the time. On the other hand, because the execution of several
instances of the process might overlap with one another, the initiation
interval can be less than the period. Figure depicts a series of
processes that have a high rate of initiation in their sequence. In order
to differentiate the starting times of the several iterations of the
program P1 that have been executed, subscripts have Been added.

Figure 2.10: Sequence of process with high initiation rate

68
Embedded Systems and IoT

In this particular example, there are four separate instances of the


processes that are each assigned to one of four distinct processors.
The initiation interval for each of these processors is equal to one
fourth of the period. The first central processing unit will now handle
the fifth iteration of the procedure. Even in the case of systems with a
single CPU, there is still a potential that the process start rate will be
lower than the period. If the total time required to complete the
procedure is much less than the period, it may be possible to start the
several instances of a program at somewhat different times.

2.5.4 Process State and Scheduling

The procedure will take place in only one of the states. There is a
ready state, an executing state, and a waiting state.

• Ready: When a process enters a new time period and/or when


it has received all of the necessary data, it transitions into the
ready state.
• Waiting: When a process requires data that it has not yet
received, or when it has done all of its work for the current
time period, it enters the waiting state and waits for further
instructions.
• Executing: Only after a process has finished preparing all of its
data to execute will it be able to transition into the executing
stage. Figure depicts the current condition of the procedure.

Figure 2.11: Process state diagram

69
Embedded Systems and IoT

Each each process will be equipped with its very own process control
block (PCB). The printed circuit board (PCB) is a data structure that
stores the information with which the operating system (OS) manages
the current state of the operation. The printed circuit board (PCB)
may be found in the memory section of the kernel. It is made up of
the details on the current stage of the procedure. The primary
constituents of a PCB are as follows:

• Process ID
• Process priority
• Parent process
• Child process and address to the PCB of the next process
which will run.

Task

In an operating system, a task is analogous to a process or thread. The


word "process" is referred to as a "task" in RTOS. It is composed of
programs that may be executed (codes), the state of which is
managed by the operating system. The task control block, abbreviated
TCB, will be present in each individual job. The information about the
data structure that the operating system uses to regulate the task state
will be stored in the TCB. It is possible that the job will be in any one
of these states: idle, ready, running, blocked, or completed. The
following is a list of the states:

• Idle state
• Ready State
• Running state
• Blocked (waiting) state
• Delayed for a preset period

Idle state

job has been formed, and memory has been allocated to the structure
of the task; but, if the task is not ready, the kernel will not schedule it.

Ready State

The newly formed job is complete and may be scheduled by the


kernel; however, it is not currently executing because another task

70
Embedded Systems and IoT

with a higher priority is already scheduled to execute and is using all


of the available system resources at this time. At this point in time,
the run state entails executing the programs and retrieving the system
resources. It will continue to run until it requires some IPC (input) or
until it has to wait for an event or until it is pre-empted by another job
with a higher priority than this one.

Figure 2.12: Task State

Execution of task codes is halted during the blocked state when the
necessary parameters have been saved into the context of the task. In
order for it to be allowed to execute after blocking, it requires some
IPC, which stands for input, or it needs to wait for an event, or it has
to wait for a job with a higher priority to complete its block.

Deleted Task

Memory that was allocated to the job that was created has been
removed. Memory is unlocked as a result. It will be necessary to
recreate the task. Figure 2.13 depicts the many components that make
up a task control block. The Task Control Block (TCB) is made up of a
Task ID, which is an integer that ranges from 0 to 255. Within the
context of Tasks, the Program Counter (PC) is the variable that stores
the address of the next instruction that will be carried out.

71
Embedded Systems and IoT

In addition, the stack pointer, the central processing unit (CPU), and
the processor status register are all accessible inside the tasks context.
The job priority in TCB is a number that ranges from 0 to 255 and is
represented by bytes. This number determines the priority of a
particular job. Task priority is also used to preserve the relationship
between parent and child tasks.

Figure 2.13: Task control block

The allotted program memory provides the addressing information


for the tasks' codes in both the primary (physical) memory and the
secondary (virtual) memory.

• Allocated data address chunks that were relevant to the job.


• Addresses allotted to the task heap, which stores data created
while the application is being executed
• Addresses that have been allotted for the register-save region
of the CPU; this area serves as a task context that is
represented by the CPU registers; these registers include the
program counter and the stack pointer. addresses on the task
stack that have been allocated for the functions that are called
while the process is being executed.
• Addresses that have been allotted for the register-save region
of the CPU; this area serves as a task context that is
represented by the CPU registers; these registers include the
program counter and the stack pointer.

72
Embedded Systems and IoT

• Addresses that have been allocated from the CPU register


saving area as a task context. Each task operates autonomously
and assumes control of the CPU when it is scheduled to do so
by the operating system's scheduler. The tasks are controlled
and carried out by the scheduler.

2.5.5 Task Characteristics for a single CPU in a system

Task is its own self-contained entity, and it is unable to call any other
tasks. A TCB is used to identify each individual task. In the same way
that each function has a name, each job also has its own unique
identifier. If the ID, also known as the task ID, is between 0 and 255,
then it is a byte. ID does double duty as an index to the job. A priority
criterion may be assigned to each individual job. A byte is used to
indicate the priority if it falls between 0 and 255 on the scale. The OS
Scheduler is responsible for context switching between the numerous
activities that are being worked on, which is how multitasking
operations are completed. Each job has to either have a re-entrant
procedure or a mechanism to address the issue of shared data in
order to be considered complete. If it is possible to call a function
while the process is already running, then the function is said to be
re-entrant. The following conditions need to be met for a function to
be considered entrant:

• None of the parameters are pointers, and all of the arguments


successfully transmit their values.
• Whenever a function call is begun, that function should not
operate on any variable that is declared outside of the function,
that is used by an interrupt service routine, or that is a global
variable. This is because an operation that is not atomic should
not be operated on by that function.
• A variable should be supplied into the function via reference
as an argument, and the function shouldn't call any other
functions that aren't reentrant in and of itself.

2.6 RTOS Task Context Switching

Real-time operating systems, often known as RTOS, are equipped


with scheduling algorithms that enable them to conduct tasks while
giving the appearance of multitasking behavior.

73
Embedded Systems and IoT

This is accomplished by endowing the real-time operating system


(RTOS) with the ability to pause the execution of a job while
simultaneously beginning work on another. The execution of the
work that was halted should be resumed at some point in the future.
In the event that this happens, the microprocessor has to be reset to
the same condition it was in the previous time the stopped job was
being carried out. This is accomplished via a process referred to as
context shift.

During the execution process, each task consumes a unique collection


of resources. These include the registers of the central processing unit,
the flags that indicate the condition of the system, and access to
memory (heap, stack, etc.). We refer to all of these resources as a task
state, which is also known as a task execution context. The act of
preserving the current state of the task (with the goal that it would be
restored at a later point in time) and then swapping that state with
another state of the job that has already been saved is known as
context switching. The transfer of contexts between tasks ensures that
each process considers the CPU to be its own. This simulates the
behaviour of true multitasking, in which each activity should have its
own dedicated processing unit (CPU).

2.6.1 Context Switching Basics

Real-time operating systems aren't the only ones that make use of the
context switching method. When an exception occurs and a service
routine has to be carried out, every microprocessor makes use of a
context switching mechanism of some kind. The handling of
exception context switching is often split between the hardware
(certain registers are stored automatically), which is present in the
majority of contemporary CPU architectures, and the code that is
created by the compiler.

The ability to transition between tasks and their contexts while using
real-time operating systems is built into their source code. Despite the
fact that it is managed by software, context switching is reliant on the
hardware. This is because the resources that are required may vary
from one CPU to another. This indicates that the code for task context
switching will need to be adapted for each different architecture of
CPU.

74
Embedded Systems and IoT

2.6.2 Implementation Details

Now that we have that out of the way, let's examine the several ways
that task context switching may be accomplished. To get things
rolling, we need to ensure that each job has its own individual private
stack. This private stack will, in addition to serving as a typical
application stack, be used to record the status of the task (including
CPU registers, the return address, the value of the stack pointer, and
so on). We often only use a single stack for the whole of the program
when it comes to the most fundamental or "bare-bone" applications.
The issue that naturally arises is how we may construct separate
stacks for each activity. Changing the value of the stack pointer
register is the method by which this may be achieved. The stack is just
a part of the volatile memory (RAM) that we "reserve" for stack
action. RAM is short for random access memory. The stack pointer is
now pointing in the direction of this section's position. The
fundamental idea is that each job will have a dedicated portion of
memory for its stack. This section of memory will be specified. When
the task is initiated, the start address of this stack will be saved in a
variable so that it may be loaded. This will allow the stack to be used.

2.6.3 Memory Allocation

Objects in the RTOS kernel, such as tasks, semaphores, and so on,


may either be allocated statically (during compilation), or dynamically
(during runtime). Typically, the RTOS will offer a variety of various
strategies for job dynamic allocation. Take, for instance:

• Committing the space to the activity only the once, and then
never releasing it
• The space on the heap that was allotted to a job is released
after that task has finished its activity.

The complexity of the application and the limitations imposed by the


embedded system both play a role in determining which dynamic
allocation technique is the most appropriate. Now let's have a look at
how much memory is needed for an RTOS job. We will not be
concentrating on any one particular distribution of the RTOS, and
instead will make an effort to address topics that are shared by all of
them.

75
Embedded Systems and IoT

Each new job that is formed need to contain a stack memory area in
addition to a task control information memory area. The left-hand
side of Fig. 2.14 illustrates this point.

Figure 2.14: RTOS task memory structure and placement in heap


memory

The size of the task control information area is fixed, and it may
contain the following:

• the name of the job, which is a reference to the C code that


actually implements the task.
• information for debugging
• the amount of space used by the task's stack
• address of the item at the top of the stack pointer
• the order of the tasks

The heap memory is used to store each and every job.

2.6.4 Context Switching Flow

As a last stage, let's examine a context switching flow by looking at an


example that involves two different tasks: Task 1 and Task 2. While
Task 1 is being worked on right now, Task 2, which has a greater
priority, has just been ready to be put into action.

76
Embedded Systems and IoT

Because of this circumstance, a shift in perspective is going to be


necessary, and the procedures required are as follows:

• Task 1 is now being carried out. An RTOS tick exception has


been produced. The device will automatically store certain
registers into the stack of the job that is currently being
performed. This is dependent on the architecture of the CPU.
The registers R0-R3, R12, LR(R14), return address, and xPSR
are all automatically saved by the ARM Cortex-M. Any extra
registers that are considered a part of the current task state are
saved by an RTOS handler function for the tick exception (see Fig.
2.15 for further information). Registers R4–R11 and R14 should be
saved by this handler function for ARM Cortex-M processors.
• The value of the stack pointer, which is the address of the last
register that was put onto the stack, is kept in the section of the
task control that is dedicated to information storage. The
handler determines whether or whether there is a job with a
higher priority that is already waiting to be executed; in our
example, this is job 2. The value of the stack pointer that is
stored in the information control memory region of Task 2 is
put into the register that handles the stack pointer for the CPU.
• Although we are still in the RTOS handler method for the tick
exception, the stack pointer has been moved such that it now
points to the very last element in the space reserved for the
Task 2 stack. This handler will now restore the context that it
had previously saved upon entrance (step 4) onto the stack. It
is important to note that the context for Task 1 was preserved
when the exception was entered, however at this time we are
restoring the context for Task 2.
• When the user exits the handler, any data that was saved
during step 3 of the flow will be immediately restored by the
hardware. Take note once again that the hardware is now
working to restore the context for Task 2, since step 6 involves
loading the stack pointer with the stack address for Task 2.
• At this point, we have completed the procedure for handling
exceptions. The program will continue to run normally, but
normal execution will not resume on the task that was paused
(Task 1). Instead, the program will run on Task 2. The change
of context has been finished!

77
Embedded Systems and IoT

Figure 2.15: Stack content before and after saving of task state
(context)

The modification of the stack pointer value to achieve a distinct stack


region for each job is directly tied to all of the "magic" that occurs
while conducting a task context transition.

2.7 Priority Based Scheduling Policies

2.7.1 Earliest-Deadline-First Scheduling

One of the most well-known algorithms for real time processing is


called Earliest Deadline First, or EDF for short. It is the most efficient
dynamic algorithm possible. The priority of a job might change as it is
being carried out according to algorithms that use dynamic priority.
When a valid schedule is present, it generates a valid schedule. The
EDF method is a preemptive scheduling technique that moves on to
the next task the process that has the earliest deadline for completion.
The system will preempt the currently operating process and send the
approaching process to completion if the arriving process has a
deadline that is sooner than the currently running process. A greater
priority is given to a work that has a shorter time limit. It completes a
task that has the earliest deadline possible. It is not possible to
schedule tasks using a rate monotonic method. EDF is the most
effective scheduling method since it does not leave the processor idle
at any particular periods. The maximum allowable level of process
utilization is 100%.

78
Embedded Systems and IoT

When adding a new task to the ready queue, give precedence to the
one that is closest to complete in the allocated time. If the running
task was not prioritised at the last sorting, the system will take action
to move it to the head of the queue. If the two tasks have identical
absolute deadlines, choose one at random (the arbitrator may decide
how to break a tie). Since it changes for different tasks within the
same job, we say that the priority is dynamic. Another possible use
case for EDF is aperiodic task sets. As a result of its efficiency, EDF
will always aim to minimise maximum latency.

Alternative approaches are required due to the high number of real-


time systems that do not have hardware preemption. Scheduling
theory states that real-time systems consist of collections of real-time
tasks, with each work containing either an endless or limited stream
of activities. Several methods exist for organising the list of tasks,
including, but not limited to, algorithms that use either fixed or
dynamic priority.

Any real-time system has to be able to guarantee that all jobs and
tasks will complete their executions before their due dates for it to
work. When people can do what needs doing, we say that the task is
schedulable. To meet the schedulability requirement, the total
utilisation of the task set can't be more than one. To begin, the earliest
potential start time for the deadline's implementation: Is it really true
that EDF scheduling cannot be implemented?

Task Arrival Duration Deadline

T1 0 10 33

T2 4 3 28

T3 5 10 29

Table 2.2: EDF scheduling

79
Embedded Systems and IoT

Figure 2.17: Earliest-Deadline-First Scheduling

Problems for implementations

• Since the absolute due dates are different for each new
iteration of the job, the priority needs to be modified each time
the work goes back to the ready queue.
• Even more importantly, absolute deadlines are always being
pushed back, so how can we assign a fixed priority value to a
date that is perpetually being pushed back?
• The most essential point is that it is not feasible to determine
absolute deadlines a-priori.

2.7.2 EDF properties

• EDF is the best option available in terms of its practicability


(also known as its schedulability).
• EDF achieves the best results possible in terms of reducing the
greatest amount of lateness.

2.7.3 Rate Monotonic Scheduling

Rate The method known as Monotonic Priority Assignment (RM) is a


kind of round robin scheduling that uses a static priority.

80
Embedded Systems and IoT

In this particular method, the priority of a process is raised if there is


a rise in the frequency with which it must be scheduled. The task with
the shortest remaining duration will be given the greatest priority.
Priorities are determined for each activity before they are carried out,
and these determinations do not shift throughout time. RM
scheduling is preemptive, which means that a job may have its
execution skipped in favor of another task that has a higher priority.
The priority that is allocated in RM algorithms is not changed at any
point in time while the system is actively being used. RM distributes
priorities in a straightforward manner that is simply in line with its
periods. This implies that the priority is greater when the period is
shorter, which means that the activation rate is higher. In other
words, RM is a method for scheduling periodic task sets. If a process
with a lower priority is already running and another process with a
higher priority becomes available to execute, the higher priority
process will take precedence over the lower priority one. On the basis
of the inverse of the period of each periodic job, its priority is
determined.

• The priority level is increased in proportion to the duration of


the time.
• The duration of the term has a negative impact on the priority.

The following presumptions were used in the validation of the


algorithm:

• Recurring events must be completed.


• Each of the tasks has to be completed before moving on to the
next request.
• None of the jobs are reliant on one another.
• The amount of time needed to complete each job request is
always the same.
• In the system, there are no necessary deadlines for any tasks
that are not periodic.

When it comes to scheduling periodic tasks, where the due dates of


the jobs coincide with their periods, RMS is the most effective
scheduling algorithm among those that use fixed priorities.

81
Embedded Systems and IoT

2.7.4 Priority Inversion

An example of priority inversion is when a task with a lower priority


is allowed to run while a work with a higher priority that is ready
and waiting. Consider the following three tasks in descending order
of priority: T1, T2, and T3. T1 and T3 both have access to the same
data or resource, but T2 does not interact with any of the other two
tasks in any way.

Figure 2.18: Priority Inversion Method

The beginning of Task T3 is indicated by the time t0, and the


semaphore is locked in at the time tv. Tl comes at time t2, and
interrupts T3 when it is in the middle of its crucial part. After some
time has passed, Tl makes a request to access the shared resource by
trying to lock s. However, this request is denied since T3 is already
using the resource. As a result, the code that is being carried out at
time t3 is still inside its vital part. Next, when T2 comes at time t4, it
has a higher priority than T3 and does not interact with either Tl or
T3. This causes T2 to take precedence over T3.

Figure 2.19: Priority Inversion Example

82
Embedded Systems and IoT

It is no longer completely reliant on the duration of the crucial section


that is being carried out by T3, due to the fact that the blocking time
of Tl has increased as a result of the execution time of T2. It's possible
for priorities to switch places when different activities share the same
resources. Inversion of priorities is unavoidable; yet, there are
circumstances in which the degree of priority inversion may be
excessive. The answer is rather simple:

• Make it impossible to skip over important parts of the story.


• Give crucial parts the greatest possible execution priority
inside the job that might benefit from it.

The answer to the issue is quite straightforward; if a lower priority


job blocks a process with a higher priority, then the lower priority
activity will inherit the priority of the task with the higher priority; as
a result, any task with a medium priority will be unable to preempt it.
Timing irregularities As we have seen, competition for available
resources may result in temporal irregularities owing to priority
inversion and deadlock. These anomalies may have arbitrary
durations if they are not managed, and they can severely disturb the
timing of the system. It is impossible to eradicate these irregularities,
however there are numerous methods that can regulate them:

• Priority inheritance protocol


• Basic priority ceiling protocol
• Stack-based priority ceiling protocol

2.7.5 Wait for graph

A wait-for graph is a kind of graph that is used to describe the


dynamic blocking connections that exist between processes. Every
task that is dependent on a certain resource will have its own vertex
in the wait-for graph of a system. This vertex will be labeled with the
job's name. If x units of a resource are assigned to a task at any given
moment, the wait-for graph will have an ownership edge with the
label x connecting a resource vertex to a job vertex. This edge will be
connected to the job vertex via a resource vertex. The wait-for graph
is a model that may be used to simulate resource contention.
Modeling has been done on every single serially reusable resource.

83
Embedded Systems and IoT

Every task that needs a resource is represented in the model by a


vertex that has an arrow pointing in the direction of the resource.

Figure 2.20: Wait for Graph

Every task that has a resource is denoted by a vertex in the graph that
faces away from the resource and in the direction of the job. In a wait-
for graph, deadlock is indicated by the presence of a cyclic route. J3
has successfully locked the solitary unit of resource R, and J2 is now
in the process of doing so. In order to avoid a deadlock, your system
must have a minimum of two available resources.

84
Embedded Systems and IoT

UNIT III

IoT AND ARDUINO PROGRAMMING

3.1 Introduction to the Concept of IoT Devices

3.1.1 IoT

The vast majority of the billions of physical objects or "things"


that have Internet connections are collectively referred to as the
Internet of Things (IoT). All of these "things" collect information
and share it with other systems and devices online. Although
the concept of the Internet of Things (IoT) has been present since
the 1990s, its usefulness has grown due to advancements in
several technologies, such as:

• Availability of sensors that are both inexpensive and


dependable
• An increase in the number of cloud computing platforms
that are available
• Recent developments in artificial intelligence and machine
learning technologies.

Devices that are connected to the internet might vary from


simple kitchen appliances found in most homes to complex
machinery used in factories. Each component of the internet of
things have a Unique Identifier (UID), and they are also capable
of transmitting data independently of human intervention.

3.1.2 Types of IoT

The networking, communication, and connection protocols are


heavily determined by the particular Internet of Things
application that is being used.

85
Embedded Systems and IoT

There are many various kinds of Internet of Things apps


dependent on how they are used, just as there are many
different kinds of Internet of Things devices. The following are
some of the most widespread ones:

• Consumer IoT - To be used mostly in ordinary situations.


Examples include voice-activated assistants, household
appliances, and light fixtures.
• Commercial IoT - Mainly employed in the medical and
transportation sectors of the economy. Examples include
monitoring systems and intelligent pacemakers.
• Military Things (IoMT) - Utilized largely for the purpose of
implementing Internet of Things technology in the realm of
military operations. Examples include human-wearable
biometrics for the battlefield and surveillance robots.
• Industrial Internet of Things (IIoT) - Applications in
manufacturing and the energy industry are two primary
examples of typical industrial uses for this product.
Examples include digital control systems, intelligent
agriculture, and big data in industry.
• Infrastructure IoT - Utilized primarily for the purpose of
establishing connection in smart cities. Examples include
sensors and management systems for the infrastructure.

The Internet of Things has made it feasible for the digital world
and the real world to interact with one another and work
together. It enables enterprises to automate and simplify the
day-to-day processes they do, which provides them with a
wide range of advantages. Companies are capitalizing on the
enormous economic benefits that the Internet of Things (IoT)
may provide as it continues its exponential growth year after
year.

86
Embedded Systems and IoT

Benefits of IoT:

• In order to develop new ways of doing business and sources


of income
• To enhance business choices by gaining data-driven insights
from Internet of Things (IoT) data
• To improve the overall experience of the consumer

3.1.3 IoT Devices

Hardware devices, such as sensors, gadgets, appliances, and


other machinery, are referred to as IoT devices. These devices
gather and share data through the internet. They may be
incorporated into other Internet of Things devices and are pre-
programmed for certain purposes. For instance, an Internet of
Things (IoT) gadget installed in your vehicle may monitor the
traffic conditions up ahead and immediately notify the person
you are supposed to meet that you are going to be late. The
many IoT devices may have different functions, but they're
really very similar in many ways. To start, IoT devices are
physical objects that can detect and respond to things
happening in the physical environment. They typically have an
integrated CPU, network adapter, and firmware in addition to
a link to a Dynamic Host Configuration Protocol server. It
needs an IP address so it can communicate with other devices
on the network. Most Internet of Things devices are managed
and set up with the help of software programmes. Consider a
programme that lets you control the lights in your home using
your smartphone. There is no longer a need to install
additional programmes since many gadgets come with built-in
web servers. For example, the lights will automatically switch
on as soon as you enter a room.

87
Embedded Systems and IoT

3.1.4 Examples of IoT Devices

• Home Security: One major factor propelling the


development of smart and secure homes is the Internet
of Things. In order to provide security at all times, the
Internet of Things (IoT) links a large number of devices,
including sensors, lights, alarms, and cameras, which can
be controlled from a smartphone.
• Activity Trackers: Alerts and peace of mind are both
provided by intelligent home security cameras. The term
"activity tracker" refers to sensor-based devices that are
able to monitor and communicate vital health indicators
in real time. You are able to monitor and control your
oxygen levels, as well as your hunger, physical activity,
and blood pressure.
• Industrial Security and Safety: It is possible to monitor
limited regions with the use of cameras, sensors, and
detecting systems that are enabled by the Internet of
Things. They are able to detect pressure buildups as well
as minor leaks of potentially harmful substances and
rectify them before they become major issues.
• Augmented Reality Glasses: When worn, computer-
enabled Augmented Reality (AR) glasses may
superimpose digital content, such 3D animations and
movies, over a user's perspective of the physical
environment. Accessing Internet applications will be
made easier with the help of the information shown
within the glasses.
• Motion Detection: Motion sensors are able to detect
vibrations in huge structures such as buildings, bridges, dams,
and other similar structures. These gadgets have the ability to
detect irregularities and disturbances in the structures that have the
potential to result in catastrophic collapses.

88
Embedded Systems and IoT

3.2 IoT Devices Versus Computers

Internet of Things (IoT):

Everything from cars to buildings and everything in between


that has electronics, software, sensors, and a network
connection makes up what is known as the Internet of Things
(IoT). Because of this, these things may communicate with one
another and exchange information. Things like buildings,
automobiles, and vehicles fall within this category.

The Internet of Things has made life simpler for humans.


Internet of Things (IoT) gadgets like smart houses and smart
automobiles have made life a lot more pleasant for humans.
Devices that are connected to the Internet of Things are
becoming commonplace in our lives.

Computers:

A computer is a piece of hardware that also has software


installed inside of it. The majority of the labor, including
arithmetic, games, web browsers, word processors, e-mails,
and so on, is completed by the computer. The primary purpose
of a computer is to do computations and to execute the
programs that have been stored on it. After receiving data from
the computer in the form of input, it first computes and
analyzes that data before producing output.

Figure 3.1: Function of Computer

89
Embedded Systems and IoT

Overview of IoT Vs Computers:

One of the most significant distinctions that can be made


between Internet of Things (IoT) devices and computers is that
the primary purpose of IoT devices is not to compute (or to act
as a computer), while the primary purpose of computers is to
compute functions and to execute programs. However, with
IoT devices, that is not the primary function that it serves;
rather, it serves some other purpose in addition to that. As an
example, the job of Internet of Things devices is not to calculate
anti-lock braking or to perform fuel injection. Instead, their
primary function from the perspective of a user is to drive and
to transport them from one location to another, and the
computer's role is simply to assist in carrying out this duty.
Take, for instance: The primary purpose of the vehicle is not to
do computations, such as those involved in anti-lock braking or
fuel injection. When seen from the perspective of a user, their
primary purpose is to drive, or to transport you from one
location to another. However, if we install software inside of it,
then that program will be able to identify the amount of
gasoline remaining.

3.3 IoT Configurations

3.3.1 Device configuration

You may take command of a device using Cloud IoT Core by


simply emailing it the configuration for the device. An arbitrary
user-defined blob of data is what makes up a device
configuration, and it is sent from Cloud IoT Core to a device. It
is possible for the data to be unstructured as well.

90
Embedded Systems and IoT

Difference between IoT devices and Computers:

IOT Devices Computers

Internet of Things devices Computers are considered


are specialized hardware. devices with a generic function.

IoT devices are only


There are a great number of
capable of doing the one
activities that may be
specific function that they
performed by computers.
were built for.

The hardware and software


The hardware and
that is preinstalled in the
software that are pre-
computers have been
installed in IoT devices
optimized to perform a wide
have been optimized for
variety of functions, including
the specific activity at
calculating, playing games and
hand.
music, and so on.

Due to the fact that


Internet of Things devices
When compared to an IoT
are purpose-built to do
device, a computer might be
certain tasks, they are
more costly and take longer to
often more efficient than
do a certain activity.
computers in performing
those tasks.

Examples include the


Examples include desktop
iPod, Alexa, and many
computers, portable laptop
forms of smart
computers, and so on.
technology.

91
Embedded Systems and IoT

Furthermore, it might be in any format, such as text, serialised


protocol buffers, JSON, or random binary data. Every device's
configuration is saved in the cloud using Cloud IoT Core. The
largest allowed size for configuration data is 64 kilobytes. For
optimal performance, a device's setup shouldn't revolve on a
set of instructions but around the values or outcomes that
should be attained.

It will be hard to restore a device's state (without running every


sequence of instructions since the device was originally started)
if you issue commands, since interim configuration versions
may lead to conflicts. It will be possible to restore a device's
status if you do not provide instructions. By prioritising values
and outcomes in the settings, you may more easily restore the
device state.

3.3.2 Configuration versions

MQTT bridge

To rephrase, under no circumstances can a device ever get a


configuration version that is older than the one it is now using;
this is because, inside any particular MQTT connection,
configurations are only supplied in the ascending version
number sequence. The device may acquire a different
configuration when it reconnects to the MQTT bridge after
disconnecting, however, since the configuration from the initial
connection may be overwritten. Bear in mind that although the
most current update will always be sent to a device, it is not
assured that it will get every configuration change. If a
configuration is modified often, devices may not get interim
versions of it.

92
Embedded Systems and IoT

You have the option of specifying the version number to be


adjusted when you are altering a device configuration. This
prevents concurrent updates from overwriting a configuration
and causing a loss of data.

HTTP bridge

The local version, which refers to the configuration version on


the device, may be specified by devices that connect via HTTP.
As was discussed in the preceding section on the HTTP bridge,
Cloud IoT Core will only return the most current available
version.

3.4 IoT Components

Figure 3.2: IoT Components

Things or Devices

The primary physical items under surveillance are things and


devices. The intelligent sensors are interconnected with other
objects or devices that collect data and transmit it to the gateway
or portal at the next level. The objects or gadgets may be
monitored using smart sensors.

93
Embedded Systems and IoT

Because of recent developments in microelectronics, it is now


feasible to create small intelligent sensors that may be used in a
range of applications. The following are examples of common
sensors:

User Interface

A user interface, or UI, is just a bunch of programmes that the


user may interact with to see and change data. What users can
see and touch when interacting with an Internet of Things (IoT)
device is called its user interface (UI). Developers have a duty
to provide users with an easy-to-navigate and aesthetically
pleasing interface that promotes greater engagement with the
product and requires less effort from the users.

Cloud

Cloud storage is used for the purpose of storing data that has
been gathered from a variety of devices or other types of items.
The term "cloud computing" refers to nothing more than a
network of interconnected servers that are always on and
accessible over the internet. The Internet of Things generates
vast volumes of data, which has to be handled effectively. This
data comes from devices, apps, and people.

94
Embedded Systems and IoT

IoT clouds are tasked with a variety of functions, including the


collecting, processing, administration, and archiving of data.
Industries and services are able to access the data remotely,
which enables them to make crucial choices whenever it is
most convenient for them. An Internet of Things cloud is, to
put it in the simplest words possible, a network of computers
that have been designed to manage traffic, process data at fast
speeds for a large number of diverse devices, and analyze data
with a high degree of precision. A distributed management
database system is required for an Internet of Things cloud to
function properly.

Analytics

Following the data's reception in the cloud, it is next subjected


to processing. In this section, data is evaluated with the use of a
variety of methods, including machine learning and others. The
term "analytics" refers to the process of transforming analog
data collected by linked sensors and devices into "actionable
insights" that are then subjected to further processing,
interpretation, and investigation. The monitoring and
improvement of the Internet of things (IoT) requires first doing
an analysis of the raw data or information that will be used in
further processing. Real-time smart analysis is one of the most
important advantages of an Internet of Things system that has
been thoughtfully developed. This kind of analysis helps
system designers to detect irregularities in the process of
information collection and to react expeditiously in order to
avert an unfavorable circumstance. The operators of the
network are able to prepare for the future steps if the
information is gathered appropriately and at the appropriate
time.

95
Embedded Systems and IoT

Network Interconnection

The Internet of Things (IoT) has seen explosive expansion in


the number of devices that are controlled by the internet and
linked to it during the last few years. Although Internet of
elements devices may be used in a myriad of contexts, there are
a few elements that all of these devices have in common, in
addition to the myriad of ways in which they vary from one
another. A wide range of technologies are what make the
Internet of Things possible. The network that is used in an
Internet of Things deployment in order to connect with other
devices is vital to the field. This role may be filled by a variety
of wireless or wired technologies.

System Security

When it comes to the deployment of the Internet of Things


(IoT), security is an essential component; nevertheless, the
security perspective is sometimes ignored throughout the
design phase. Attacks with malicious intent are being launched
against IoT vulnerabilities on a daily basis; however, the
majority of these vulnerabilities can be patched in a simple and
affordable manner. The first step in creating a safe network is
to remove security flaws from Internet of Things (IoT) devices
and then to provide users with the means to resist malicious
assaults, identify them, and recover from their effects.

Central Control Hardware

A Control Panel is responsible for managing any number of


data flows that take place across many channels and interfaces. In
addition to its other functions, a control panel must translate the
many different wireless interfaces that are present and guarantee
that all connected sensors and equipment can be accessed.

96
Embedded Systems and IoT

3.5 Introduction to Arduino

Using open-source software and intuitive hardware, Arduino


allows users to construct electrical creations. Arduino boards
take in data from many sources, such light hitting a sensor, a
button being pressed, or even a tweet, and convert it into
actions, like running a motor, lighting an LED, or publishing
something online. Hundreds of projects have relied on Arduino
as their central processing unit (CPU) throughout its lifetime.
From commonplace household goods to cutting-edge laboratory
apparatus, these projects cover it all. A worldwide community
of makers has emerged around this open-source platform. It
includes professionals, students, artists, and programmers,
among others. Everyone from beginners to seasoned pros may
benefit from the incredible amount of freely accessible material
that this community has amassed. The Italian Ivrea Interaction
Design Institute created the straightforward Arduino platform
for quick prototyping. Its creators set out to make it accessible to
pupils who were unfamiliar with electronics and programming.
As soon as the Arduino board became accessible to a wider
community, it started to change to meet new needs and
overcome new challenges. Because of this, the business was able
to expand its product line beyond simple 8-bit boards to include
items for wearable technology, embedded systems, the Internet
of Things, and 3D printing.

• Inexpensive: When compared to the cost of competing


microcontroller platforms, the price of an Arduino board is
quite low. The hand-assembled version of the Arduino
module is the most affordable option; nevertheless, even the
pre-assembled Arduino modules cost less than $50.

97
Embedded Systems and IoT

• Cross-platform: Windows, Macintosh OS X, and Linux are


the operating systems that are compatible with the Arduino
Software (IDE). Windows is the only option for the majority
of microcontroller devices.
• Simple, clear programming environment: Even though it
provides advanced programmers with a great deal of
customisation options, the Arduino Software (IDE) is easy
enough for beginners to utilise. Since it is built on top of the
Processing environment, both teachers and students may
easily adapt to it. Students learning to programme in
Processing will already be familiar with the Arduino IDE.
• Open source and extensible software: The Arduino
software is distributed in the form of open source tools,
making it possible for skilled programmers to extend its
functionality. People who are interested in understanding
the technical aspects may make the transition from Arduino
to the AVR C programming language, which is the
language that it is based on. The language can be enhanced
via the use of C++ libraries. In a similar manner, if you want
to, you may integrate code written in AVR-C straight into
your Arduino applications.
• Open source and extensible hardware: Because the designs
for the Arduino boards are made available to the public
under a Creative Commons license, skilled circuit designers have
the ability to construct their own version of the module, which
they may then expand upon and improve. The breadboard
version of the module may be constructed by users of varying
degrees of competence in order to get an understanding of how
the module functions and to save money.

98
Embedded Systems and IoT

3.6 Types of Arduino

The original intent of the Arduino board was to provide an easy


way for students to incorporate electrical components into their
own projects. The open source software that comes with the
Arduino boards allows users to build their own gadgets and
projects based on their own needs. Many different components,
including microcontrollers, connections, LEDs, and more, are
included into this electrical platform. There is a vast selection of
Arduino boards available, including the UNO, Red Board,
LilyPad, Mega, and Leonardo models. Arduino Mega is another
alternative. You may use an Arduino board in a wide range of
electrical projects; each board has its own special set of features,
capabilities, and potential uses. The six most popular types of
Arduino boards that you can buy right now are as follows:

3.6.1 Arduino UNO

It is considered that the Arduino UNO board was created


relatively recently compared to the previous Arduino boards.
The user will find it easy to include this board into their project
due to its many included features. One of the main components
of the Arduino UNO is the Atmega16U2 microprocessor. This
particular board outperforms others in terms of transfer rate
and memory storage capacity.

The Arduino UNO board may function independently of


peripherals such as a joystick, mouse, and keyboard. In
addition to the RESET pin, the Arduino UNO has two other
pins that are located near it: SCL and SDA.

99
Embedded Systems and IoT

Out of the fourteen digital input and output pins on the board,
six are for pulse width modulation (PWM) and six are for
analogue inputs. In addition to the power connector, reset
button, and USB port, the board also has one. You may connect
the Arduino UNO board to a computer using a USB port,
which also lets the device take electricity from the computer.
Data saved in the Arduino UNO is made use of via the device's
32 KB of flash memory. Another aspect of the Arduino UNO is
its ability to be connected with other Arduino devices and its
compatibility with other shields.

3.6.2 LilyPad Arduino

The LilyPad Arduino is a sort of Arduino board that is believed


to be another form of Arduino board and is meant for
integration with e-textile projects and wearable applications.
This board has a circular form, which helps to reduce the
likelihood of it catching on other objects and makes it simple to
connect it to other devices. This board has an Atmega328
microprocessor, and it is loaded with an Arduino bootloader.
This board makes use of an extremely limited number of
external components, which contributes to its simple and
compatible design.

For easy connection to other devices, the board has large-sized


pin holes and requires a power supply ranging from 2 to 5
volts. Among the many things that this board is utilised for are
the controls of lights, motors, and switches. All of the parts of
this board—the sensor board, the input board, and the output
board—are washable as it is used in the clothing business.

100
Embedded Systems and IoT

3.6.3 Arduino Mega

This circuit board, which contains an Atmega2560, is generally


understood to be a microcontroller. It has a total of 54 input
pins and output pins, with 16 pins serving as analog inputs, 14
pins serving as PWM output, and 4 pins serving as a hardware
port. In addition, there is a connector for a USB device on the
board, as well as an ICSP header, a power jack, and a REST pin.
Crystal oscillators with a frequency of 16 MHz may be accessed
using extra pins on the board that have been designed
specifically for this purpose. The data may also be stored in the
board's flash memory, which is 256 KB in capacity and has
been included on the board. The Arduino Mega board may be
connected to the computer system via the use of a USB
connection. Additionally, the board's power source can be
supplied through the use of either a battery or an AC to DC
converter. Due to the fact that the board has a substantial
quantity of pins, it is well suited for use in endeavors that need
for a greater quantity of pins to be installed.

3.6.4 Arduino Leonardo

The presence of an Atmega32u4 microprocessor on this board


leads many to assume that it is the microcontroller. Twenty
pins are available for digital inputs and outputs; seven of those
pins are PWM and twelve are analogue inputs. Twenty digital
input/output pins round out its features. The board also has a
power jack, a micro USB connection, and a reset button. The
board has additional pins that may be used to access crystal
oscillators that have a frequency of 16 MHz. A USB connection
allows the Arduino Leonardo board to be linked to a computer
system, and a battery or an AC to DC converter may power the
board.

101
Embedded Systems and IoT

Because the microcontroller that is utilized by the Arduino


Leonardo has a built-in USB connection, there is no longer a
need for an additional processor to be included in it. It is
possible for the board to function as a mouse or keyboard for
the computer system since there is not an extra USB connection
on the board. When compared to other Arduino devices, the
Arduino Leonardo is the one that is regarded as having the
lowest price point.

3.6.5 Arduino Red Board

Another form of Arduino board, known as an Arduino Red


board, may be programmed with the help of the Arduino IDE
by connecting a small USB connection to the board. It is not
necessary to alter any of the board's security settings in order to
get it running with the Windows 8 operating system since this
board is compatible with that system. The FTDI chip and the
USB chip are used for the purpose of connecting the Red board
to other devices. Due to the fact that the red board has a fairly
straightforward layout, it is readily adaptable to several
different projects. The only thing that is required is to plug in
the red board and choose the suitable choice, and then you will
be able to upload the software in no time at all. The Arduino
Red board's built-in USB cable may be controlled through its
barrel jack in certain configurations.

3.6.6 Arduino Shields

Arduino shields may be thought of as pre-built circuit boards


that are used in the process of connecting various other
Arduino boards. The Arduino shields are added on top of the
Arduino boards and expand the capabilities of the boards in a
variety of areas, including establishing wireless connection,

102
Embedded Systems and IoT

controlling the motor and LCD, and connecting to the internet


network. There are several kinds of shields that may be used in
various situations. It comes with a GSM shield, an Ethernet
shield, a proto shield, and wireless shields. This contributes to
making the Arduino boards more compatible with one another.

3.7 Arduino Toolchain

Figure 3.3: Toolchain

Create some code, then hit the upload button. For the purpose of
uploading the code, the Arduino toolchain is put through its
paces.

• The file with the.ino extension was stored in a folder with


the same name as the arduino sketches program.
• Arduino IED will now begin carrying out the following
tasks.
• The files on the sketch are assembled by the preprocessor
that comes with the Arduino IDE. There is one file
discovered inside the folder.
• Because there are a great number of boards, each of which
has a unique arrangement of pins, there is a folder in the

103
Embedded Systems and IoT

/hardware/arduino/variant directory that stores all of the


various varieties of Arduino pin configuration.
• In addition to combining all of the files, the GCC compiler,
which is an open-source C++ compiler, is included as a part
of the Arduino package.
• The preprocessor is responsible for deciphering all of the #if
and #define instructions and deciding what components are
really included in the build.
• The source code is then built and linked into a single
executable file that is tailored to the kind of processor that is
present on the board.
• After the compilation process has been completed, a piece of
open source software known as avrdude will actually
deliver the code to be executed, which will be stored in
hexadecimal binary format, to the board via the USB serial
port.
• When the Arduino is reset, a software known as bootloader
runs on the Arduino board. This program is invoked
whenever the Arduino is reset.
• When serial connection begins, the hardware serial link will
involuntarily do a reset. This will allow the bootloader to
check for any incoming drawings before continuing.
• If sketches are present, the hexadecimal value will be
converted to binary by the Arduino applications.
• The drawing is saved to the memory of the flash drive.

AVR Studio

Because the bootloader eliminates the requirement for a


particular MCU-dependent emulator, you may flash the
AVRboard directly by using AVRISPv2, AVRDragon, or
USBtinyISP instead of the bootloader.

104
Embedded Systems and IoT

However, this will not let you to use the bootloader. Because the
bootloader takes a second each time to check for new programs,
this may shorten the amount of time it takes for the board to
load.

Figure 3.4: AVR Studio

• The software known as AVR Studio is used for


programming the microcontrollers that are integrated inside
Arduinos.
• Instead of using USB, an emulated hardware programmer is
being used for the upload.
• Compared to Sketch DE, Emulator has a more involved
interface.
• The majority of the board is equipped with a 6-pin header
that enables it to be directly linked to any AVR Dragon to
access programs that are really executing on ATmega chips.
• Finally, if you are confident in your ability to upload your
software onto the Arduino board using AVR tools, you may
skip the Bootloader step entirely.

105
Embedded Systems and IoT

Figure 3.5: Hardware programmer emulator

3.8 Arduino Programming Structure

It is possible to use a wide range of languages with electronic


gear to carry out a wide range of tasks. When interacting with
machines, these languages are useful for conveying
instructions. As well as having their own syntax and
instructions, the many programming languages out there each
have their own standards for programme structure. Arduino is
an embedded system that uses the C++ programming
language. The article deconstructs the Arduino program's
structure into its individual elements.

3.8.1 Overview

The Arduino program is composed of its three primary


components, which are the structure, the values, and the
functions. When creating a piece of software, it is very essential
to ensure that the syntax of the language being used is adhered
to. This is because, in order for the code to be properly
executed, the syntax must be right. Consequently, the
following syntax should be adhered to while developing a
program for Arduino:

106
Embedded Systems and IoT

Figure 3.6: Arduino Program

107
Embedded Systems and IoT

• At the very end of the statement, after the phrase ";", a


semicolon is used to finish off the sentence.
• The “{}” symbol is used to surround the block inside the
parentheses. A statement, the declaration of a variable, a
function, or a loop may be included inside a block in a
computer program.
• It is possible to add comments to each statement in the code
in order to get a deeper comprehension of the statement's
operational capabilities. If there is just a single line
comment, you may do this by using a double forward slash
(represented by "//") at the beginning of the remark.
However, a forward slash asterisk "/*" should be used at the
beginning of the remark, and a forward slash asterisk "*/"
should be used at the conclusion of the comment if there are
many lines of commentary in a row. You may also omit any
statement by using comments in this way.

The syntax that must be followed while writing code for


Arduino software is outlined in the following illustration,
which can be found below:

Figure 3.7: Syntax used for coding in Arduino software

Once you have a firm grasp of the syntax, we can go on to


discussing how to make use of variables in an Arduino program
and the different kinds of variables that are used in the

108
Embedded Systems and IoT

construction of a program. A number or an alphabet may be


used to store any values that will be utilized in the application.
These values might be anything. When you use variables in your
application, you will have the opportunity to save, change,
update, and access the information even as it is being processed
by the computer. Variables may be of many various kinds,
including char, int, double, string, float, unsigned int, long, and
unsigned long. These are only some of the types that can be
utilized. The following is a list of operators that are utilized in
the Arduino programming:

• The "=" symbol is what is used when assigning a value to a


variable or a character. This might be anything.
• %, +, *, -, and / are all examples of mathematical operators
that may be employed. Other possible operations include
percentage, multiplication, subtraction, and addition.
• The comparison of the various values is accomplished by
the use of operators such as less than equal to, greater than
equal to, equal to, less than, and more than (==,,=).
• Logical operators, such as AND (&&), NOT (!) and OR (||),
are used in the definition of conditional expressions.

3.8.2 Arduino Program structure

The two main functions that make up an Arduino programme


are the set-up function and the loop function. Libraries and
variables used by the code are initialised in the setup() method.
Just like that, this function specifies the Arduino pin modes. It
also initiates the first connection between the computer and the
Arduino board. There is only one occurrence of the event.

109
Embedded Systems and IoT

Figure 3.8: Arduino Program structure

The loop() function continually repeats the instructions and


actively controls and monitors the Arduino. It also keeps the
program running.

Example

Compiled sample code is used to better comprehend Arduino's


modular programming architecture. The code controls the LED
light to blink at an interval of 1000 milliseconds between each
blink. The following is the Arduino code that will cause the
LED to blink:

Figure 3.9: Blinking of the LED light

110
Embedded Systems and IoT

In the first step of the setup code, the pin mode is initialized;
specifically, pin 8 has been configured as an OUTPUT. After a
delay of one thousand milliseconds, the status of the LED will
either be HIGH or LOW depending on whether the loop
function is being used. In a similar vein, we may argue that a
loop function is responsible for carrying out the
implementation of the setup function.

3.9 Sketches

Arduino refers to a program as a "sketch," which is the name of


the sketch file. It's the piece of code that gets uploaded to an
Arduino board and then is executed on that board.

3.9.1 Comments

The Blink sketch begins with a statement that spans its first few
lines:

When the Arduino executes the sketch, it will disregard


anything that is included between the /* and the */. The star (*)

111
Embedded Systems and IoT

that appears at the beginning of each line is only cosmetic and


is not essential for the comment to function properly. Those
who are viewing the code may use it to better understand the
purpose of the program, how it operates, or the reasoning
behind the way it was designed. Commenting on your
drawings and making sure those comments are up to date
whenever you make changes to the code is a recommended
best practice. This makes it easier for other people to learn from
your code or adapt it. There is still another format for making
brief remarks on a single line. These go all the way to the end
of the line and begin with the // symbol. Take for instance the
following line:

int ledPin = 13; // LED connected to digital pin 13

The message "LED connected to digital pin 13" is a comment.

3.9.2 Variables

A variable is a location in which a piece of data may be stored.


A name, a type, and a value are all associated with it. As an
example, the preceding line from the Blink design defines a
variable called ledPin, which has the type int and the value 13
as its initial value. Its purpose is to point out which pin on the
Arduino the LED is attached to, therefore it is now being
utilized. The value of ledPin will be fetched whenever the
name of that variable comes anywhere in the code. The
individual who was responsible for coding the software in this
instance had the option of omitting the creation of the ledPin
variable and, as an alternative, writing the value 13 every time
they were required to enter a pin number. One of the benefits
of using variables is that it makes it much simpler to shift an
LED to a different pin.

112
Embedded Systems and IoT

All that has to be changed is the one line of code that is


responsible for assigning the variable's initial value. On the
other hand, as the sketch is being executed, the value of a
variable will often shift. As an example, you might put the
value that was read from an input into a variable. The
Variables lesson has further information that may be found
there.

3.9.3 Functions

A function is a named chunk of code that may be called from


another location in the sketch. Functions may be called
procedures or subroutines in some contexts. The setup()
function in the Blink example has the following definition, for
example:

void setup()
{
pinMode(ledPin, OUTPUT); // sets the digital pin as
output
}

The first line of code contains information about the function,


such as the name of the function itself, "setup." The return type
and arguments are indicated by the text that comes before and
after the name of the variable; they will be discussed further
on. The portion of code located between the { and } is referred
to as the function's body, which describes the actions that the
function does. A function that has previously been defined
may be called (either in your sketch or as part of the Arduino
language). Take, for instance, the sentence in ledPin and
OUTPUT are the two arguments that are sent to the pinMode()
method when it is called using the pinMode(ledPin, OUTPUT);

113
Embedded Systems and IoT

syntax. The pinMode() method uses these arguments to determine


which pin and mode to set before performing its action.

A pin may be set up to operate as either an input or an output


by using the pinMode() method. You tell it the number of the
pin you want to customize and whether you want it to be an
INPUT or an OUTPUT when you utilize it. When the pin is set
up to function as an input, it is able to determine the status of a
sensor such as a pushbutton. It is possible for it to operate an
actuator such as an LED as an output.

Example Code: pinMode()

The digitalWrite() function outputs a value on a pin. For


example, the line:

digitalWrite(ledPin, HIGH);

114
Embedded Systems and IoT

Set the ledPin (pin 13) to HIGH, or 5 volts. Writing a LOW to


pin connects it to ground, or 0 volts.

Example Code: digitalWrite()

115
Embedded Systems and IoT

The loop() method is used repeatedly and serves as the central


focus of the vast majority of designs.

Even if you don't plan on using any of those functions for


anything, you still need to include them in your drawing.

116
Embedded Systems and IoT

3.10 Pins

It is possible to assign either an input or an output function to


each of the pins on the Arduino. The operation of the pins in
various modes may now be understood as a result of this.

It is essential to be aware that the overwhelming majority of


Arduino (Atmega) analog pins may be set and utilized in
precisely the same way as digital pins. This is something that
can be done in exactly the same way.

117
Embedded Systems and IoT

3.10.1 Properties of Pins Configured as INPUT

The pinMode() method is unnecessary when utilising Arduino


(Atmega) pins as inputs since they are already defined as inputs
by default. According to the claim, this configuration places the
pins in a high-impedance state. The input pins' very small
demands on the sampled circuit are like those of a 100 megaohm
series resistor placed in front of the pin.

The pins could be used for a capacitive touch sensor, LED


photodiode reading, or analogue sensor reading using RCTime,
among other things, because this means that switching the input
pin from one state to another requires very little current.

This also implies that pins that aren't connected to anything or


have wires that aren't part of any other circuit will report
seemingly random changes in pin state, pick up electrical noise
from the environment, or capacitively couple the state of a
nearby pin if they're configured as pinMode(pin, INPUT).
Capacitively coupling the state of an adjacent pin or external
electrical noise may both produce these changes.

3.10.2 Pullup Resistors with pins configured as INPUT

In situations when there is no accessible input signal, it is often


beneficial to route an input pin to a state that is already known.
It is possible to do this by connecting the input to either a pullup
resistor (a resistor that is linked to +5V) or a pulldown resistor (a
resistor that is connected to ground). It is possible that a pullup
or pulldown resistor with a value of 10 kiloohms might be
judged to have a sufficient value.

118
Embedded Systems and IoT

3.10.3 Properties of Pins Configured as INPUT_PULLUP

The programme allows access to the 20K pullup resistors that


are hardwired into the Atmega chip. You have to assign the
value INPUT_PULLUP to the pinMode() variable before you can
utilise the built-in pullup resistors. Because of this, the INPUT
mode's usual behavior—indicating that the sensor is off when
HIGH and on when LOW—is reversed. It is the microcontroller
in question that decides what this pullup variable should be set
to. Most AVR-based boards are guaranteed to have a value
between 20,000 and 50,000. The value on the Arduino Due might
be anything from 50,000 to 150,000 ohms.

The exact value may be found by consulting the datasheet of the


microcontroller that is put on your board. Make sure you
connect the other end of the sensor to ground when attaching it
to a pin that has been configured using INPUT_PULLUP. the
pin's reading will be HIGH when the switch is not pushed and
LOW when it is pressed, when this is applied to a simple switch.
An LED connected to an input pin is only slightly lit thanks to
the current provided by the pullup resistors. If the project's
LEDs seem to be working, but only at a dim level, this is likely
the reason.

The registers, which are found in the internal memory regions of


the chip, are also responsible for controlling the pullup resistors.
Two states may be controlled by the same registers in this way.
Therefore, when a pin is converted from an INPUT to an
OUTPUT using the pinMode() method, the configuration of the
pin will be changed to HIGH if the pin has pullup resistors
switched on when the pin is configured as an INPUT.

119
Embedded Systems and IoT

This works in the other manner as well, and if pinMode() is used


to convert an output pin to an input, and the output pin is left in
the HIGH state, the pullup resistors will be set. The following is
an example of how the internal pull-ups may be configured
prior to the release of Arduino version 1.0.1:

• pinMode(pin, INPUT); // set pin to input


• digitalWrite(pin, HIGH); // turn on pullup resistors

It is more difficult to utilise digital pin 13 as an input than any of


the other digital pins on most boards since it already has an LED
and a resistor attached to it in addition to being soldered to the
board. The onboard LED and series resistor keep the voltage
level low, so it will remain at around 1.7V instead of the
expected 5V, even after the internal 20k pull-up resistor is
turned on.

The falling voltage is a result of the inbuilt LED and resistor. It is


necessary to employ an external pull down resistor and set pin
13's pinMode() to INPUT if its usage as a digital input is
absolutely necessary.

3.10.4 Properties of Pins Configured as OUTPUT

As an output, setting a pin using pinMode() is said to put it in a


low-impedance state. This means that other circuits may get a
substantial amount of current from them.

An Atmega microcontroller's pins may send up to 40 milliamps


(mA) of current to other circuits or electronic parts, either as a
source (positive current) or a sink (negative current). Although
this current can power a great number of sensors, it won't be
enough to run most motors, solenoids, or relays.

120
Embedded Systems and IoT

The LED's brightness will be severely diminished if the series


resistor is not included. In addition to potentially damaging the
whole Atmega chip, short circuiting an Arduino pin or trying
to run high current devices from it might damage or destroy
the pin's output transistors. Additionally, Arduino pins might
experience short circuits. A "dead" pin will appear on the
microcontroller as a consequence, but the rest of the pins will
continue to work well. Unless your application demands
otherwise, it's recommended to connect the OUTPUT pins to
other devices using resistors of 470 or 1k. This will prevent the
pins from drawing the maximum current available.

3.11 Input/Output from Pins Using Sketches

3.11.1 Step-By-Step Instructions

• On the breadboard shown in the circuit diagram, install


the potentiometer.
• Connect any one of the outer pins of the potentiometer to
the jumper wire that you ran from the 5-volt pin of the
Arduino to the potentiometer.
• Connect one of the ground pins on the Arduino
(designated GND) to the other outer pin of the
potentiometer using another jumper wire.
• Connect the last jumper wire to the potentiometer's center
pin by running it from pin A0 on the Arduino to that pin.
• Insert one end of the resistor with a value of 220 ohms into
pin 9. Insert the short leg of the LED into the ground pin
that is located next to pin 13.

121
Embedded Systems and IoT

Figure 3.10: Pins Using Sketches

• Using the alligator clip, connect the long leg of the LED
to the other end of the resistor. Connect the Arduino to your
computer using the USB cable. Launch the Arduino
integrated development environment. Open up the
drawing for this part of the chapter.
• In the upper left corner of the screen, you'll see a button
labeled "Verify." Click on that button. As soon as it is
done, it will change from blue to orange, and then back to
blue again.
• Next to the Verify button, you'll see an Upload button;
click it. As soon as it is done, it will change from blue to
orange, and then back to blue again. Open the window for
the serial monitor; data from the sensor, both input and
output, should be flowing through it.
• You should see a change in the brightness of the LED as
you turn the knob on the potentiometer.

122
Embedded Systems and IoT

3.11.2 Analog input, analog output, serial output

It takes an analogue input signal, converts it to a range between


zero and two hundred and fifty, and uses that signal to control
the pulse width modulation (PWM) of an output signal. The
results are also shown on the serial monitor.

The circuit:

123
Embedded Systems and IoT

The Sketch

This sketch begins by declaring and then initializing two


variables: one for the potentiometer input pin and one for the
LED output pin. Both of these variables will be used later in the
code. In a later stage of the design, both of these variables will be
put to use. Because the variables meet the requirements to be
constants, their values cannot be changed by any other
component of the program and they are safeguarded from any
such changes:

124
Embedded Systems and IoT

Next, we will go on to the very last block of code, which is called


loop(). The value at the analog pin A0, which is where the
potentiometer is connected, is first read by the loop() function,
and then that value is assigned to a variable called sensor Value:

// read the analog in value:

sensorValue = analogRead(analogInPin);

You should keep in mind that the analogRead() function


produces a number that falls between 0 and 1023. For the sake of
this demonstration, the analogWrite() function's output value is
set to be the input value that was just recorded by us. But hold
on just a second! The analogWrite() method will only take
values in the range of 0 to 255, and nothing outside of that range
will be processed.The value that is recorded by analogRead() has
the potential to be substantially higher. The rescaling of the
input values such that they fall within the acceptable parameters
of the analogWrite() function is one approach to solving this

125
Embedded Systems and IoT

issue. This can be accomplished quite simply using the map()


function:

In this instance, we make use of the map() method in order to


modify the input value such that it falls inside the scope of the
analogWrite() function. Let's move on to the output now that we
have a value that can be used with the analogWrite() function.
Here are some examples to get you started:

analogWrite(analogOutPin, outputValue);

You may remember that the analogWrite() function requires two


parameters. 1) a pin number, and 2) the value that has to be
written. This function makes use of pulse width modulation,
which enables you to modify the amount of power that is
produced by a PWM-enabled pin (pin 9, in this example, which
is where the LED is connected). But without some kind of data
output, a program is nothing more than an empty shell. By
sending the input and output values to the serial port, we are
able to solve our problem.

126
Embedded Systems and IoT

The third statement contains code that will insert a tab character
into the string. Compared to the previous Serial.println()
method, which just included "print," the most recent one uses
"println" instead. To ensure that everything is in its proper place,
the println() method writes the value of the outputValue
variable and then begins a new line in the window that displays
the serial monitor. Adding a newline effectively inserts a new
line, much like hitting the return key in a word processor. At the
very end of the sketch is the delay() function, which controls the
timing of the analog-to-digital converter's initialization before it
receives new inputs in the loop() function. Now, we will go over
the function's purpose:

• Reads a value from the input at the analog pin A0


• Gives the value to one of the variables.
• Modifies the value of the input such that it corresponds to
the scale of the output's permitted range
• A value is assigned to a variable based on the newly
mapped value.
• Adjusts the brightness of an LED by passing the variable
via the analogWrite() function.
• Delays the program for two milliseconds in order to
guarantee that the next reading will be accurate.

3.12 Introduction to Arduino Shields

Arduino shields are additional boards that may be connected on


top of the main Arduino board to increase the capabilities of that
board. There are a number of different types of shields that may
be used for a variety of purposes. Some examples are Arduino
motor shields and Arduino communication shields. The term

127
Embedded Systems and IoT

"shield" refers to any piece of hardware that may be put on top


of the board in order to expand the functionalities of the
projects. In addition to that, it makes our job simpler. For
instance, Ethernet shields are what are used in order to establish
a connection between the Arduino board and the internet.The
shields have a pin configuration that is comparable to that of the
Arduino boards. Using the connection cable, we can not only
link the modules and sensors to the shields, but we can also
connect the modules to each other.

Types of Shields

The following is a list of the most popular Arduino shields:

Ethernet shield

The Arduino board may be connected to the internet via the use
of Ethernet shields. It is necessary for us to attach the shield to
the top of the Arduino board that has been stated. The familiar
function of uploading drawings onto the board will be
performed through the USB port.

128
Embedded Systems and IoT

Figure 3.11: Ethernet shield

A slot for a micro SD card has been included in the most recent
iteration of Ethernet shields.With the assistance of the SD card
library, the microSD card slot may be made into an interface.In
addition, we are able to attach a second shield directly on top of
the Ethernet shield. This indicates that we are able to place a
total of two shields on the top of the Arduino board.

Xbee Shield

Figure 3.12: Xbee Shield

By using the Xbee Shield with Zigbee, we are able to engage in


wireless communication with the Arduino board. The
elimination of the need for a connection contributes to the Xbee

129
Embedded Systems and IoT

model's capacity for wireless communication. We are able to


communicate at distances of up to 100 and 300 feet inside and
outdoors, respectively, thanks to the Xbee wireless module.
Additionally, it is compatible with a variety of Xbee models for
usage.

Proto shield

Custom circuits are what proto shields are meant to protect. It is


possible for us to solder electrical circuitry directly onto the
shield. The shield has SPI signal pads, two power lines, and two
LED pads. It also has two power lines. The board has two power
lines: the IOREF, which stands for "Input Output voltage
REFerence," and the GND, which stands for "Ground." On the
prototype area, we are also able to solder SMD (Surface Mount
Device) integrated circuits. On the surface of the SMD region,
there may be a maximum of 24 pins incorporated.

Figure 3.13: Proto shield

Relay shield

Due to voltage and current constraints, the Arduino digital I/O


pins are unable to withstand the high current that is being sent

130
Embedded Systems and IoT

through them. To get over this kind of difficulty, the relay shield
is used.

Figure 3.14: Relay shield

It offers a solution to the problem of managing the devices that


carry large currents and voltages.This shield has four LED
indicators and four relays in its construction.In addition to this,
it has NO/NC interfaces as well as a shield form factor, which
enables a straightforward connection to the Arduino board.The
status of each relay is shown by the LED indicators as either
"ON" or "OFF."The relay that was used in the construction of the
building is of superior grade.Each relay has pins labeled COM,
NO (normally open), NC (normally closed), and NO (normally
closed), respectively.The use of the Relay shield may be seen in
applications such as remote control, etc.

Motor shield

Through the use of the Arduino board and the motor shield, we
are able to control the motor. It determines the motor's working
direction as well as its operating speed. Either an external power
source connected to the input terminal of the motor shield, or
the Arduino itself, may be used to provide power to the shield.

131
Embedded Systems and IoT

With the assistance of the motor shield, we are also able to


determine the current that is being absorbed by each motor.

Figure 3.15: Motor shield

The L298 chip, which is included into the motor shield, has the
capability of driving either a step motor or two DC motors. A
complete bridge IC may be found on the L298 chip. The
performance of the motor shield is improved because to the
inclusion of the heat sinker, which is also a part of it. It is able to
drive inductive loads, such as solenoids and other similar
components. There is a range of 5V to 12V in the operational
voltage. Applications of the motor shield include things like
intelligent cars and microrobots, amongst other things.

LCD shield

The LCD (Liquid Crystal Display) shield has five buttons that
are referred to as up, down, left, and right, as well as the select
button. On the shield, there is a total of six push buttons that
may collectively function as a control panel for a bespoke menu.
It is made up of 1602 white characters, which can be seen on the
blue backlight LCD screen.

132
Embedded Systems and IoT

Figure 3.16: LCD shield

The power is turned on, as shown by the LED that is located on


the board. The presence of these five keys on the board enables
us to navigate the menus and transition smoothly from the
board to our project.The LCD shield is often developed for
traditional circuit boards like the Duemilanove and other similar
products.

Bluetooth shield

The Bluetooth shield has the capability of functioning as a


wireless module, allowing for transparent serial communication.
It comes with a module for serial Bluetooth connectivity. The
serial hardware ports in the Bluetooth shield are labeled D0 and
D1, and they may connect with the two serial ports (from D0 to
D7) on the Arduino board. These ports range in number from
D0 to D7. Through what is known as a Grove connection, which
are two serial ports on the Bluetooth shield, we are able to attach
Groves. The analog Grove connection is in contrast to the digital
Grove connector. Within the confines of the house, the Bluetooth
shield has a communication range of up to 10 meters when there
are no obstructions in the way.

133
Embedded Systems and IoT

Figure 3.17: Bluetooth shield

Capacitive Touchpad shield

It is able to combine the Arduino board with the touch shield


thanks to the touchpad interface that it has. Twelve sensitive
touch buttons are included as part of the capacitive touchpad
shield, in addition to three electrode connections and nine
capacitive touch pads. The logic level of either 3.3V or 5V may
be used successfully with the board.The capacitive shield is
shown in the following image:

Figure 3.18: Capacitive Touchpad shield

134
Embedded Systems and IoT

UNIT IV

IoT COMMUNICATION AND OPEN PLATFORMS

4.1 IoT Communication Models and APIs

The Internet of Things (IoT) refers to a network of


interconnected electronic devices that are able to interact with
one another, exchange data, and carry out operations
independently of human involvement. The significance of
communication in the Internet of Things (IoT) cannot be
emphasized since it serves as the basis upon which the whole
system is constructed. It is necessary for the many devices that
comprise the IoT ecosystem to be able to interact with one
another in order for the ecosystem to work effectively and for
the devices to accomplish their goals. Devices in the Internet of
Things are able to exchange data, receive instructions, and
accurately reply to requests for information when there is
effective communication between them. This is essential for the
effective adoption of Internet of Things solutions across a variety
of sectors, including healthcare, manufacturing, transportation,
and smart homes, among others.

For instance, in a smart home, the equipment (such as lighting,


thermostats, and security systems) are able to communicate with
one another, which enables them to collaborate in order to make
the living environment more comfortable and secure for the
people who live there. In a similar vein, Internet of Things
devices may be used in the context of the healthcare industry to
remotely monitor patients and notify healthcare personnel in the
event of an emergency, therefore guaranteeing that prompt
medical attention is offered.

135
Embedded Systems and IoT

4.1.1 Types of Communication Models in IoT

The Internet of Things (IoT) ecosystem supports a variety of


communication models, the selection of which is determined by
the specifications of the use case being implemented. The
Internet of Things primarily employs the following three
communication models:

Client-Server Model

In a communication mechanism known as "client-server," the


client contacts the server with encoded requests for the
information it needs at any given time. This model is stateless,
which means that each request is processed in isolation from the
others, and data is not saved from one request to the next. The
request is first categorized by the server, then the data is
retrieved from the database or resource representation, and
finally, the data is converted into an encoded response that is
transmitted back to the client. After then, the answer is sent to
the customer.

Figure 4.1: Client-Server Model

136
Embedded Systems and IoT

On the other hand, in the Request-Response communication


paradigm, the client initiates a request that is then sent to the
server. The server then decides how to obtain the information or
resources that are required to create a response to the request
that was initiated by the client. After the answer has been
created, the server will send it back to the client.

Publish-Subscribe Model

Publishers, Brokers, and Consumers make up the three


components of the Publish-Subscribe communication paradigm.
The broker is in charge of creating and transmitting data to
specified themes, and the publishers are responsible for
generating and distributing that data. The publishers are
unaware of the number of subscribers who have purchased the
subject.

Figure 4.2: Publish-Subscribe Model

Consumers sign up for the subjects that are controlled by the


broker so that they may get data from publishers. It is the duty
of the broker to distribute the data to the right customers, taking
into account the subjects to which those customers have
subscribed.

137
Embedded Systems and IoT

It is the responsibility of the broker to receive data from the


publishers and then transmit that info to the right consumers
who have subscribed to that particular subject. The only entity
with knowledge about the consumer to whom a certain subject
belongs is the broker, and the publishers are unaware of this
information.

Push-Pull Model

Data publishers, data consumers, and data queues are the three
components that make up the Push-Pull communication
paradigm. The publishers and the customers are not conversant
with one another. The data is pulled out of the queue by
consumers after being pushed in by publishers, who add new
messages or data to the queue. When there is a disparity in the
rates at which the publisher and the consumer are pushing or
pulling data, the queue steps in to function as a buffer for the
messages.

Figure 4.3: Push-Pull Model

Queues play an important part in decoupling messaging


between the producer and the consumer, and they operate as a

138
Embedded Systems and IoT

buffer in instances where there is a mismatch in the pace at


which data is pushed by producers and pulled by consumers.
Queues play an essential role in decoupling messaging between
the producer and the consumer. This buffer contributes to
ensuring that communication between the two entities goes off
without a hitch.

Exclusive Pair Model

Communication models known as Exclusive Pairs are those that


allow for full-duplex, two-way exchanges of information
between a client and a server. These models are intended for use
in situations in which there is a continual or ongoing link
between the two entities. After a connection has been
established between the client and the server, both parties are
able to communicate with one another via the exchange of
messages. The connection will stay open as long as the client
does not send a request to the server to stop it, and the server
will be aware of each and every open connection. Because of
this, the client and the server are able to interact without any
disruptions and in real time.

Figure 4.4: Exclusive Pair Model

139
Embedded Systems and IoT

4.1.2 REST-based Communication APIs

REST, which stands for "representational state transfer," is a set


of architectural principles that may be used to create Web
services and Web application programming interfaces (APIs)
that put an emphasis on the resources of a system and the
manner in which the states of those resources are addressed
and communicated. REST APIs are application programming
interfaces that adhere to the request response communication
paradigm. Within a distributed hypermedia system, the rest
architectural restrictions apply to the components, connectors,
and data elements. The following is a list of the remainder of
the architectural constraints:

• Client-server: The client-server restriction is founded


on the idea of separating the interests of the two parties
involved. Clients, for instance, should not be worried
with the storage of data, which should instead be the
responsibility of the server. Similarly, the client, not the
server, should be worried with the user interface. The
server should not worry about the user interface. The
client and the server are able to be separately created
and updated because to the separation.
• Stateless: Each request that is sent from the client to
the server has to provide all of the information that is
required to fully comprehend the request, and the
server is not allowed to make use of any cached
context. The client is responsible for storing the session
state in its entirety.
• Cache-able: The data included inside a response to a
request has to be implicitly or explicitly designated as
cache-able or non-cache-able in order to satisfy the

140
Embedded Systems and IoT

requirements of cache restrictions. If a response may be


cached, then a client cache has the permission to utilize
the data from that answer for subsequent requests that
are functionally identical. Caching may remove certain
instructions entirely or in part, so improving both
performance and scalability.
• Layered system: The behavior of components is
constrained by the layered system restrictions in such a
way that each component is unable to look beyond the
current layer with which it is interacting. The client, for
instance, is unable to determine whether it is connected
directly to the destination server or to an intermediate
server along the route. It is possible to increase the
scalability of a system by enabling intermediates,
rather than the end server, to react to queries. This may
be accomplished without requiring the client to make
any adjustments.
• Code on demand – The clients may run scripts or
executable programs that the server has provided for
them to run in their own context. The only requirement
that may be relaxed is this particular one.

Because of the limits imposed by the uniform interface, the


mode of communication that is used between the client and the
server is required to be consistent. The representations of the
resources' data that are provided back to the client are not the
same things as the resources themselves; resources are specified
in the requests (in web-based systems, this is done via URIs).
When a client maintains a representation of resources, that client
is in possession of all of the information necessary to modify or
delete the resource (assuming that the client possesses the

141
Embedded Systems and IoT

necessary permissions). Each message has an adequate amount


of information to specify how the message should be processed.
A " Web API " that is constructed using HTTP and REST
concepts is referred to as a " RESTful web service ". The most
widely used interface for Internet of Things communications is
called REST.

4.1.3 WebSocket based communication API

With the help of Websocket APIs, clients and servers may have
bidirectional conversations at the same time. Websocket APIs
follow the principle of exclusive pair communication. When
compared to request-response formats like REST, WebSocket
APIs provide full duplex communication without requiring the
creation of a new connection before each message is sent.
Through the submission of a connection setup request, the
client establishes communication with the server. After then,
the server handles this request. Once sent over HTTP, the
server interprets the request—known as a websocket
handshake—as a request for an update. If the server is
websocket capable, it will respond to the websocket handshake
response. Once the connection has been successfully
established, the client and server may engage in full duplex
communication. The Websocket API drastically reduces latency
and network traffic as there is no cost for connection formation
and termination requests per message. Internet of Things
applications requiring low latency or high throughput may be
met by a websocket. Internet of Things (IoT) systems are best
served by the Web socket protocol, which is an API for Internet
of Things communication.

142
Embedded Systems and IoT

Figure 4.5: WebSocket Protocol

4.2 IoT Communication Protocols

When establishing a network to support their Internet of


Things environment, technologists have a number of different
communication protocols from which to choose. Some of the
more frequent ones are listed below.

4.2.1 AMQP

The Advanced Message Queuing Protocol goes by the name


AMQP. An open standard protocol for message-oriented
middleware goes by that name. Consequently, it paves the way
for systems to engage in messaging-based communication with
one another, regardless of the media or platforms used. It
guarantees reliability, security, and interoperability even across
long distances or via unreliable networks. Whether or not all
systems are available simultaneously, it permits
communications anyway.

143
Embedded Systems and IoT

4.2.2 Bluetooth and BLE

Bluetooth is a short-range wireless technology that uses


narrow-wavelength, very high-frequency radio waves to
communicate. Although its primary function has always been
to enable audio streaming, it has recently grown in importance
as a bridge between wireless and networked devices. This
makes this low-power, low-range connectivity option ideal for
use in both individual home networks and IoT setups.

Another option is Bluetooth Low Energy, which goes by a few


different names: LE and BLE. Connectivity between devices on
the Internet of Things was the primary goal in developing this
more recent version of Bluetooth. As its name implies, BLE is
particularly beneficial in many contexts due to the fact that it
consumes less power than conventional Bluetooth. From a
consumer perspective, it seems like a natural match for smart
home gadgets and fitness trackers. From a commercial
perspective, it shines when used to in-store navigation.

4.2.3 Cellular

A well-known and widely-accessible option for Internet of


Things applications is cellular. Additionally, it's a wonderful
option for deployments when connections span longer
distances. Even while previous cellular technologies like 2G
and 3G are currently being phased out, telecom companies are
rapidly expanding the coverage of newer high-speed standards
like 4G/LTE and 5G. Cellular networks provide reliable, high-
bandwidth communication.

144
Embedded Systems and IoT

Because it provides greater leeway, its ability to transmit


massive amounts of data is crucial for several Internet of
Things (IoT) deployments. While these features are certainly
useful, they aren't cheap or energy efficient when compared to
alternative options.

4.2.4 CoAP

The Internet Engineering Task Force Constrained RESTful


Environments Working Group first published CoAP
(Constrained Application Protocol) in 2013. Because of this, it
was designed to work with IoT systems that rely on the
Hypertext Transfer Protocol (HTTP). Thanks to User Datagram
Protocol, which is supported by CoAP, secure connections can
be set up and data may be sent across several locations with
ease. With CoAP, even devices with low energy consumption,
poor availability, or low bandwidth may join an Internet of
Things ecosystem. Applications using machine-to-machine
(M2M) communication often make use of this protocol.

4.2.5 DDS

The Data Distribution Service was developed by the Object


Management Group (OMG) specifically for use in real-time
computing settings. DDS is described by OMG as "a
middleware protocol and API standard for data-centric
connectivity," pointing out that "it integrates the components of
a system together, providing low-latency data connectivity,
extreme reliability, and a scalable architecture that business
and mission-critical IoT applications need." By using a publish-
subscribe format, this M2M standard enables scalable, high-
performance, real-time data communication.

145
Embedded Systems and IoT

4.2.6 LoRa and LoRaWAN

A noncellular wireless technology that allows for long-distance


communication, LoRa stands for "long range" and is an
abbreviation for the term. It guarantees secure data transport
for IoT and machine-to-machine applications while using less
power. Semtech has implemented this unique technology onto
its radio frequency platform.

Semtech was an early member of the LoRa Alliance, which is


now in charge of the LoRa standard. The LoRa Alliance first
developed and continues to maintain LoRaWAN, an open
cloud-based protocol. It paves the way for LoRa
communication between IoT devices.

4.2.7 LWM2M

According to OMA SpecWorks, "a device management


protocol designed for sensor networks and the demands of an
M2M environment" is what Lightweight M2M (LWM2M) is.
This communication protocol is great for low-power devices
with limited processing and storage capacity since it was
created specifically for remote device administration and
telemetry in Internet of Things (IoT) settings and other
machine-to-machine (M2M) applications.

4.2.8 MQTT

Message Queuing Telemetry Transport was its original name


when it was created in 1999, but today it's just known as
MQTT. No longer does this protocol make use of message
queuing in any way.

146
Embedded Systems and IoT

Utilising MQTT's publish-subscribe architecture enables


machine-to-machine communication. A number of devices are
able to connect with one another thanks to its simple message
system, which is compatible with a restricted number of
devices. Its design prioritises performance in low-bandwidth
scenarios, such those involving mobile devices and sensors
linked to unstable networks. This capability makes it a top pick
for wireless networks experiencing unpredictable latency due
to bandwidth constraints or unreliable connections, and for
connecting devices with a small code footprint. MQTT has
transformed from a proprietary protocol into the most widely
used open source alternative for connecting IoT and industrial
IoT devices.

4.2.9 Wi-Fi

Due to its extensive usage in residential, commercial, and


industrial contexts, Wi-Fi has become one of the most preferred
protocols for the Internet of Things. Fast data transfer and
simultaneous analysis of large datasets are also capabilities it
has. Local area network (LAN) situations, where the distances
are usually between short and medium, are ideal for Wi-Fi.
Plus, developers have a lot of options when it comes to
adopting the technology thanks to the many Wi-Fi standards;
802.11n is the most popular one in homes and certain
businesses. Yet, for some Internet of Things applications, the
power consumption of several Wi-Fi protocols—including the
one often used in homes—is too high. Particularly for gadgets
that run on batteries or operate with little power, this is the
case. This limits the availability of Wi-Fi as a feature in some
setups.

147
Embedded Systems and IoT

4.2.10 XMPP

The Jabber open-source community originally developed


XMPP in the early 2000s for use in real-time human-to-human
communication. Lightweight middleware now uses XMPP for
M2M communication and XML data routing. Since XMPP
allows the real-time transfer of structured data that is yet
extensible across various entities connected to a network, it is
most often used for consumer-oriented Internet of Things
installations, including smart home appliances. It is an open-
source protocol that the XMPP Standards Foundation supports.

4.2.11 Zigbee

In the beginning, Zigbee was established as a protocol for mesh


networks. Its primary purpose was to be used in applications
that were associated with home and building automation. At
the present time, it is one of the mesh protocols that is used the
most often in Internet of Things environments. Through the use of
Zigbee, a communication technology that is both low-power and
short-range, it is possible to extend communication across a number
of different devices. The transmission rate of this technology is
slower than that of Bluetooth Low Energy (BLE), but it has a greater
range than BLE. An adaptive and self-organizing mesh, extremely
low power consumption, and a library of applications are all
features that it offers. Additionally, the Zigbee Alliance is in charge
of overseeing its administration.

4.2.12 Z-Wave

Z-Wave is yet another proprietary alternative that functions as


a communication protocol for wireless mesh networks and is
based on low-power radio frequency technology.

148
Embedded Systems and IoT

Similar to Bluetooth and Wi-Fi, Z-Wave allows smart devices to


communicate securely with one another. The infrastructure
supporting the Internet of Things is therefore further fortified.It
finds extensive use in commercial applications, such as energy
management systems, and in residential ones, such as home
automation and security systems. The transportation sector is
another major user. While its radio frequency does vary from
country to country, it is most often utilised at 908.42 MHz in
the US. An organisation that works to improve the technology
and compatibility of Z-Wave devices is the Z-Wave Alliance.
The Z-Wave Alliance is the organisation behind Z-Wave.

4.3 Bluetooth

As a method for establishing wireless connections between


electronic devices, Bluetooth has been used. Since that time,
Bluetooth has established itself as the de facto standard for
establishing wireless connections in wearables, gadgets, and
other types of devices. Bluetooth technology is now integrated
into a wide variety of products, including autos, speakers,
wearables, medical equipment, wireless headphones, and
shoes, to name a few. It is safe to presume that if we own any
contemporary device, we have been exposed to and made use
of Bluetooth technology at some point in the past.

To put it another way, Bluetooth is a kind of wireless


technology that has a small range and is designed to transfer
data between two electronic devices over a relatively short
distance. This technology does away with the need of using
wires in order to connect devices.

149
Embedded Systems and IoT

As an example, we are now able to listen to music on the go


using a headset without having to connect it into the headset
jack of the mobile device.

Figure 4.6: Bluetooth

Standard Bluetooth has given way to smart Bluetooth as the


technology behind Bluetooth has evolved, with Bluetooth 5
being the most current version available. When compared to
earlier generations, Bluetooth 5 has a range that is four times
further, a speed that is four times faster, and a data transmission
frequency that is 800 percent higher. Because of these updated
qualities, businesses with extensive and essential infrastructures
may be able to achieve 100 percent uptime and cost-efficient
solutions by deploying Internet of Things devices that are
equipped with Bluetooth 5. In addition, Internet of Things (IoT)
devices may get assistance from Bluetooth Low Energy (BLE), a
variant of Bluetooth that is specialized for low-powered devices.
BLE can keep IoT devices in sleep mode until they are
connected, which helps save energy. Because it can pair and
reconnect with devices in only six milliseconds, rather than the
six seconds that it takes with regular Bluetooth, BLE is ideal for
Internet of Things applications. Not only does this enhance the
working efficiency, but it also increases the availability of the
gadget.

150
Embedded Systems and IoT

A typical Internet of Things design consists of several levels, the


most notable of which are the hardware, communication,
software system, and application layers. Bluetooth is used as the
communication layer. The communication layer serves as an
essential connecting point for all of the other levels. It is part of a
stack that consists of many layers and contains data connection,
network or transport, and session protocols. Bluetooth Low
Energy, most often abbreviated as BLE, is a data communication
layer that connects sensors to one another as well as sensors to
gateways. On the other hand, it is the responsibility of the
network layer to transport or route data packets through the
network in a manner that makes use of the most efficient
potential paths. The session layer protocols make it possible for
the various components of the Internet of Things
communication subsystem to communicate with one another.
When compared to alternative communication protocols, such
as RFID, NFC, WLAN, LoRa WAN, LTE-A, and WiFi-Direct, the
use of Bluetooth technology is much more cost-effective.
Additionally, it enables wireless communication as well as the
instant formation of a personal area network (PAN) in locations
where there is insufficient wireless infrastructure. It utilizes a
standardized process and has a low level of interference.
Additionally, the Bluetooth standard range of 0-30 meters may
be extended in certain cases by raising the power beyond one
milliwatt.

Bluetooth IoT Applications

Because of the use of energy-saving Bluetooth programs and


energy-harvesting models, a variety of electronic devices,
including remote controls, smart home gadgets, wearables,
tracking devices, and keyboards, among others, have been

151
Embedded Systems and IoT

designed to alleviate the anxiety and financial burdens that are


associated with customers being required to replace batteries on
a regular basis. Applications for Bluetooth Internet of Things are
used in both industrial and corporate settings. These include
asset monitoring, indoor locating, beacons, industrial
automation sensors, tire pressure monitors, electronic shelf
labels, and other similar devices. As a result, ownership and
maintenance expenses will be reduced since it will no longer be
necessary to replace the batteries in these devices.

4.4 Wi-Fi

Wi-Fi is an acronym that stands for Wireless Fidelity or


Frequencies. This technology makes it possible for many
computers to interact with one another and offers a way to
connect to the Internet by going from an access point to a
personal computer or laptop. Utilizing a variety of radio
frequency bands, the Wi-Fi networking technology mixes and
sends data and information between connected devices. Wi-Fi is
a technology that is used often in today's personal computers
and mobile phones.

Figure 4.7: Wi-Fi

152
Embedded Systems and IoT

4.4.1 Working

Radio waves are used in the transmission of data over a Wi-Fi


network, much as they are in mobile phones. A wireless adapter,
which transforms the data being sent into a radio signal, ought
to be included in the computer. Through the use of an antenna,
identical signals are sent to a router's decoder. Following the
completion of the decoding process, the data is then sent to the
Internet via a linked Ethernet connection.

Figure 4.8: Working of Wi-Fi

Because the wireless network is two-way, data coming from the


Internet will also go via the router and be encoded into a radio

153
Embedded Systems and IoT

signal that the wireless adapter in the computer will pick up.
This is because the wireless network is a bidirectional network.

4.4.2 Types of Wi-Fi Connections

Router

The majority of homes in today's world connect to the Internet


via the use of a wireless router. Some of the advantages are as
follows:

• The simplicity of the setup.


• Portability inside the area covered by the Wi-Fi access
point (also known as a router).
• The capacity to link a large number of separate devices.

The possibility for interference from other electromagnetic


equipment in the house is one of the drawbacks, along with
limited capacity and deteriorating performance as more
electronic gadgets connect to the same Wi-Fi network.

Hotspot

As a safe and convenient way to stay connected while traveling,


mobile hotspots are quickly gaining in popularity. One of the
most common types of hotspot devices is a smartphone. Another
example is a jetpack. In today's world, almost any mobile phone
or tablet computer can function as a temporary hotspot, which is
a fantastic option for those of us who just use this capability on
occasion. It is simple to use and does not need the acquisition of
additional devices; nonetheless, it has a rapid drain on both the
user's battery and their data allowance.

154
Embedded Systems and IoT

On the other hand, a jetpack may serve the purpose of a


customized mobile hotspot that, much like our smartphone, can
connect to a signal emanating from nearby mobile towers. It has
a wider range and can connect to a greater number of devices than its
predecessor. Since our smartphone is a separate piece of hardware,
the amount of power stored in its battery does not change.

4G LTE

4G LTE Home Internet is an option worth considering in the


event that we find ourselves living in a distant area with
limited internet access options. It offers high upload and
download speeds of around 25 Mbps and often has reduced
latency while also providing more data than satellite does. The
perks include increased speeds as well as increased reliability
from our carrier. The disadvantages of 4G LTE Home Internet
include its limited availability as well as the high costs of both
the service and the installation.

5G

When it becomes more widely accessible, 5G (also known as


Fixed Wireless Access) has the potential to become one of the
greatest and most cost-effective internet services that are
currently available. It has a higher capacity than 4G, much
faster speeds (up to one gigabit), and lower latency than what
the majority of people experience at their homes as a result of
using a new spectrum of stable radio frequencies over a
wireless network. Due to the fact that 5G wireless base stations
are often located within 10 kilometers of residential areas, the
dependability of the service is typically remarkable. The limited
availability of 5G home internet service is now the only major
drawback it has, although this will change in the near future.

155
Embedded Systems and IoT

Wi-Fi In IoT

Because of the ease with which hostile attacks may be launched


against Wi-Fi networks, the Internet of Things necessitates the
usage of microchips as well as strong firmware in order to keep
track of each device's Wi-Fi credentials. Enabled with Wi-Fi
Devices connected to the internet of things are usually large,
immobile hubs. However, there are certain smaller devices that
are also capable of using Wi-Fi. If we wish to utilize Wi-Fi, the
Internet of Things device that uses Wi-Fi must be within a
certain distance of the Wi-Fi access point.

4.5 ZigBee

ZigBee is an industry standard for wireless technology that


delivers a collection of communication protocols for use in
close-range communication. It is a worldwide open-source
standard that was designed by the Zigbee Alliance to meet the
requirements of low-cost and low-power wireless Internet of
Things networks. The protocol is used in wireless networking
devices that have a low data transfer rate and a short to
medium range, such as sensor and control networks. ZigBee is
an open wireless networking standard that offers tremendous
compatibility as well as flexibility for developers and end
users. The protocol may be used in a wide variety of settings as
a result of its advantageous characteristics, which include
cheap cost, low power consumption, and speedier wireless
communication. For instance, it is a well-liked technology for
usage in smart homes since, in comparison to other wireless
technologies, it has a number of characteristics that set it apart.
First and foremost, the fact that communication with ZigBee
devices is bidirectional contributes to their dependability.

156
Embedded Systems and IoT

Second, it serves all markets, including the lighting industry, the


security industry, the appliance industry, and the home access
market. Thirdly, and most crucially, this technology has a very
low power need. This is mostly attributable to the fact that it has
a short latency and a low duty cycle. In addition to this, it
utilizes a mesh network, which decreases the likelihood of
failure at individual nodes.

Figure 4.9: ZigBee

ZigBee has a wireless range of up to 400 meters outside and up


to 70 meters indoors. It is compatible with a variety of networks,
including point-to-point and point-to-multipoint mesh-based
networks. Notably, it utilizes AES 128 encryption, which
safeguards your information even while it is being sent over the
air. In addition, the ease with which it may be installed and
maintained contributes to its relatively low cost.

An intriguing fact about where the term ZigBee came from is


presented here! The term "waggle dance" comes from the
behavior that bees engage in upon returning to their hives in
order to communicate with one another. This is where the name
derives from. ZigBee earned its name from this zigzag dance
that it used to do.

157
Embedded Systems and IoT

4.5.1 ZigBee Frequency

The physical and media access control layers of the IEEE


802.15.4 standard are used by Zigbee. In addition, it utilizes the
unlicensed ISM band at 2.4 GHz for its operations. Even
though 2.4 GHz is widely used everywhere, there are still
devices that operate on lower frequency bands in some regions,
such as the United States (915 MHz), Europe (868 MHz), and
China (784 MHz). Additionally, it is capable of transferring
data at a speed of 250 kbps.

4.5.2 ZigBee vs Wi-Fi

ZigBee operates on the same frequency spectrum as Wi-Fi and


Bluetooth, making it possible for it to be utilized for short-
range communications or the creation of personal area
networks. It was developed specifically for use in sensor and
control networks. Its primary function is to monitor and control
devices, a task for which Wi-Fi and Bluetooth are inadequate options
due to their inadequacies as wireless communication technologies in
this particular context. Wi-Fi is mostly reliant on the IEEE 802.11
series, while ZigBee is primarily based on IEEE 802.15.4. Because
ZigBee is based on WPAN and Wi-Fi on WLAN, the two
technologies cannot be compared to one another. Wi-Fi has a range
of 30–100 meters, but when combined with another technology, it
can reach a distance of 10–30 meters. In addition to that, it offers a
data rate of 250 Kbps. Wi-Fi technology, on the other hand, is used
for communication by devices that have a high power output and a
high data transfer rate since it operates at a rate of 54 Mbps. The
lowest power consumption rate and the longest possible battery life
of the devices are two of Zigbee's strongest selling points.

158
Embedded Systems and IoT

4.5.3 ZigBee vs Bluetooth

ZigBee, in contrast to Bluetooth, employs a transmission power


that is just 100 milliwatts, making it more power-efficient than
Bluetooth in terms of power usage. In addition to this, it is built
with the capability of supporting hundreds of devices, which is
a significant advantage when compared to Bluetooth, which
only supports a maximum of seven devices. You are now
aware of the practical applications of ZigBee! The key
distinctions are shown in the table that follows.

Figure 4.10: ZigBee vs Bluetooth

4.5.4 System Structure

There is a ZigBee Coordinator, a ZigBee Router, and an End


device that make up the ZigBee system.

159
Embedded Systems and IoT

• ZigBee Coordinator (ZC): A network must have at least


one central unit to function properly. Because it
coordinates and serves as a bridge for the network, ZC
is the most significant device in the system. It is the
piece of hardware that initiates the connection between
computers in a network. The most significant duty that
falls within this unit's purview is that of data
transmission and receiving. In addition to this, it
makes managing and storing information more
simpler.
• ZigBee Router (ZR): A router is a device that serves as
an intermediary. It makes it possible for data to move
freely across them and on to other devices.
• ZigBee End-Device (ZED): A ZED acts as an interface
to a sensor and is responsible for carrying out the
control action. The capability that is included in the
end device is simply sufficient for it to speak to either
the coordinator or the router. This results in the node
being asleep for an extended period of time, which
extends the battery life to a significant degree. A ZED
device has a lower energy need in comparison to a ZC
or ZR device.

4.5.5 Topologies

The network topology that is being used will determine the


amount of coordinators, routers, and devices that are present in
the network. There are three different topologies that may be
used for a ZigBee Network: star, cluster tree, and mesh.

160
Embedded Systems and IoT

• A coordinator is required for a star network, in


addition to an unspecified number of end devices.
After then, these devices are linked to the coordinator,
but they are kept separate from one another.
• In an architecture known as Cluster Tree, end devices
link to the coordinator via the use of Routers.
• Because the nodes in mesh networks are coupled with
other nodes, there are various paths that may be taken
to reach each node.

Figure 4.11: ZigBee Network topologies

The connectivity between nodes is maintained by the use of


several built-in routing protocols. As a result, it maintains a
high level of stability in the face of shifting circumstances or
failure at any node.

161
Embedded Systems and IoT

4.5.6 ZigBee Architecture

The architecture of a ZigBee network consists of four different


levels. The ZigBee standard defines two of the four levels that
make up the stack that makes up the ZigBee protocol
architecture. The physical and MAC layers are described in
IEEE 802.15.4, while the other two layers belong to the Zigbee
specification.

Figure 4.12: ZigBee Architecture

• The signals that are transmitted and received go through


the process of modulation and demodulation at the
Physical layer. MAC layer is responsible for data transport
via CSMA/CA. In addition to this, the MAC layer is
responsible for synchronizing the communication
between the various devices.
• The network layer is in charge of establishing a network,
connecting to the various devices, and routing data,
among other responsibilities. Finally, the application layer
enables the device to connect with a network layer, which
enables the devices to communicate with one another and
handle the data that is sent between them.

162
Embedded Systems and IoT

4.5.7 ZigBee Applications

ZigBee makes it possible to use wireless networks extensively by


providing low-cost and low-power solution options. Most
crucially, it enables applications to be monitored and controlled
while continuing to function for years on batteries that are quite
affordable. ZigBee is generally making breakthroughs in the
fields of home automation, healthcare, and the monitoring of
materials, to name a few of these sectors. The following are some
of its applications:

Figure 4.13: ZigBee Applications

163
Embedded Systems and IoT

4.6 GPS

The Global Positioning System (GPS) utilizes satellites to track


the location of everything that is equipped with a GPS tracking
device. This includes people, animals, and even cars. It functions
normally no matter what the weather is like and provides
accurate location updates in real time. The Global Positioning
System (GPS), which was one of the early methods to collect and
communicate digital information from the actual world, has had
a major effect on the development of Internet of Things
technology. It is possible for the Internet of Things (IoT) to
acquire and measure large volumes of data on everything from
an individual's health to public transit; GPS tracking is necessary
in order to give location information for such things. Using GPS
and the Internet of Things, one may create a data collection that
is more trustworthy and is also more readily available. The
Internet of Things is able to keep track of moving objects and
record information about those objects' motions in real time,
much as a GPS system can monitor a moving automobile and
determine its exact position. Every day, the satellites that
comprise the GPS system perform two precise orbits around the
earth. Through the use of a GPS receiver, the signal of an
individual satellite as well as its orbital characteristics may be
decoded and utilized to determine the position of the satellite.
GPS receivers make use of this information in conjunction with
triangulation to locate the exact position of the people who have
the devices.

The uses of GPS and the Internet of Things

When integrated into devices that are connected to the Internet


of Things (IoT), GPS technology may provide advantages that

164
Embedded Systems and IoT

you did not anticipate enjoying. In this day and age, when
everything is connected to the internet, it is feasible to collect
massive volumes of data from a broad range of different
sources. The information that is contained consists of things like
face mapping and medical records. We have been able to locate
our missing cellphones by utilizing the GPS technologies that
are built into them up to this point. We are now able to find the
luggage that were misplaced. These high-tech backpacks, known
as Symphonia Bags, are capable of being monitored via GPS.
Parents are able to use the backpack as a tool to locate their
children in situations when they cannot see them. You won't
need to worry about leaving any of your items behind at the
airport or when traveling since you'll have this bag with you.
The keen expectation that people have for the day when they
will be able to relax in a driverless car as they put their feet up
and let it take them away is something that nobody can dispute.
There is a possibility that the children and teenagers of today
may never put their driving abilities to use. Fully autonomous
driving capabilities will be available in automobiles that are
fitted with GPS technology.

The Long-Term Perspective of GPS with IoT

If you are using a GPS device, it is feasible that all of your


possessions may be found. For instance, the Italian company
Sherlock employs Global Positioning System (GPS) technology
in conjunction with the Internet of Things in order to monitor
your bicycle. The adoption of this form of monitoring by bicycle
owners helps deter theft of their bicycles. In addition, the owner
of the vehicle will be notified of any alterations that are made to
it.

165
Embedded Systems and IoT

GPS technology, when combined with that of the Internet of


Things (IoT), has the potential to be beneficial to the logistics
and distribution industry. Using this brand-new technology,
manufacturers will be able to track deliveries and maintain an
accurate inventory. The Internet of Things combined with the
Global Positioning System helps improve both the quality and
safety of transportation. Before, we were only able to track
which foundation came, left, etc., but now that we can control
the specific current position, transit quality and security have
also been improved. Previously, this was the only information
that was traceable. Because you can engage with the questions
that other users are asking in real time, you may utilize it
without any concerns at all. promoting a transportation service
that is beneficial. Attracting customers whose products are too
big to be carried using more traditional methods is a possibility.
To differentiate yourself in the field of transportation
management, use IoT-GPS. The supply of unique management
ways (such as barcode scanning, managing of arriving at the
base via RFID, etc., commencing picking up of crossing points
on slips, etc.) is one way to differentiate oneself from both rivals
and end users. Reduce the amount of money that is spent on
personnel management. Employers have the ability to obtain
insight into the "what? who? where?" of their operations by
providing employees with GPS trackers. Employers can then use
this data to construct attendance and safety management
systems that are more effective. The old method of using time
cards, in which workers' attendance is stamped manually, has
been replaced by the use of GPS transmitters, which offer
accurate time and real-time location information that may be
used for attendance and attendance management.

166
Embedded Systems and IoT

This is in contrast to the previous method of using time cards.


Even for tasks that entail frequent direct bounce, like as sales and
delivery, it is simple to engrave out and about from a mobile device.
This includes the ability to engrave barcodes. If an employee runs into
troubles, they may use the geolocation data to hunt for other
employees in the vicinity and promptly send them over to help.

4.7 GSM modules

The "Internet of Things" (IoT) is the meeting point of the


physical and virtual worlds. The term "Internet of Things" is
often shortened to "IoT." This area of technology has grown in
popularity in the last many years. Another definition of the term
is the network of physical objects, or "things," that have been
embedded with various technologies such as sensors and
software to allow them to communicate and share data with
other online devices and systems. Numerous internet-of-things
(IoT) devices are available, including the ESP8266, GSM/GPRS
Module, and ESP32.

4.7.1 GSM/GPRS Module

A.K.A. "Global System for Mobile Communication" and


"General Packet Radio Service," respectively, are the acronyms
that describe these two networks. One such standard for mobile
telephone networks is the Global System for Mobile
Communications, more often known as GSM. One of the many
enhancements to the GSM Network is the General Packet Radio
Service (GPRS). A built-in feature of the GSM Network, GPRS
provides an efficient method of data transfer utilising the same
resources as the GSM Network itself.

167
Embedded Systems and IoT

4.7.2 AT commands for GPRS Module

AT commands are instructions that are used to operate a


modem. AT is an acronym for Attention, which is the full name
of the command.

168
Embedded Systems and IoT

We are able to get the status of the GSM/GPRS module as well


as its feedback by using AT commands. In addition to this, it
may be used to establish a connection with any URL, after which
data transfer will take place.

4.7.3 IoT using GSM/GPRS Module

When using a GSM/GPRS Module, there are three crucial


components that must be present.

Figure 4.14: IoT using GSM/GPRS Module.

• Sensor: It determines the values of the particular


parameters that are specified in the datasheet. For
instance, the DHT11 determines the Temperature and the
Humidity of the surrounding air.
• Microcontroller: It gathers the information from the
sensor, analyses that information, and then transfers the
processed and analyzed information to the web server via
an Internet of Things device.
• GSM/GPRS Module: It makes it possible to establish a
reliable connection with a web server such as Thingspeak,
Amazon Web Services, or another similar service.

4.8 Open Platform (like Raspberry Pi)

The Raspberry Pi is a single-board computer that was created


with teaching, tinkering, and do-it-yourself projects in mind.

169
Embedded Systems and IoT

The Raspberry Pi Foundation in the United Kingdom was the


organization that pioneered the usage of Raspberry Pi, which is
now extensively used by both amateurs and experts all over
the globe. More highlights on Raspberry Pi:

• Because of its cheap cost, low power consumption, and


small form factor, the Raspberry Pi is an excellent choice
for a wide range of applications.
• The most common applications for this technology are
media centers, web servers, game consoles, and robots.
• The Raspberry Pi is equipped with a Broadcom System-
on-Chip (SoC), which has an ARM CPU, RAM, storage,
GPIO (general-purpose input/output) pins, and a variety
of ports, such as USB, Ethernet, HDMI, and Wi-Fi.
• It is compatible with a wide variety of operating systems,
such as Raspbian, Ubuntu, and others, and it offers
support for a wide range of programming languages, such
as Python, C++, and Scratch.
• The Raspberry Pi components consist of the board, a
power supply, a microSD card that may be used for
storage as well as the operating system, an optional
display, and a variety of peripherals such as a casing, a
keyboard, a mouse, and other items.
• The Raspberry Pi computer may be linked to a wide
variety of sensors, actuators, and modules, which enables
it to be used in the creation of interactive projects and
investigations.
• Raspberry Pi is an inexpensive single-board computer that
may be used for a variety of purposes across a wide range
of industries, including education, research,
entertainment, and many more.

170
Embedded Systems and IoT

4.9 Raspberry Pi Architecture

Figure 4.15 Raspberry Pi Architecture

With a 32-bit ARM processor, which is a kind of CPU that is


often used in mobile devices, the Raspberry Pi delivers a strong
punch in a compact size.

• The Raspberry Pi has an architecture known as RISC,


which stands for Reduced Instruction Set Computing.
This design provides simplified instructions, lower power
consumption, and quicker processing.
• The clock speed of this powerful CPU is 1.2 gigahertz, and
it is backed by a Broadcom BCM2835 System-on-Chip
(SoC).
• Fans of graphics-intensive applications, such as movie
playback and gaming, often incorporate a powerful
VideoCore IV GPU that is able to decode 1080p video at
30 frames per second.

171
Embedded Systems and IoT

The Raspberry Pi design includes a memory subsystem that has


1 gigabyte (GB) of random access memory (RAM).

• The RAM is shared between the ARM CPU and the GPU,
and the proportion of each may be customized via the
software settings.
• In addition, the operating system and all user data are
stored on a microSD card that may be inserted into the
slot.
• In addition to a variety of input/output (I/O) ports, the
Raspberry Pi is equipped with 40 GPIO pins, often known
as general purpose input/output pins. These pins make it
possible to connect the Raspberry Pi to a variety of
sensors, actuators, and other devices.

4.10 Programming

Python programming language

Python is a high-level programming language that is used for


web development on the server-side to construct a variety of
online apps. In addition to this, it is also used to interface with
databases in order to alter the data that is stored in the database.
Python is a programming language that has an easy-to-
understand syntax that is also simple to create, but the
indentation is something that must be carefully considered
while using Python. The integrated development environment
(IDE) for the Python programming language known as Thonny
is compatible with all operating systems, including Windows,
macOS, and Linux variants in addition to the Raspberry Pi.

172
Embedded Systems and IoT

Raspberry Pi

A Raspberry Pi is a kind of single-board computer that may be


implemented in a variety of applications, including those
involving robotics and automation. The Raspberry Pi is
compatible with a variety of operating systems, although the
"Raspberry Pi operating system," which was developed by the
Raspberry Pi foundation, is the one that is recommended for
use. The MU editor and Thonny are only two of the several
integrated development environments (IDEs) for Python that
are included with the Raspberry Pi operating system. We have
a variety of programming options available to us for the
Raspberry Pi thanks to Python.

4.10.1 Basics of the Python Programming language

The syntax of each programming language is unique when


compared to the syntax of other programming languages;
hence, the primary goal is to become proficient in the syntax of
the particular programming language. The Python
programming language is easy to learn, and in this part, we
will go over some of the fundamental commands that are used
in the Python programming language.

Printing a string:

We have the option of printing the strings by first saving them


in the variables, and then we also have the option of printing
the strings directly by using the print command. Either way, we can
print the strings. Both are taken into consideration. First, we will
print the "Hello! Welcome to LinuxHint" message by putting it in the
"Welcome" variable, and then, using the print command in Thonny
Editor, we will print the identical text directly:

173
Embedded Systems and IoT

Welcome = “Hello! Welcome to LinuxHint”


print (Welcome)

The output is:

The following will be shown as a result of running the


command:

Now that the string has been formatted, we will print it out
without saving it in the variable:

Using loops in Python:

The for loop and the while loop are both available to us, just as
they are in other programming languages. The syntax for the
for loop in the Python programming language is as follows:

operating_system=[“Linux”,” RaspberryPi”,” Windows”]


for x in operating_system:
print(x)

The following is what comes out of the for loop in Python that
was just mentioned:

174
Embedded Systems and IoT

The following is what comes out of the for loop in Python that
was just mentioned:

i=1
while(i<5):
print(i)
i=i+1

The following is what comes out of the while loop in Python:

Using conditional statements in Python:

Another fundamental component of programming is the use of


conditional statements, which allow the output of the program
to be contingent on the fulfillment of certain criteria. These
conditional statements include both switch statements and if-
else statements in their construction. Statements using if and
else are going to be shown with the assistance of the following
Python program since they are the most fundamental and
practical option. In any integrated development environment
(IDE), including the Thonny IDE, which we are using, copy
and paste the Python code that is described below:

x=5
if x > 0:
print("Number is greater than zero")
else:
print("Number is less than zero")

175
Embedded Systems and IoT

4.10.2 Programming Raspberry Pi using the terminal

To develop, compile, and execute Python programs, we may


also utilize the terminal. To do so, we will first generate a file
using any text editor and name it using the extension ".py." In
this example, we will create a file with the name
"LinuxHint.py" by issuing the following command:

$nano LinuxHint.py

Type the following script to display the “Welcome to


LinuxHint”:

print(“Welcome to LinuxHint”)

You may quit the editor after saving the file using the nano
editor's shortcut key, which is CTRL+S, and then execute the
script of the file by entering the following command:

$python LinuxHint.py

4.11 Interfaces

Data may be sent over the Raspberry pi via its Serial, SPI, and
I2C interfaces.

176
Embedded Systems and IoT

Serial

Receive (Rx) and transmit (Tx) pins are included on the


Raspberry Pi's Serial interface so that it may communicate with
other serial devices.

SPI

The Serial Peripheral Interface, or SPI, is a synchronous serial data


protocol that is used for connecting with one or more devices that are
considered to be peripheral. There are five pins on the Raspberry Pi
that are used for the SPI interface, which are as follows:

• MISO (Master in slave out): The master line for


transmitting data to the various peripherals.
• MOSI (Master out slave in): Line used by the slaves to
transmit data to the master.
• SCK (Serial Clock): The clock that is used to synchronize
the data transmission is created by the master.
• CE0 (Chip Enable 0): To activate or deactivate various gadgets.
• CE0 (Chip Enable 1): To activate or deactivate various gadgets.

I2C

You may connect different pieces of hardware to the Raspberry


Pi by using the I2C interface pins. The I2C interface enables
synchronous data transmission with just two pins: the data line
(SDA) and the clock line (SCL).

4.12 Accessing GPIO Pins

Raspberry pi's GPIO pins, also known as general purpose input


and output pins, may function either as inputs or outputs, and

177
Embedded Systems and IoT

they enable the computer to connect to general purpose I/O


devices.

• The Raspberry Pi 3 model B removed a total of 26 GPIO


pins from the board.
• Using these general purpose input/output (GPIO) pins, a
Raspberry Pi may operate a wide variety of external
input/output devices.
• These pins serve as a physical connection point between
the Raspberry Pi and the rest of the world.
• These pins may be programmed according to our
requirements so that they can communicate with devices
from the outside. For instance, if we want to determine
what state a physical switch is in, we may enable any of
the available GPIO pins to function as an input, read the
state of the switch, and then use that information to arrive
at a conclusion. Additionally, we are able to set any GPIO
pin to act as an output in order to control the ON/OFF
state of the LED.
• The Raspberry Pi may connect to the internet by either the
Wi-Fi that is built into the device or with a Wi-Fi USB
adaptor. After successfully connecting the Raspberry Pi to
the Internet, we will be able to exercise remote control
over the devices that are linked to the Raspberry Pi.

Some of the GPIO pins may perform various tasks at the same
time, such as I2C, SPI, or UART, for example. For our
application, we are free to utilize any of the available GPIO pins.

The following picture outlines the GPIO Pins available on the


Raspberry Pi 3:

178
Embedded Systems and IoT

Figure 4.16: Raspberry Pi 3 Model B GPIO Pin Mapping

4.12.1 Pin Numbering

It is important that we establish a GPIO pin that may either be


used as an output or an input. The Raspberry Pi, on the other
hand, offers two distinct options for specifying the pin number,
as follows:

• GPIO Numbering
• Physical Numbering

GPIO Numbering refers to the number on the Broadcom SoC


(System on Chip) whenever pin number is mentioned.
Therefore, whenever we use a GPIO pin, we need to be sure to
take into account the pin mapping. During the process of
Physical Numbering, the term "pin number" refers to the
position of the pin on the 40-pin P1 header on the Raspberry Pi
Board. Counting the number of pins on the P1 header allows us
to easily designate each one as a GPIO, which makes the
preceding physical numbering straightforward.

179
Embedded Systems and IoT

However, we need still take into consideration the pin


configuration diagram that was shown before in order to
determine which pins are GPIO pins and which are VCC and
GND.

4.12.2 Control LED with Push Button using Raspberry Pi

Figure 4.17: Control LED using Raspberry Pi Interfacing


Diagram

Example

Let's go on to the next step, which is to control LEDs by


utilizing a switch that is attached to the Raspberry Pi. For
controlling the ON-OFF state of the LEDs, we are making use
of Python (WiringPi).

180
Embedded Systems and IoT

4.12.3 Control LED using Python

Now, let's use Python on Raspberry Pi to toggle the ON and


OFF states of an LED. The on/off status of the LED may be
controlled by the switch.

Python Program for Raspberry Pi to control LED using Push


Button

4.12.4 Functions Used

RPi.GPIO

Importing the RPi.GPIO package, which has a class that can be


used to control GPIO and allows us to access the Raspberry Pi's
GPIO pins, is required.

181
Embedded Systems and IoT

On the Raspbian operating system, this RPi.GPIO Python


module has already been installed. Therefore, there is no need
for us to install it at an external location. We need to include a
library into our application so that we may make use of Python's
functions for GPIO access. The explanation behind this is as
follows.

import RPi.GPIO as GPIO

GPIO.setmode (Pin Numbering System)

The Pin numbering system, also known as GPIO numbering or


Physical numbering, may be defined with the use of this
function. The GPIO numbering in RiPi.GPIO is determined by
the BCM, but the physical numbering is determined by the
BOARD.

Pin Numbering System = BOARD/BCM

For example, if we utilize pin number 40 of the P1 header as a


general-purpose input/output (GPIO) pin that we have to setup
as an output, then:

GPIO.setup (channel, direction, initial value, pull up/pull


down)

This function is used to set whether the GPIO pin will act as an
input or an output in the system.

182
Embedded Systems and IoT

• Channel: The number of the GPIO pin according to the


numbering scheme.
• Direction: GPIO pins may have their directions adjusted
to either Input or Output.
• initial value: may provide a starting point or value
• pull up/pull down: Adjust the pull up or draw down
mechanism as necessary.

The following are a few instances that illustrate this point:

GPIO.output (channel, state)

Through the usage of this function, the output state of the GPIO
pin may be changed.

• Channel: the number of the GPIO pin according to the


numbering scheme.
• State: The output state of the GPIO pin, expressed as
either HIGH or LOW.

e.g. GPIO.output(7, GPIO.HIGH)

183
Embedded Systems and IoT

GPIO.input(channel)

It is possible to read the value of the GPIO pin by using this


function.

e.g. GPIO.input(9)

4.13 Sending and Receiving Signals Using GPIO Pins

Example:

184
Embedded Systems and IoT

Receive procedure:

• Continue reading the state of pin B, and when it reaches


high, read the status of pin A.
• Record the current state of pin A in a string.
• Continue to pull the status of pin B, and when it becomes
low, go to step 1.

185
Embedded Systems and IoT

It is necessary for the "wait some time" instruction to be at least


twice as long as the pulling speed. If you pull at a rate of one
time per second, for instance, you will need to wait two seconds
before delivering the next bit.

4.14 Connecting to the Cloud

Utilizing a REST API or another interface that is made available


by the cloud service provider, Raspberry Pi is able to upload
sensor data to the cloud. Using a cloud service to store and
analyze sensor data will normally set you back between one
dollar and ten dollars each month. There are a variety of cost-
free solutions accessible, such as Pantry Cloud, which make it
simple to configure a Raspberry Pi and get knowledge about
how to link it to the cloud.

Figure 4.18: Connecting to the Cloud.

4.14.1 Pantry Cloud

Pantry Cloud is a cloud service for storing JSON data that


provides a substantial free tier for users. Signing up with
Pantry Cloud and sending data to it via a Raspberry Pi have
both proven to be quite simple processes for me.

186
Embedded Systems and IoT

Pantry Cloud is an excellent choice for Raspberry Pi


applications that need just a little quantity of cloud storage
space for storing data. Pantry Cloud provides 100 megabytes of
storage space, which is sufficient for around 10 million
temperature readings from the Raspberry Pi Sense HAT (with
the overheads involved with storing them as JSON). Any
device may access the data that has been stored to Pantry
Cloud by the Raspberry Pi as long as it has the API key. When
you initially register an account, the API key will be sent to you
(there is no need for a password). Because of this, it may be
somewhat less secure than some of the other cloud storage
choices available here, such as those that demand
authentication (using a username and password) before
allowing users to access with the cloud data. At least in my
experience, one of the benefits of using a cloud service that
does not need a password is that it is much simpler to connect
with that service. To setup Pantry Cloud on Raspberry Pi:

• On their website, here, provide an email address to get a


free API key (there is no need to provide a password).
• On your Raspberry Pi, launch Python and then import the
json and requests libraries.
• To connect with the Pantry Cloud REST API on this page,
follow the instructions provided (you may convert the
code to Python to get additional helpful examples).

Pantry Cloud may also be used to deliver control and


command data to a Raspberry Pi. This functionality is
available. The Raspberry Pi may be programmed to read the
instructions and settings saved by another computer in the
cloud, and then it could be used to control other devices.

187
Embedded Systems and IoT

Using Pantry Cloud with your Raspberry Pi for these reasons:

• Generous free tier


• Easy to set up (no password required)
• Easy to send data to

4.14.2 Cloud4RPi

Cloud4RPi is a cloud service that was developed specifically to


be compatible with Raspberry Pi. Using their web-based
interface in the cloud, it allows you to access data and exercise
control over your Raspberry Pi. Their website will show a
dashboard with data coming from a Raspberry Pi, in addition
to buttons and inputs that may be used to remotely operate a
Raspberry Pi. Everything is carried out in the here and now.
The following are examples of projects that might benefit from
using Cloud4RPi:

• Home automation
• Gardening automation
• Remote control of a machine

Cloud4RPi is helpful if you require a real-time dashboard view


of whatever it is that your Raspberry Pi is monitoring or if you
need to remotely operate anything else. When is it best to
refrain from utilizing Cloud4RPi: It is necessary to get a large
quantity of data from a wide variety of various devices. It is
possible for a single device to combine many data streams into a
single transmission packet; but, if multiple devices are
communicating with the cloud at the same time, this becomes an
extremely difficult task. It is necessary to do research on
historical data.

188
Embedded Systems and IoT

When I tried to extract and analyze data that had been gathered
over a period of time in order to analyze a pattern in anything, I
realized that it was a little difficult to do so. It is doable; the
process is simply not as straightforward as it is with some other
providers.

4.14.3 Microsoft Azure IoT

Microsoft's Internet of Things (IoT) technology may be


integrated into the Azure cloud service through a set of services
known as Azure IoT. These services are supplied by Microsoft.
As is the case with many other Microsoft products, it may be
used by individuals working on a project at home all the way up
to operating significant industrial applications (such as factory
monitoring and chemical refinement processes). This flexibility
makes it a very versatile tool. Utilizing Azure IoT with
Raspberry might be a smart move for the following reasons:

• Projects that are work-related or industrial in nature, and


for which you can anticipate that they will generate
sufficient revenue to warrant the time and effort required
to set up Azure IoT.
• A working model of an idea that you want to implement
in a commercial or professional setting (for example, a
tracking system for vehicles).
• Getting familiar with how Azure operates and how it can
communicate with the Internet of Things

A free trial of Azure, which incorporates Internet of Things


functionality, is available from Microsoft. It seems that after
attending a Microsoft conference (which offered a little bit of
free Azure credit), it revoked my free trial and requested that I
pay for every small amount of data consumed.

189
Embedded Systems and IoT

UNIT V

APPLICATIONS DEVELOPMENT

5.1 Complete Design of Embedded Systems

The term "Embedded Systems" is used to describe various


electrical items that are run by microcontrollers. They are
equipped with computational logic, memory, communications,
and input/output peripherals, and their typical purpose is to do
a certain task. An example of an embedded system is a washing
machine. The same may be said for your smartphone, the
security access system, the vending machine, and potentially
even other 'intelligent' home gadgets. The process of
constructing embedded systems from scratch is known as
embedded systems design, and it involves the collaboration of
hardware and firmware designers. This requires the use of
printed circuit board (PCB) design, which is the process of
connecting the required components to create working circuits.
After the firmware has been created, it is subsequently
programmed into the microcontroller so that the electronics may
be brought to life.

5.1.1 Embedded Systems Design Cycle

If you don't go into it with a solid game plan, designing


embedded systems may be a very challenging endeavor. The
design process, on the other hand, may be broken down into
more manageable phases with the aid of a systematic
methodology, which enables more effective planning, execution,
and cooperation.

190
Embedded Systems and IoT

Figure 5.1: Creating schematic diagrams is one of the stages of


embedded systems design.

5.1.2 Analysis of Requirements

The first essential step in the design of embedded systems is to


compile, investigate, and transform the product requirements
into specifications. You will need to make a detailed list of
every need and discuss it in depth with either your boss or
your customer.

191
Embedded Systems and IoT

There are more considerations besides the number of inputs


and outputs as well as the logic diagram. In order to determine
the appropriate specifications for the embedded system, it is
helpful to investigate the utilization as well as the operating
circumstances. An embedded system that must consistently
perform in adverse environments is quite different from one
that just functions in an indoor setting.

• Schematic: After the needs have been transformed into


specifications, the designer of the hardware may start the
process of creating the schematic. At this point in the
process, the design team will be responsible for selecting
the appropriate microcontroller as well as the other
components for the circuit. A microcontroller usually
serves as the embedded system's central processing unit.
Before making any final choices, it is important to pay careful
consideration to a variety of factors, including processor speed,
memory capacity, peripherals, amount of power used, and
cost.
• PCB: After finishing the schematic, the next step in
developing the embedded system is to design the printed
circuit board (PCB). PCB design is a sensitive process, and
the designer is responsible for implementing industry
standards to ensure that the final product is reliable,
functional, and producible. When dealing with a high-
speed microcontroller and/or mixed-signal circuitry, PCB
design might become more difficult. systems that operate
at high speeds may give rise to issues such as
electromagnetic interference (EMI), and mixed-signal
systems need for appropriate ground separation and
noise-coupling mitigation methods.

192
Embedded Systems and IoT

• Prototype: After ensuring that the PCB layout is error-free


and passes the DRC test, the next step is to complete the
prototypes of the device. This is not a problem since there
are many different providers that offer low-volume
prototype.
• Firmware Development: The design of an embedded
system involves more than just the hardware component
alone. In order for everything to function properly, the
designers of the firmware need to "bring the hardware to
life" with the software. Utilizing pre-existing driver
libraries and the sample code provided by the
manufacturer may help speed up the process. These are
both available from the manufacturer. However, writing
firmware is a time-consuming process, and even a single
line of code that is entered in the wrong location might
result in many hours spent troubleshooting the program.
• Testing & Acceptance: It is required that the design of an
embedded system succeed in a battery of demanding tests
before it can be manufactured or put into use. In addition
to passing the functionality test cases, the circuit has to be
evaluated for its reliability, especially when it is working
close to its limitations.

5.2 Development of IoT Applications

Figure 5.2: Development of IoT Applications

193
Embedded Systems and IoT

5.2.1 Define the requirements for the application

Defining the purpose of your application and the parameters it


will operate inside is an essential part of the process of
designing an Internet of Things application. This requires you
to distill your goal down to its most essential components.
Among the aims may be found:

• Movement or position may be tracked in real time, giving


consumers the ability to monitor where their gadgets are
located at all times (for example, electric vehicles owned
by a delivery chain).
• Keeping an eye on things like temperature and humidity
levels, which may assist with the management of heating
and cooling systems in places like hospitals
• Utilizing sensors at industrial operations (such as
refineries) to detect dangerous gases such as carbon
monoxide, methane, and hydrogen sulfide

The functionality that you desire will be included as part of the


scope of your application. This might involve the following:

• Device Management
• Dashboarding
• Device to Mobile Communication
• Remote Shell
• Over-the-air updates
• Device Shadow
• Metadata management
• Data visualization

194
Embedded Systems and IoT

5.2.2 Choosing the right hardware

The requirements of your project will determine the sort of


hardware you use. It could be anything from sensors to GPS
trackers to wearable technology. However, it is essential to
choose hardware that is dependable and applicable to the work
that you are doing. Take a look at the many kinds of sensors
that are offered. If you are designing smartwatches, for
instance, you will want oximeters, pedometers, and pulse
monitors in order to complete your work. But in order to
construct intelligent cars, you will want a variety of sensors,
such as a global positioning system (GPS) or an altitude
monitor. You will need to locate sensors that are suitable for
your gadget, and the sensors you choose will depend on
whether it is designed for consumer use, industrial usage, or
automobiles. Because industrial and automotive sensors are
responsible for more delicate duties than those found on
consumer electronics, they need a far higher level of reliability.
After you have decided which sensors to use, the next step is to
examine the overall hardware architecture of the device in
order to determine whether or not it requires microcontrollers
or microprocessors in order to process the data. It is crucial to
get these details perfect, since replacing your gear in the future
will be time-consuming and costly. Although the details may
seem daunting, it is important to get them properly.

5.2.3 Find the right connectivity protocols

You have the option of using a variety of network protocols,


including WiFi, 2G, 5G, Bluetooth, LoRa, NB-IoT, or Zigbee,
among others. You need to choose the appropriate connection
channels in accordance with the devices you are using and the
resources that are at your disposal.

195
Embedded Systems and IoT

The use of WiFi for data transmission is an option for you to


consider if, for instance, the majority of your device use takes
place in a residential or commercial setting. On the other hand,
you may want to go with GSM if your gadgets are going to be
moving around a lot or staying in isolated areas. Likewise, a
companion device like a wristwatch might utilize Bluetooth to
communicate with other devices. It is vital to choose the
appropriate protocol for the use cases that you have in mind
since, similar to the situation with hardware, it is doubtful that
you will be able to reverse this choice in the future. This will
also have an impact on the cost structures you use. When you
add GSM connection to your device, you will be required to
pay for cellular data, however when you use WiFi or Bluetooth,
you won't have to worry about these costs.

5.2.4 Ensure the firmware is well equipped

The software that is installed on your device and is responsible


for its operation is referred to as the firmware or the device-
side software. It is crucial to make sure that your firmware is
properly equipped; otherwise, you may end up losing data and
spending a lot more money than required on the storage and
transfer of data. This can be avoided by ensuring that your
firmware is well prepared. Check to ensure that the following
features are included in your firmware:

The retrying of data pushes on network disconnections helps


ensure that data is not lost in the event that connectivity
difficulties arise. Persistence of data on the disk even in the
absence of a network for extended amounts of time. This is an
imperative must if you want for your devices to be mobile or to
be situated in a distant area.

196
Embedded Systems and IoT

Processing data in batches and compressing it may help save


expenses. The cost of your data may add up over time, which
can significantly reduce your return on investment. You are
able to protect sensitive data by encrypting it using TLS, which
is a protocol that is widely used. Downloads of over-the-air
updates that are reliable will guarantee that regular upgrades
take place, which will ultimately increase the device's efficiency
and overall performance over time.

5.2.5 Pick the right cloud platform

If you choose the correct IoT platform, it will provide you with
the tools you need to build an application that fulfills your
requirements. In order to choose an Internet of Things platform
that meets your needs, you will need to check for the following
characteristics:

• Uptime
• Data security
• Debugging
• Feature stability
• Security
• Migration capabilities
• Connectivity, and
• Scalability

5.2.6 Embedded System Design Examples

• Automatic chocolate vending machine (ACVM)


• Digital camera
• Smart card
• Mobile phone

197
Embedded Systems and IoT

Automatic Chocolate Vending Machine (ACVM)

When a kid puts money into the ACVM, the machine is


supposed to give the youngster some chocolate as a reward.
This is the design purpose of the machine.

Design Steps

The following constitute a significant portion of the design


phases.

• Requirements
• Specifications
• Hardware and software functioning.

Requirements

When a youngster puts a quarter in the machine and chooses


the kind of candy that he or she would like to buy, this is
known as "self-service."

Inputs

• Coins, user selection.


• An interrupt is generated at each port whenever a coin is
inserted.
• A separate notification is sent to each port.

Outputs

• Chocolate
• Refund
• A message is displayed on LCD like date, time, welcome
message.

198
Embedded Systems and IoT

System Function

• The youngster gives instructions to the system through a


graphical user interface, telling it the kind of chocolate the
child would like to buy.
• In which the graphical user interface is comprised of an
LCD, a keypad, and a touch screen.
• When a youngster slips a coin into the machine, the
machine will provide chocolate to the child if the number
of coins input is more than the price of the chocolate being
purchased. The money is given returned to the user via
the ACVM machine.
• The proprietor of the ACVM is able to monitor client
locations by employing the utilization of a Universal
synchronous bus.

5.2.6 Design Metrics

Power Dissipation

The design has to take into account the size of the display as
well as the mechanical components.

Process Deadline

A timer has to be configured so that the automated coin


vending machine (ACVM) responds within a few seconds
whenever the kid enters a coin by delivering the chocolates and
giving a refund if there is an excess. For instance, if the reaction time
is 10 seconds, the ACVM should provide the chocolate and refund
the money if there is an excess within the first 10 seconds after the
kid enters the coin and makes a request for chocolate. If there is an
excess, the child should be refunded the money.

199
Embedded Systems and IoT

Specifications

When the youngster puts the coin in the ACVM system, the
following information is obtained. The coins are separated into
their respective piles according to the ports that are available:
Port1, Port2, and Port5. An interrupt is created by the port
whenever coins are received, and this interrupt is then
delivered to read the current amount's value and raise it.

Figure 5.3: Automatic chocolate vending machine

Various messages, including welcome, the current time, and


the fee, are shown on an LCD that is located here. There is a
port delivery that the chocolates are brought to in order to be
collected.

200
Embedded Systems and IoT

Hardware

The following is a list of hardware specs for the ACVM


hardware architecture:

• Microcontroller 8051
• 64 KB RAM and 8MB ROM
• 64 KB Flash memory
• Keypad
• Mechanical coin sorter
• Chocolate channel
• Coin channel
• USB wireless modem

Software of ACVM

It is necessary to write many programs in a way that allows


them to be reprogrammed in RAM or ROM in the event that
this becomes necessary.

Figure 5.4: Hardware architecture of ACVM

201
Embedded Systems and IoT

• The Price of Chocolate Has Gone Up


• Informational LCD displays will be updated regularly.
• Modifications to the machine's capabilities.

An Embedded System is a system that combines hardware and


software to carry out a certain task. Microprocessors and
microcontrollers come in two distinct varieties. For a developer
to successfully build and implement an embedded system, they
must first take into account a number of design limitations and
standards.

5.3 Home Automation

Automatically managing your house's electronics is what we call


"home automation." These gadgets can be managed from afar
thanks to their Internet connectivity. Instead of manually
controlling each item through an app or voice assistant, home
automation allows them to trigger one another.

Figure 5.5: Home Automation

You may program your lights to turn out at the same time you
do, or you can set your thermostat to begin blasting the air
conditioner an hour before you get home from work to avoid
coming home to a steamy house.

202
Embedded Systems and IoT

Automating your home not only makes your life easier, but it
may also save your utility costs. Security cameras and systems,
which are examples of Internet of Things devices, may improve
home security.

Internet of Things vs. Home Automation

The term "Internet of Things" (IoT) is used to describe any item


that can be controlled remotely via the internet, such as a smart
light bulb. There is no Internet of Things gadget that can't be
programmed to automatically trigger another. While the
Internet of Things (IoT) describes the connected gadgets
themselves, home automation describes the ways in which such
gadgets may be used to make people's daily lives simpler.

Different communication protocols, including as Wi-Fi,


Bluetooth, and ZigBee, are used to link the many devices that
make up a home automation system to the internet. This
network is what makes home automation operate. Remote
control of the gadgets is possible thanks to electronic interfaces
in the form of controllers.

These controllers might be voice assistants like Alexa or Google


Assistant, or they could be apps. The user of many of these
Internet of Things devices may get information about the
device's surroundings by making use of the device's sensors,
which detect changes in motion, temperature, and light.
Actuators are physical mechanisms such as smart light switches,
motorized valves, or motors that enable objects to be controlled
remotely. The user activates actuators in order to make changes
to the device that are manifested in its physical form. The home
automation system functions on all three levels:

203
Embedded Systems and IoT

Monitoring

Monitoring allows users to do checks on their own equipment at


a distant location by using an application. A live stream from a
smart security camera, for instance, is viewable by unauthorized
parties.

Figure 5.6: Nest Hello and Google Home Hub

Control

Operate indicates that the user may operate these devices


remotely, such as turning a security camera to observe more of
a living room. Control also refers to the ability to change
settings.

Figure 5.7: Amazon Echo Show and Box

204
Embedded Systems and IoT

Automation

Lastly, automation involves putting up equipment in such a


way that they may trigger one another. For example, an armed
security camera might set off an intelligent alarm anytime it
senses motion.

Figure 5.8: Amazon Alexa and Amazon Cloud Cam

5.3.1 Home Automation System Components

Some home automation systems do need hubs, however some


mobile apps can connect directly to a router, which can then
connect directly to an Internet of Things device. Naturally, it is
preferred when there is no hub, since it is merely an extra
expense on top of the cost of the IoT device itself. However, in
certain cases, it may be necessary to include a hub.

Remote Control

The most distinguishing feature of home automation is remote


control, which can be exercised through a smartphone
application or a voice assistant. This control may be exercised
from a distance.

205
Embedded Systems and IoT

• Mobile Application: The smartphone application gives


consumers the ability to exercise real-time control over the
gadgets they have connected to their homes, such as
turning off the exterior lights or releasing the parking
brake on their automated garage door. In addition, users
can use the app to create schedules, scenes, and groups of
Internet of Things devices, as well as tweak device
settings, such as changing the color of the lights in their
living room to the ideal shade of blue. The vast majority of
the Internet of Things devices that we've tested come
equipped with applications for both the Android and iOS
operating systems, which makes them suitable for use
with a wide variety of mobile phones and tablets.
• Voice Assistants: Imagine voice assistants as the icing on
top of the dessert that is home automation. You can use
your voice to manage devices, such as disarming a
security system as you enter in the front door, seeing the
footage from your video doorbell on your Echo Show
device, or setting a timer on a smart speaker while your
hands are full with kitchen utensils. This is made possible
by voice assistants, which allow you to utilize your voice.
Alexa, Google Assistant, and Siri are the three most
common voice assistants that are compatible with Internet
of Things devices.
• Alexa: The Echo Show and the Echo Dot both come
equipped with Amazon's speech assistant, which is
known as Alexa. Alexa is the speech assistant that has
been incorporated into the most smart home products
produced by firms such as SimpliSafe, Ring Alarm, and
Cove.

206
Embedded Systems and IoT

Figure 5.9: Amazon Alexa

● Google Assistant: As you may have guessed, Google


Assistant is the company's voice assistant platform. In spite of
the fact that Google Assistant does not have as many "skills" or
"actions" as Alexa does, it has been shown to be the most
accurate voice assistant when it comes to accurately
interpreting and responding to questions. You will need either
a smart speaker or a smart display in order to use Google
Assistant; to get started, see our evaluation of the Nest Mini or
our review of the Nest Hub.

Figure 5.10: Google Nest Mini

207
Embedded Systems and IoT

● Siri: Apple's voice assistant Siri is built into the iPhone


and acts as a virtual personal assistant. Even while Siri has a
worldwide market share of 35 percent for voice assistants,
which is much higher than Google Assistant's nine percent and
Alexa's four percent, respectively, there are not a lot of Internet
of Things devices that are compatible with Siri. Instead, the
voice assistant is mostly used on iOS devices like iPhones and
iPads, in contrast to home automation systems, which are
dominated by digital assistants like Alexa and Google
Assistant.

5.3.2 Cloud Computing with Home Automation

Rather of basing home automation systems off of a separate IP


address or high-end computer, many systems are now built on
the cloud, which is not only more cost effective but also simpler
to operate.4 The Nest cameras, for instance, do not have slots
for micro-SD cards, which would have enabled video to be
saved locally and provided further redundancy. Rather, every
piece of recorded content is uploaded to the cloud on a
continuous basis, and the only way to see it is by subscribing to
the Nest Aware service. The use of cloud computing is quite
common on the Internet nowadays, and Internet of Things
devices are not an exception to this trend.

Control Protocols

The term "control protocol" refers to the method through which


Internet of Things (IoT) devices connect to the internet and to one
another; if you imagine IoT devices as individuals, you may think of
the protocol as their shared language. Devices, much like people, are
able to communicate using a variety of languages, sometimes known
as protocols, including the following:

208
Embedded Systems and IoT

• WiFi: Your Internet of Things device will utilize the


standard Internet connection that is supplied by your
Internet Service Provider if it is controlled through WiFi,
which is by far the most popular control protocol. Even
while this does not need an extra hub, you should be
aware that it may slow down your online browsing rates.
This is particularly true if you are simultaneously setting
up a large number of different Internet of Things devices.
• Z-Wave: You don't want to tinker with the WiFi in your
house, do you? Z-Wave is a wireless technology that will
not interfere with your WiFi; rather, it works on low
power at 908.42 Mhz in both the United States of America
and Canada.
• ZigBee: ZigBee is a mesh network and universal
language, much to Z-Wave, that enables Internet of
Things devices to interact with one another.
• Thread: Thread is yet another low-power, wireless mesh
networking technology that is based on an open standard
for IP addresses; it enables Internet of Things devices to
communicate to one another as well as the cloud.
• Bluetooth: Last but not least, Bluetooth is yet another
mesh technology that gives consumers the ability to
manage and monitor objects connected to the internet of
things as well as automate processes.

A house is considered to be "smart" if it has automated gadgets


that are linked to the Internet of Things and mobile apps. Users
have control over a variety of aspects of their homes by using
these Internet of Things devices, including the lighting, the
security systems, and the appliances. In spite of the fact that
more and more houses are being designed with automation

209
Embedded Systems and IoT

from the very beginning of the building process, strictly


speaking, a smart home is defined as any home that has both
an internet connection and internet of things devices.

Set Up Home Automation

The process of installing a home automation system is really


much less difficult than it would first seem to be. You have the
option of going with the flow and purchasing a smart home
device that seems like it would be a good fit for you, or you can
set up your smart home in a more methodical manner by
following these simple steps:

Smart home ecosystem

First things first, choose the "smart home ecosystem" that you
wish to participate in, which most likely refers to either Amazon
or Google's offerings. This will define the voice assistant you
choose, which in turn will determine which Internet of Things
devices are compatible with your system. Sticking to one or the
other voice assistant is something we encourage since it may be
difficult to keep track of which one to use with which Internet of
Things device.

Figure 5.11: Google Nest Mini and Box

210
Embedded Systems and IoT

Although it is possible to utilize goods that are compatible with


both Alexa and Google Assistant, doing so may be rather
confusing. After you have selected the voice assistant that best
suits your needs, the next step in setting up your home
automation system is to get a smart speaker or display that is
compatible with your chosen voice assistant.

• Control protocol: Next, determine the communication


protocol you want your devices to use, such as WiFi, Z-
Wave, ZigBee, or one of the many others available. WiFi
will be your most convenient choice if you are just getting
started with a smart home since the majority of Internet of
Things devices are compatible with WiFi.
• Types of products: Next, go around the house one room
at a time and determine which kinds of goods you will
need in each space, such as safety cameras, light bulbs,
locks, coffee makers, and other such items. The purchase
guide that we provide below might be of assistance!
• Brands: The next step is to conduct some research into the
most reputable smart home firms; the reviews on our
website include the most well-known brands, such as
Ring, Nest, SimpliSafe, Alder Security, and many more.
• Devices: It is now time to really go out and purchase your
Internet of Things devices. Considering that many
retailers give price reductions for bigger quantities of their
products, we strongly advise making bulk purchases.
• Installation: It is now time to actually install the Internet
of Things devices in the locations that you have chosen.
The vast majority of Internet of Things devices enable do-
it-yourself (DIY) installation, which means you may do it
for free on your own. However, certain businesses, such

211
Embedded Systems and IoT

as Vivint and ADT, need professional installation for their


smart security systems. Because of this, you should be
sure to figure in the cost of installation, if there is one, to
your final cost.
• Customize settings: You've done the necessary research,
shopping, and installation to have your house outfitted
with Internet of Things (IoT) gadgets. What should I do
now? The fun can now begin in earnest since you can now
personalize the devices to your specifications, which may
include putting them on schedules, adjusting the
brightness of the lights, or having the gadgets trigger one
another. Let's speak about the Internet of Things devices
that are genuinely for sale on the market today first, and
then we'll discuss these aspects in more detail later on.

5.3.3 Home Automation

We've seen everything from smart medical alert systems to


smart microwaves over the last several years as more and more
products become accessible in the form of Internet of Things
technology. The following is a list of the many devices that may
be purchased, along with some tips on what to look for in each.

Figure 5.12: Internet of Things Devices

212
Embedded Systems and IoT

There were 15 billion Internet of Things devices in use in 2015.


By the year 2020, this figure has skyrocketed to an astounding
200 billion Internet of Things devices and counting. We are
unable to provide a list of all of the Internet of Things devices
that are now available; nevertheless, the following are some of
the more common ones:

• Lights: The installation of smart lights, which are one of


the Internet of Things devices that are more reasonably
priced, may render the process of modifying your
illumination more user-friendly and individualized than it
has ever been before. The majority of smart lights allow us
to alter their color, reduce their brightness, program them
to follow schedules, and even have them blink in time to
the rhythm of our music. That is superior than a light that
costs three dollars from the hardware store.
• Thermostats: With the help of a smart thermostat, we are
able to save money on our heating and cooling bills by
remotely adjusting the temperature in our house and also
by programming it to follow a schedule.
• Locks: The security of our property was significantly
improved after we installed smart locks. They closed
themselves as soon as we stepped outside the house, but if
we wanted to allow someone in while we weren't there,
we could either unlock them using the app or give our
visitors a temporary password. This was a far more secure
option than hiding a key beneath the welcome mat.
Investigate your choices with our recommendations for
the top smart locks.
• Video doorbells: In their most basic form, video doorbells
are just outside cameras that may or may not be plugged

213
Embedded Systems and IoT

into an existing doorbell system, depending on whether or


not you already have one. We were informed anytime
either the camera or the doorbell identified motion or a
person, depending on the capabilities of the artificial
intelligence in question in the camera.
• Security cameras: You can check in on what's happening
at home using a mobile app connected to your security
camera, and depending on the camera's artificial
intelligence, it may also alert you when it detects motion
or individuals.
• Security systems: A motion sensor, an entrance sensor,
and a glass break sensor are the three types of sensors that
are often included in sophisticated security systems. These
sensors alert you to motion, doors and windows opening
and shutting, and, you guessed it, glass shattering.
• TVs and remotes: Google, please ratchet up the volume
by ten percent! We have smart TVs like Apple TV, Fire
TV, and Chromecast in our house. These devices may
either be incorporated into smart TVs or hooked into the
USB connection of a standard television.
• Speakers: It is common practice to use smart speakers as
the foundation for a smart home ecosystem since they
make it possible to provide speech commands through
voice assistants. For instance, when we tell our
Chromecast to pause, we are not speaking directly to the
Chromecast device that is hooked into our TV; rather, we
are speaking to our Nest Mini, which is equipped with the
speaker and microphone required for us to interact with
Google Assistant. When we tell our Chromecast to pause,
we are not speaking directly to the Chromecast device that
is plugged into our TV.

214
Embedded Systems and IoT

• Displays: The only difference between smart displays and


smart speakers is that the latter have built-in voice
assistants while the former feature screens and, in many
cases, cameras. This enables smart displays to provide
additional entertainment choices and to facilitate video
conferencing. Because the price of smart displays is often
much higher than that of smart speakers, we would
advise you to go with a smart speaker rather than a smart
display if you are working with a limited budget.
• Medical care: There are a variety of medical alert systems
available that are linked to WiFi. Many of these systems
incorporate fall detection, which is useful if you have an
elderly relative or friend that you would want to care for
and watch remotely.
• Other IoT products: We have seen everything from smart
plugs, scales, smoke alarms, and carbon monoxide
detectors to microwaves that are equipped with Alexa.
While the primary emphasis of this website is on
intelligent home security systems and cameras, home
automation encompasses a much wider range of
technologies and includes Internet of Things devices that
fall into a variety of different categories. In addition to
that, you may deactivate your smoke alarm using your
smartphone, which is an extremely handy feature.

5.4 Smart Farm

The term "smart farming" refers to the management of farms


via the use of current information and communication
technology to improve both the quantity and quality of the
goods produced while simultaneously reducing the amount of
manual work needed.

215
Embedded Systems and IoT

The following are examples of technology that are now


accessible to farmers:

• Sensors: control of the soil, water, light, and humidity as


well as the temperature
• Software: software solutions that are customized to
target certain kinds of farms or Internet of Things
platforms that are not application specific
• Connectivity: cellular, LoRa
• Location: GPS, Satellite
• Robotics: Autonomous tractors, processing facilities
• Data analytics: standalone analytics solutions, data
pipelines for downstream solutions

Figure 5.13: Smart farming

216
Embedded Systems and IoT

Farmers who are equipped with such instruments may monitor


the state of their fields and make strategic choices for either the
whole farm or just a single plant without ever having to set foot
in the field themselves. The Internet of Things (IoT) is the
engine that drives smart farming, which involves linking
various devices and sensors that are installed on farms to
generate data-driven and automated agricultural operations.

5.4.1 The IoT-Based Smart Farming Cycle

The information that can be extracted from objects and sent


through the internet forms the backbone of the Internet of
Things. IoT devices that are deployed on a farm should gather
and analyze data in a repeated cycle in order to maximize the
efficiency of the agricultural process. This will allow farmers to
respond more rapidly to developing problems and shifts in the
surrounding environment. A cycle quite similar to this one is
followed by intelligent farming:

• Observation : The crops, animals, soil, or atmosphere may


all be monitored and recorded via the use of sensors.
• Diagnostics: The readings from the sensors are sent to an
Internet of Things platform that is located in the cloud.
This platform has predetermined decision rules and
models, which are sometimes referred to as "business
logic." These rules and models determine the state of the
item being analyzed and point out any flaws or
requirements.
• Decisions : After problems have been identified, the user
and/or machine learning-driven components of the IoT
platform decide whether or not a location-specific
therapy is required and, if so, which one should be used.

217
Embedded Systems and IoT

• Action : The cycle starts all over again from the


beginning once the end-user provides feedback and
takes action.

5.4.2 IoT Solutions to Agricultural Problems

Many people feel that Internet of Things technology may be


beneficial to all aspects of farming, from planting crops to
managing forests. Precision farming and farm automation are
two areas in which the Internet of Things has the potential to
completely transform the agricultural industry. There are a
number of ways in which IoT may make farming more efficient.

Precision Farming

The term "precision farming," which may also be referred to as


"precision agriculture," is an umbrella term that refers to
techniques based on the internet of things that make farming
more regulated and precise. To put it another way, both plants
and animals get the exact care that they need, which is decided
by machines with a precision that exceeds that of a person.
Instead of making choices for a whole field, precision farming
enables for decisions to be made on a per-square-meter or even
per-plant or per-animal basis. This is the primary distinction
between traditional farming and precision farming. Farmers are
able to increase the efficiency of herbicides and fertilizers by
carefully monitoring fluctuations within a field, or they may
utilize these inputs in a more targeted manner.

Precision Livestock Farming

As is the case with precision agriculture, smart farming methods


allow farmers to better monitor the requirements of individual
animals and change the nutrition that they get appropriately, so

218
Embedded Systems and IoT

reducing the risk of illness and improving the overall health of


the herd. The whereabouts of cattle, as well as their well-being
and overall health, may be tracked via wireless Internet of
Things apps by large-scale farmers. Because of this knowledge,
they are able to recognize unwell animals and remove them
from the herd in order to stop the spread of disease.

Automation in Smart Greenhouses

In traditional greenhouses, environmental factors are controlled


by means of either physical intervention or a proportional
control system. This approach often results in a loss of
productivity as well as a loss of energy and an increase in the
cost of labor. Smart greenhouses that are controlled by the
Internet of Things are able to automatically monitor as well as
adjust the environment, doing away with the need for human
interaction. A wide variety of sensors are set up in order to
measure the characteristics of the surrounding environment in
accordance with the needs of the crop. That data is then saved
on a cloud-based platform so that it may undergo additional
processing and be controlled with as little human involvement
as possible.

Agricultural Drones

Agriculture is one of the primary industries that uses ground-


based and aerial drones for crop health evaluation, irrigation,
crop monitoring, crop spraying, planting, soil and field analysis,
and other fields of operation. Drones may be flown from the
ground or from the air. Farmers are able to gain insights into a
wide variety of metrics thanks to the data collected by drones
while they are in flight. These metrics include plant health
indices, plant counting and yield prediction, plant height

219
Embedded Systems and IoT

measurement, canopy cover mapping, field water pond


mapping, scouting reports, stockpile measuring, chlorophyll
measurement, nitrogen content in wheat, drainage mapping,
and weed pressure mapping, amongst others. It's important to
note that IoT-based smart farming isn't just for industrial-scale
farms; it can also benefit emerging farming trends like organic
farming, family farming, including the breeding of specific cattle
and/or the cultivation of specific cultures, the preservation of
specific or high-quality varieties, and the enhancement of highly
transparent farming to consumers, society, and market
consciousness.

5.4.3 Third Green Revolution

The Internet of Things (IoT) and advances in precision


agriculture are laying the groundwork for a Third Green
Revolution. The Third Green Revolution is sweeping over
agriculture in the same way that plant breeding and genetics did
before it. Data-driven analytics technology like drones, robots,
the Internet of Things (IoT), big data analysis, and precision
agricultural tools are at the heart of this transformation. The
smart agricultural revolution shows a future in which pesticide
and fertilizer consumption decreases but productivity increases.
Internet of Things technology will improve food tracking, which
will raise food safety. More effective use of water is only one
example of how this can help the environment. Better
optimization of treatments and inputs is another.

Because of its more targeted and effective use of resources,


smart farming has the potential to provide a more productive
and sustainable type of agricultural production. Building new
farms will fulfill an age-old human aspiration.

220
Embedded Systems and IoT

5.5 Smart Cities

To solve the rising problems of urbanization, sustainable


development projects rely heavily on the infrastructure
provided by ICT (Information and Communication
Technologies). Data is gathered and analyzed with the use of
Internet of Things devices like sensors, lighting, and meters.
Smart city solutions are interacted with by citizens through
smartphones, linked cars, and smart houses. The goal of
creating a "smart city" is to expedite the delivery of key
services, increase sustainability, and improve the quality of life
for residents. Here are a few arguments in favor of Internet of
Things for smart cities:

• Smarter Use of Existing Materials: In order to make the


most efficient use of scarce commodities like power,
water, and transportation, these experts use cutting-edge
technology like the Internet of Things (IoT), artificial
intelligence (AI), and big data analytics. This has the
potential to save expenses, cut down on waste, and boost
productivity.
• Enhanced Standard of Living: There are several ways in
which they raise the standard of living for locals. Data and
technology may be used to improve healthcare, education,
and law enforcement. They may also facilitate people'
access to data and their engagement in government.
• Increased Sustainability: Reduced energy use, increased
use of renewable energy, and decreased garbage
production are all goals of the smart city design. This may
strengthen urban areas' resistance to climate change and
reduce its negative impacts.

221
Embedded Systems and IoT

• Economic Development: They promote growth in the


economy by inspiring entrepreneurs to set up shop in the
area. They may also help current firms function more
effectively, which is good for the economy.

Figure 5.14: Applications of Smart cities

Large-scale implementations of the IoT in smart cities are


becoming commonplace. It aids in increasing productivity,
decreasing expenses, and bettering inhabitants' quality of life.
It gathers data in real time with the use of Internet of Things-
enabled gadgets including Bluetooth sensors, RFID tags, and
meters. Cities may use this information to enhance their
infrastructure, offerings, and public services. IoT smart city
examples from the actual world include:

222
Embedded Systems and IoT

Smart Traffic Management

Traffic signals, roads, and cars may all benefit from having
Internet of Things (IoT) sensors placed to gather data on traffic
flow, congestion, and accidents. This information may be
utilized to enhance road safety, decrease congestion, and
enhance the efficiency of traffic movement. These systems
indicate a vehicle's position and speed using data gathered
from sensors and the rider's smartphone's GPS. Furthermore,
preferred routes may be predicted using previous data, which
helps avoid congestion issues.

Smart Parking

Internet of Things (IoT) sensors may be deployed in parking


lots to report when a spot is taken. Finding a parking place
doesn't have to be a time-consuming ordeal thanks to this
information. When a parking place becomes available, the
integrated sensors send that information to the cloud, where it
can be accessed by the driver instantly.

Public Safety

Public locations may have IoT-enabled cameras and sensors


placed to keep an eye out for any suspicious behavior or left
luggage. Analytics, real-time monitoring, and the ability to
make decisions are all built into IoT-enabled products. Crime
patterns may be predicted with the use of data analysis from
social media feeds and closed-circuit television (CCTV)
cameras and sound sensors installed across the city. As a result,
law enforcement authorities may be better prepared to deal
with any dangers that may arise.

223
Embedded Systems and IoT

Waste Management

By monitoring garbage levels, fuel usage, and container


utilization in real time, IoT-enabled systems help waste
collection companies improve collection schedules and routes.
To save expenses and environmental effect, Internet of Things
(IoT) sensors may be put in trash cans and recycling bins to
track how full they are and determine the most efficient routes
for garbage and recycling pickup. Each one is equipped with a
sensor that keeps track of the amount of trash inside. To
prevent emptying a container while it is just halfway full, a
mobile app alerts the truck driver as soon as the container
reaches the threshold level.

Utility Management

Internet of Things (IoT)-enabled smart solutions help


homeowners save money on utility costs by:

• Energy management: With the use of Internet of Things


(IoT) sensors, energy consumption in buildings and
residences can be monitored and optimized, leading to
savings in both money and carbon emissions.
• Smart lighting: The installation of Internet of Things (IoT)
sensors in streetlights may reduce energy consumption
and pollution by adjusting the illumination brightness
depending on ambient light.
• Water management: To save money and resources, IoT
sensors may be deployed in water distribution systems to
monitor water quality, find leaks, and optimize
consumption.

224
Embedded Systems and IoT

Remote Monitoring

Smart city solutions built on the Internet of Things also help


people better control their utilities. Residents may monitor and
manage their energy and water usage with the help of these
meters. A homeowner, for instance, may use a mobile app to
disable their HVAC system. As a result, utility providers may
keep homeowners apprised of any problems, such as leaks or
impending breakdowns, and dispatch repair crews as soon as
possible.

Environmental Well-being

Municipalities may remotely monitor environmental


conditions with the aid of IoT-powered systems. To monitor
water quality and alert authorities to any problems, such as
leaks or changes in the water's chemical composition, sensors
are installed in water distribution networks. The same
machinery is used

Public Transport

Data collected from sensors placed in a variety of sources may


help traffic operators better understand how people utilize
public transportation.

This information is useful in standardizing safety and


punctuality, decreasing passenger wait times, and improving
the overall travel experience for residents. Roads and bridges
in a smart city may be equipped with BLE beacons to monitor
their condition and trigger prompt maintenance if any damage
is detected.

225
Embedded Systems and IoT

5.5.1 Benefits of IoT in Smart Cities

Smart cities that are built on the Internet of Things provide


efficient living and working environments by combining the
usage of a variety of technologies, including applications,
linked systems, buildings, and other gadgets. Just a handful of
the numerous advantages it offers are listed below:

• Improved infrastructure management: The Internet of


Things has the potential to be used in the monitoring and
management of the city's infrastructure, which includes
the roads, bridges, and buildings. This may assist in
determining what maintenance is required, cut down on
unscheduled downtime, and increase overall safety.
• Enhanced public safety: Sensors and cameras that are
equipped with internet of things technology may assist in
improving public safety by identifying possible security
concerns, tracking criminal behavior, and monitoring
reaction times for emergency situations.
• Efficient transportation: The Internet of Things helps
enhance traffic flow, decrease congestion, and increase the
efficiency of public transit lines. Connected cars are able to
connect with one another as well as with the
infrastructure that controls traffic, making travel both
safer and more efficient.
• Energy efficiency: The Internet of Things makes it
possible to monitor and manage the use of energy in
buildings and public areas, which results in less wasted
energy and lower prices.Increased efficiency in the
management of trash: sensors connected to the internet of
things may help improve waste collection routes, which

226
Embedded Systems and IoT

can reduce the negative effect that rubbish collection has


on the environment and save expenses.
• Enhance citizen engagement: Platforms that are enabled
by the Internet of Things may make it possible for
residents to take part in the design of their cities, offer
input on municipal services, and report problems in real
time.
• Health and wellness: The Internet of Things (IoT) may be
used to monitor air quality, identify environmental risks,
and track health trends. This provides public health
authorities with vital data that can be utilized to establish
policies that promote the health of citizens.

Figure 5.15: Implementation Model

227
Embedded Systems and IoT

5.5.2 Smart City Implementation Model

It is necessary for municipalities to have a fundamental smart


city platform in place before they can adopt sustainable
development practices, enhance traffic management, or
automate garbage collection. These goals may be accomplished
via the use of smart city technology. If the municipality wants
to broaden the types of services it offers, it can simply upgrade
the architecture of this platform with new technologies with
the assistance of a business that specializes in the creation of
Internet of Things applications.

5.6 Smart Healthcare

Devices that are enabled by the Internet of Things (IoT) have


made remote monitoring in the healthcare industry feasible.
This has unlocked the potential to keep patients safe and
healthy while also providing doctors with the tools they need
to provide exceptional care. Because of this, interacting with
physicians has become less difficult and more productive,
which has led to an increase in patient involvement and
satisfaction. In addition, the use of remote monitoring of a
patient's health assists in shortening the duration of the
patient's stay in the hospital and helps to avoid readmissions.
The Internet of Things also has a substantial influence on
greatly lowering overall healthcare expenditures and
significantly improving patient outcomes. The Internet of
Things is unquestionably revolutionizing the healthcare
business by altering the environment in which devices and
people interact in the process of providing healthcare solutions.
Applications of IoT may be found in the healthcare industry,
and these applications are beneficial for patients, families,
doctors, hospitals, and insurance companies.

228
Embedded Systems and IoT

5.6.1 IoT for Patients

Patients have access to individualized care via the use of


technology in the form of wearable devices such as fitness
bands and other wirelessly linked equipment such as blood
pressure and heart rate monitoring cuffs, glucometers, and so
on. These gadgets are able to be programmed to remind users
of a calorie count, an activity check, an appointment, variances
in blood pressure, and a great deal more.

Because it enables continuous monitoring of health problems,


the Internet of Things has significantly improved people's lives,
particularly older patients. People who live by themselves and
their families are significantly impacted by this. An alarm
system notifies a person's family members and any concerned
medical professionals if there is a disruption in a person's
regular activities or a change in those activities.

5.6.2 IoT for Physicians

Wearable technology and other forms of home monitoring


devices that are integrated with the internet of things allow
medical professionals to keep a closer eye on the health of their
patients. They are able to monitor whether or not patients
follow to their treatment regimens and identify whether or not
patients need emergency medical intervention.

The Internet of Things allows medical personnel to be more


vigilant and to communicate with patients in a more proactive
manner. The data received by Internet of Things devices may
assist medical professionals in determining the most effective
course of therapy for patients and achieving the desired results.

229
Embedded Systems and IoT

5.6.3 IoT for Hospitals

In addition to monitoring the health of patients, there are many


other areas in which gadgets connected to the internet of things
may be extremely helpful in hospitals. IoT devices that have
been equipped with sensors may be used to monitor the
position of medical equipment in real time. This includes
wheelchairs, defibrillators, nebulizers, oxygen pumps, and
other monitoring devices. Real-time analysis may also be
performed on the distribution of medical personnel across
various sites. Patients in hospitals have a significant amount of
cause for anxiety over the spread of illnesses. Hygiene
monitoring tools that are enabled by the Internet of Things may
be helpful in reducing the risk of infection for patients. IoT
devices are also helpful in asset management, such as the
control of pharmacy inventory. They are also helpful in
environmental monitoring, such as checking the temperature in
a refrigerator, as well as in the control of humidity and
temperature.

5.6.4 IoT for Health Insurance Companies

Intelligent gadgets that are linked to the internet provide a


wealth of potential for health insurance providers.
Underwriting and claims processes may both benefit from the
use of data obtained from wearable health monitoring devices
by insurance firms. They will be able to recognize fraudulent
claims and locate possibilities for underwriting with the use of
this data. Devices connected to the internet of things add
transparency to the underwriting, pricing, claims management,
and risk assessment procedures that take place between
insurers and their clients.

230
Embedded Systems and IoT

Figure 5.16 Healthcare Architecture

Customers will have sufficient insight into the reasoning


behind each choice that is taken and the consequences of each
process as a result of data-driven decisions that are powered by
the Internet of Things (IoT). It's possible that insurers may
reward their clients monetarily for utilizing and sharing the
health data that's been created by IoT devices.

They are able to provide incentives to clients who use Internet


of Things devices to monitor their day-to-day activities, as well
as their adherence to treatment regimens and preventative
health measures. This will be of tremendous assistance to
insurers in their efforts to decrease claims. Using the data
collected by these sensors, Internet of Things devices may also
make it possible for insurance firms to authenticate claims.

231
Embedded Systems and IoT

5.6.5 Simple Healthcare System Architecture

The Internet of Things (IoT) has the potential to revolutionize


the healthcare industry by making it more efficient, more
rapid, and more accurate. There are several distinct IoT
architectures in the healthcare industry, each of which
contributes to the health care system.

• Product Infrastructure: IoT product infrastructure,


including hardware and software components, reads the
signals from the sensors and displays them on a device
that is specifically intended for that purpose.
• Sensors: The Internet of Things (IoT) in healthcare uses a
variety of sensor devices, such as pulse oximeters,
electrocardiograms, thermometers, fluid level sensors, and
sphygmomanometers (blood pressure monitors), to read
data on the present state of the patient.
• Connectivity: IoT systems provide improved
communication (through Bluetooth, WiFi, and other
protocols) of devices or sensors between the
microcontroller and the server, allowing for data to be
read in both directions.
• Analytics: On the basis of their evaluated data, healthcare
systems are able to improve a patient's health by
determining whether or not they have healthy parameters
for their patients, which they acquire from the data that
comes from sensors and correlates.
• Application Platform: IoT system provides access to
information on patients on the monitor devices used by
medical experts, together with all of the patients' data.

232
Embedded Systems and IoT

Figure 5.17: IoT in Healthcare

5.6.6 Redefining Healthcare

The increasing availability of internet-of-things solutions with a


focus on healthcare paves the way for enormous prospects.
Additionally, the enormous volume of data produced by these
interconnected devices has the potential to revolutionize
healthcare. The Internet of Things features a four-step
architecture, which may be thought of as steps in a process.
Each of the four steps is related to the others in such a way that
the value generated at one level may be used in the subsequent
stages to acquire or process data. The incorporation of core
values into the process generates insights and generates
dynamic business opportunities.

• Step 1: The first thing that has to be done is to set up a


network of linked devices. These should comprise sensors,
actuators, monitors, detectors, video systems, and so on.
These gadgets are responsible for collecting the data.
• Step 2: In most cases, the data that are received from
sensors and other devices are in the analog form. In order
to continue processing the data, it is necessary to
aggregate the data and convert it to the digital form.

233
Embedded Systems and IoT

• Step 3: Following the digitization and aggregation of the


data, it is then pre-processed, standardized, and uploaded
to the cloud or a data center.
• Step 4: The final data has been properly maintained and
evaluated at the level necessary. When applied to this
data, advanced analytics provides businesses with
insights that can be put to use for making more informed
decisions.

The Internet of Things is transforming healthcare by assuring


better care, improved treatment results, and decreased costs for
patients, as well as better procedures and workflows, greater
performance, and an enhanced patient experience for
healthcare professionals.

Figure 5.18: The four stages of IoT solutions

The following are some of the primary benefits that the Internet
of Things brings to healthcare:

• Cost Reduction: The Internet of Things makes it possible


to monitor patients in real time, which results in a
considerable reduction in the number of needless trips to
the doctor, hospital stays, and readmissions.

234
Embedded Systems and IoT

• Improved Treatment: It gives doctors the ability to make


judgments that are evidence-based and educated, and it
delivers complete openness.
• Faster Disease Diagnosis: The continuous monitoring of
patients and the collection of real-time data helps
physicians diagnose illnesses at an earlier stage or even
before the onset of symptoms associated with the
condition.
• Proactive Treatment: The provision of preventative
medical care is made possible via continuous monitoring
of patients' health.
• Drugs and Equipment Management: In the field of
healthcare, one of the most significant challenges is the
administration of pharmaceuticals and medical supplies.
These may be effectively handled and exploited, resulting
in cost savings, thanks to linked devices.
• Error Reduction: Data created by Internet of Things
devices not only aid in the process of making sound
decisions but also guarantee that healthcare operations
run smoothly with fewer instances of mistake, waste, and
overall expenses to the system.

The Internet of Things (IoT) in healthcare is not without its


issues. Connected devices that are enabled by the Internet of
Things collect enormous volumes of data, including sensitive
information, which raises worries about the safety of the data.
It is essential to put appropriate security measures into action.
The Internet of Things investigates new facets of patient care
by allowing real-time monitoring of patients' health and access
to patients' medical records.

235
Embedded Systems and IoT

This data is a treasure trove for the many players in the


healthcare industry, who can use it to enhance patients' health
and experiences while also creating new income possibilities
and enhancing the efficiency of healthcare operations. In a
world that is becoming more interconnected, having a strategy
in place to take use of the potential of digital technology will
set you apart.

5.7 Layers of IoT Architecture

The Internet of Things architecture may have as many as seven


levels, which are respectively referred to as the perception,
transport, edge, processing, application, business, and security
layers.

Perception Layer

The perception layer of an Internet of Things system


architecture is sometimes referred to as the device layer, and it
is made up of a number of different parts. These elements
include sensors, cameras, actuators, and other similar devices
that collect data and carry out activities. For instance, an
Internet of Things (IoT) sensor installed on an automobile
production line may do quality assurance testing on a nearby
robot. When the robot is putting together a fuse box, an
Internet of Things sensor checks to see whether it has placed
the fuses in the right positions by analyzing the fuses' color
coding.

Transport Layer

In an Internet of Things system design, the transport layer is


responsible for transmitting data from many devices (such as
on-premise sensors, cameras, and actuators) to either an on-

236
Embedded Systems and IoT

premise or cloud-based data center. IoT gateways are


responsible for converting the analog input they receive into a
digital representation as the initial stage in the process. After
that, the gateway will send the data to either an on-premise or
cloud-based data center by using a data transfer protocol
(DTP), which might be any of a variety of protocols.

DTP Protocols

• MQTT (Message Queue Telemetry Transport): MQTT is


a lightweight protocol that was first built by IBM. It has
interaction techniques such as publish and subscribe. Due
to the fact that it is open-source and is suitable for devices
situated in distant places with inadequate internet access,
it has become the protocol that is utilized the most in the
realm of the internet of things (IoT).
• Modbus: Following the supervisory control and data
acquisition (SCADA) model, the data communications
protocol Modbus is the method of choice for connecting a
supervisory computer to remote terminal units (RTUs) in
Internet of Things (IoT) systems. Modbus was originally
designed for use with the programmable logic controllers
(PLCs) manufactured by Modicon, which are now
manufactured by Schneider Electric.
• AMQP (Advanced Message Queuing Protocol): The
AMQP protocol was largely designed for the purpose of
usage in sending data within the financial services
industry. This development was spearheaded by
JPMorgan Chase, one of the major banks in the United
States. The AMQP protocol has a built-in security
architecture that makes use of components such as
transport layer security (TLS) and simple authentication

237
Embedded Systems and IoT

and security layer (SASL). This is one of the protocol's


strengths.
• PROFINET (Process Field Network): The Ethernet-
compatible PROFINET protocol has seen widespread use
in industrial automation systems that need
communication across many edge devices, equipment,
and software systems. This protocol was developed and is
sponsored by PROFIBUS & PROFINET International (PI),
an automation community located in Germany.

Edge Layer

Latency is one of the primary performance difficulties that


becomes one of the primary challenges when IoT networks
expand in size. This is because several devices connecting to a
hub end up congesting the network. Edge computing solves
these issues by making it feasible to do data processing and
analysis as near to the point of origin as is practically
practicable. This is accomplished via the edge layer of an
Internet of Things system design. One characteristic that is
shared by all of the devices that are located on the edge of the
Internet of Things network is the ability to send what they have
discovered to nodes in the form of data packets, which are then
further processed by the nodes. When a significant deviation is
discovered, certain'smart' edge devices are also configured to
immediately interrupt the process being monitored or to begin
some kind of damage control action. Edge devices for the
Internet of Things are often built to function easily with other
devices made by a variety of manufacturers. This is something
that is essential for the proliferation of edge devices at scale in
an Internet of Things system.

238
Embedded Systems and IoT

Data Pre-Processing

Data pre-processing is one of the aspects of Internet of Things


systems that is expanding at the quickest rate. It has the ability
to identify and fix issues in a timely manner, all while reducing
the cost of transferring vast amounts of data. On the other
hand, complex processors raise the costs of network layer
installation and maintenance, and pre-processing design bears
the extra risk of filtering out vital IoT device data before it can
be processed further. Both of these risks contribute to an
increase in overall system costs.

Processing Layer

The processing layer, also known as the middleware layer, is


an essential element of the architecture of an Internet of Things
(IoT) system. This layer often makes use of a large number of
concurrently linked computers in the form of cloud computing
in order to provide greater performance in the areas of
computation, storage, networking, and security. In particular, it
is the responsibility of the processing layer within the
architecture of an IoT system to conduct analyses of the
incoming data in order to offer fresh insights, helpful forecasts,
and timely alerts. The Internet of Things (IoT) often manages
enormous amounts of data, which are produced by a large
number of edge devices located at a number of different places
around the network's perimeter. In order to get this data ready
for the application layer, the'middleware' of the processing
layer goes through a three-step process:

• Data Accumulation: The middleware will accurately


identify and allocate various data kinds to the storage that
is most suited for them. Data lakes are used to store

239
Embedded Systems and IoT

unstructured data, which includes audio and video


streams, as well as photographs. This kind of data often
requires more storage capacity. On the other hand,
structured data, which includes instrument readings, log
values, and measurements (telemetry data), takes up less
space and is kept in data warehouses.
• Data Abstraction: entails gathering information from a
variety of different sources and ensuring that it is
transformed into a format that can be "read" by the
application layer software.
• Data Analysis: use algorithms with a focus on machine
learning (ML) or deep learning, which are adept in finding
structure in apparently unrelated data

Application Layer

Deciphering promising patterns in IoT data and organizing


them into summaries that are simple for humans to grasp, such
graphs and tables, is what the application layer of an IoT
system design is all about. Common examples of software that
belongs in the application layer of an IoT architecture are
device control and monitoring programs and process control
applications.

Business Layer

Application-level pattern decoding may lead to better business


insights, trend projections, and operational choices that boost
productivity, security, cost-effectiveness, and customer
satisfaction. The business layer of an Internet of Things system
design is where all of these objectives may be realized.

240
Embedded Systems and IoT

Security Layer

When designing an architecture for an Internet of Things (IoT)


system, security is among the most crucial needs. Ironically, it
also happens to be one of the most significant issues that the
architecture of the Internet of Things (IoT) faces, as well as IoT
devices themselves. The three primary components that make
up the Internet of Things security layer are as follows:

• Equipment Security: concerns the actual Internet of


Things devices themselves and the safeguarding of these
endpoints from malicious software and unauthorized
access.
• Cloud Security: The majority of Internet of Things data is
handled on the cloud, making cloud security an essential
component in the fight against data breaches.
• Connection Security: Centered on protecting data as it is
being sent over networks, particularly via the use of
encryption. The transport layer security protocol,
sometimes known as TLS, is widely regarded as the
standard for Internet of Things connection safety.

241
Embedded Systems and IoT

References

1. Rajkamal, ‘Embedded system-Architecture, Programming,


Design’, TMH,2011.

2. Peckol, “Embedded system Design”,John Wiley &Sons,2010

3. Lyla B Das,” Embedded Systems-An Integrated Approach”,


Pearson2013

4. Elicia White, ”Making Embedded Systems”, O’Reilly


Series,SPD,2011

5. Bruce Powel Douglass, ”Real-Time UML Workshop for


Embedded Systems,Elsevier,2011

6. Advanced Computer architecture, By Rajiv Chopra, S Chand ,


2010

7. Jorgen Staunstrup, Wayne Wolf, Hardware / Software Co-


Design Principles and Practice, Springer, 2009.

8. Shibu K.V, “Introduction to Embedded Systems”, Tata


Mcgraw Hill,2009

9. Tammy Noergaard, ”Embedded System Architecture, A


comprehensive Guide for Engineers and Programmers”,
Elsevier, 2006

10. Giovanni De Micheli, Mariagiovanna Sami, Hardware /


Software Co- Design, Kluwer Academic Publishers, 2002

242
View publication stats

You might also like