0% found this document useful (0 votes)
10 views

UPDATED ESIOT NOTES

The 8051 microcontroller is an 8-bit microcontroller developed by Intel in 1981, featuring a processor that operates on 8-bit data, with 4 KB ROM and 128 bytes RAM. It includes a CPU, memory, I/O ports, timers, and various registers, all integrated into a single chip, making it widely used in embedded systems. The document also describes the architecture, pin configuration, and addressing modes of the 8051 microcontroller.
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)
10 views

UPDATED ESIOT NOTES

The 8051 microcontroller is an 8-bit microcontroller developed by Intel in 1981, featuring a processor that operates on 8-bit data, with 4 KB ROM and 128 bytes RAM. It includes a CPU, memory, I/O ports, timers, and various registers, all integrated into a single chip, making it widely used in embedded systems. The document also describes the architecture, pin configuration, and addressing modes of the 8051 microcontroller.
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/ 131

UNIT-1

1.1. 8051 Microcontroller


8051 microcontroller is an 8-bit microcontroller created in 1981 by Intel Corporation. It has an 8- bit
processor that simply means that it operates on 8-bit data at a time. It is among the most popular and
commonly used microcontroller.
As it is an 8-bit microcontroller thus has 8-bit data bus, 16-bit address bus. Along with that, it holds 4
KB ROM with 128 bytes RAM.
1.1.1. What a Microcontroller is?
A microcontroller is an integrated chip designed under Very Large Scale Integration technique that
consists of a processor with other peripheral units like memory, I/O port, timer, decoder, ADC etc. A
microcontroller is basically designed in such a way that all the working peripherals are embedded in
a single chip with the processor.
Any programmable device holds a processor, memory, I/O ports and timer within it. But a
microcontroller contains all these components embedded in a single chip. This single-chip manages
the overall operation of the device.
A microprocessor simply contains a CPU that processes the operations with the help of other
peripheral units. Microprocessors are used where huge space is present to inbuilt a large motherboard
like in PCs.
1.2. Architecture of 8051 Microcontroller
The figure below represents the architectural block diagram of 8051 microcontroller:
As we can see that several units are present in the above architecture. And every unit is embedded to
execute the desired operation. Let us now discuss the operation of each unit present in the
architecture.
1.2.1. Central processing unit (CPU): 8051 uses the 8-bit processor. This unit carries out the
operation on 8-bit data. A processor is the heart of microcontroller. As the execution of the program
stored in the memory is performed by the processor.

The unit performs arithmetic and logical operations on 8-bit data as it has ALU, with internal
registers and program counters.
Several logical operations are performed by the ALU according to the program stored in the memory.
The processor of 8051 microcontrollers possesses a special feature by which it can process single bit
or 8-bit data. This simply means that it has the ability to access each single bit data either to clear, set
or move etc. for any logical computation.
1.2.2. Memory: Basically 8051 microcontroller consists of on-chip program memory i.e., ROM and
on-chip data memory i.e., RAM.
Let us first understand
• ROM
8051 microcontroller has 4 KB ROM with 0000H to 0FFFH as the addressable space. It is
completely a program or code memory that means used by the programmer to store the programs that
are to be executed by the microcontroller.
• The operations that are executed by the device in which the microcontroller is present are stored in
the ROM of the memory at the time of fabrication. Hence cannot be changed or modified.
• RAM
8051 holds a 128 bytes RAM. Basically, RAM is used to store data or operands for only a small time
duration. It can be altered anytime according to the need of the user. It is also known as the data
memory as it stores the data temporarily.

1.2.3. Input/ Output port: 8051 consists of 4 parallel ports of 8 bit each thereby providing 32 input-
output pins. All the 4 ports function bidirectional i.e., either input or output according to the software
control.

1.2.4. Timer and Control Unit: Timers are used to create a time gap or delay between 2 events.
8051 microcontroller consists of 2 timers of 16 bit each by which the system can produce two delays
simultaneously in order to generate the appropriate delay.
1.2.5. 8051 Flag Bits and PSW Register
The program status word (PSW) register is an 8-bit register, also known as flag register. It is of 8-bit
wide but only 6-bit of it is used. The two unused bits are user-defined flags.
1.2.6. The Data Pointer (DPTR) is the 8051's only user-accessible 16-bit (2-byte) register. The
Accumulator, R0–R7 registers and B register are 1-byte value registers. DPTR is meant for pointing
to data. It is used by the 8051 to access external memory using the address indicated by DPTR.

1.2.7. Pin diagram of 8051 Microcontroller Introduction :


The 8051 microcontroller is a popular 8-bit microcontroller widely used in embedded systems. It
is a single-chip microcontroller with a Harvard architecture that includes a CPU, RAM, ROM,
and several peripherals. The 8051 microcontroller has a 40-pin dual in-line package (DIP) that
provides various inputs and outputs for communication with external devices.
8051 microcontroller is a 40 pin Dual Inline Package (DIP). These 40 pins serve different
functions like read, write, I/O operations, interrupts etc. 8051 has four I/O ports wherein each
port has 8 pins which can be configured as input or output depending upon the logic state of the
pins. Therefore, 32 out of these 40 pins are dedicated to I/O ports. The rest of the pins are
dedicated to VCC, GND, XTAL1, XTAL2, RST, ALE, EA’ and PSEN’. Pin diagram of 8051
Description of the Pins :
• Pin 1 to Pin 8 (Port 1) – Pin 1 to Pin 8 are assigned to Port 1 for simple I/O operations. They
can be configured as input or output pins depending on the logic control i.e. if logic zero (0) is
applied to the I/O port it will act as an output pin and if logic one (1) is applied the pin will act as
an input pin. These pins are also referred to as P1.0 to P1.7 (where P1 indicates that it is a pin in
port 1 and the number after ‘.’ tells the pin number i.e. 0 indicates first pin of the port. So, P1.0
means first pin of port 1, P1.1 means second pin of the port 1 and so on). These pins are
bidirectional pins.
• Pin 9 (RST) – Reset pin. It is an active-high, input pin. Therefore if the RST pin is high for a
minimum of 2 machine cycles, the microcontroller will reset i.e. it will close and terminate all
activities. It is often referred as “power-on-reset” pin because it is used to reset the
microcontroller to it’s initial values when power is on (high).
• Pin 10 to Pin 17 (Port 3) – Pin 10 to pin 17 are port 3 pins which are also referred to as P3.0 to
P3.7. These pins are similar to port 1 and can be used as universal input or output pins. These
pins are bidirectional pins. These pins also have some additional functions which are as follows:

P3.0 (RXD) : 10th pin is RXD (serial data receive pin) which is for serial input. Through this
input signal microcontroller receives data for serial communication.

• P3.1 (TXD) : 11th pin is TXD (serial data transmit pin) which is serial output pin. Through this
output signal microcontroller transmits data for serial communication.

• P3.2 and P3.3 (INT0′, INT1′ ) : 12th and 13th pins are for External Hardware Interrupt 0 and
Interrupt 1 respectively. When this interrupt is activated(i.e. when it is low), 8051 gets
interrupted in whatever it is doing and jumps to the vector value of the interrupt (0003H for
INT0 and 0013H for INT1) and starts performing Interrupt Service Routine (ISR) from that
vector location.

• P3.4 and P3.5 (T0 and T1) : 14th and 15th pin are for Timer 0 and Timer 1 external input.
They can be connected with 16 bit timer/counter.

• P3.6 (WR’) : 16th pin is for external memory write i.e. writing data to the external memory.

• P3.7 (RD’) : 17th pin is for external memory read i.e. reading data from external memory.

• Pin 18 and Pin 19 (XTAL2 And XTAL1) – These pins are connected to an external oscillator
which is generally a quartz crystal oscillator. They are used to provide an external clock
frequency of 4MHz to 30MHz.

• Pin 20 (GND) – This pin is connected to the ground. It has to be provided with 0V power
supply. Hence it is connected to the negative terminal of the power supply.
• Pin 21 to Pin 28 (Port 2) – Pin 21 to pin 28 are port 2 pins also referred to as P2.0 to P2.7.
When additional external memory is interfaced with the 8051 microcontroller, pins of port 2 act
as higher-order address bytes. These pins are bidirectional.

• Pin 29 (PSEN) – PSEN stands for Program Store Enable. It is output, active-low pin. This is
used to read external memory. In 8031 based system where external ROM holds the program
code, this pin is connected to the OE pin of the ROM.

• Pin 30 (ALE/ PROG) – ALE stands for Address Latch Enable. It is input, active-high pin.
This pin is used to distinguish between memory chips when multiple memory chips are used. It
is also used to de-multiplex the multiplexed address and data signals available at port 0. During
flash programming i.e. Programming of EPROM, this pin acts as program pulse input (PROG).

• Pin 31 (EA/ VPP) – EA stands for External Access input. It is used to enable/disable external
memory interfacing. In 8051, EA is connected to Vcc as it comes with on-chip ROM to store
programs. For other family members such as 8031 and 8032 in which there is no on- chip ROM,
the EA pin is connected to the GND.

• Pin 32 to Pin 39 (Port 0) – Pin 32 to pin 39 are port 0 pins also referred to as P0.0 to P0.7.
They are bidirectional input/output pins. They don’t have any internal pull-ups. Hence, 10 K?
pull-up registers are used as external pull-ups. Port 0 is also designated as AD0-AD7 because
8051 multiplexes address and data through port 0 to save pins.

• Pin 40 (VCC) – This pin provides power supply voltage i.e. +5 Volts to the circuit.
8051MicrocontrollerArchitecuture

Embedded Systems - Addressing Modes


An addressing mode refers to how you are addressing a given memory location. There are five
different ways or five addressing modes to execute this instruction which are as follows −

• Immediate addressing mode

• Direct addressing mode

• Register direct addressing mode


• Register indirect addressing mode

• Indexed addressing mode


Immediate Addressing Mode
Let's begin with an example. MOV A, #6AH
In general, we can write,
MOV A, #data
It is termed as immediate because 8-bit data is transferred immediately to the accumulator
(destination operand).

The above instruction and its execution. The opcode 74H is saved at 0202 address. The data 6AH
is saved at 0203 address in the program memory. After reading the opcode 74H, the data at the
next program memory address is transferred to accumulator A (E0H is the address of
accumulator). Since the instruction is of 2-bytes and is executed in one cycle, the program
counter will be incremented by 2 and will point to 0204 of the program memory.
Note − The '#' symbol before 6AH indicates that the operand is a data (8 bit). In the absence of
'#', the hexadecimal number would be taken as an address.

Direct Addressing Mode


This is another way of addressing an operand. Here, the address of the data (source data) is given
as an operand. Let’s take an example.
MOV A, 04H
The register bank#0 (4th register) has the address 04H. When the MOV instruction is executed,
the data stored in register 04H is moved to the accumulator. As the register 04H holds the data
1FH, 1FH is moved to the accumulator.

Note − We have not used '#' in direct addressing mode, unlike immediate mode. If we had used
'#', the data value 04H would have been transferred to the accumulator instead of 1FH.
Now, take a look at the following illustration. It shows how the instruction gets executed.
Register Direct Addressing Mode
In this addressing mode, we use the register name directly (as source operand). Let us try to
understand with the help of an example.

MOV A, R4
At a time, the registers can take values from R0 to R7. There are 32 such registers. In order to use 32
registers with just 8 variables to address registers, register banks are used. There are 4 register banks
named from 0 to 3. Each bank comprises of 8 registers named from R0 to R7. named from 0 to 3. Each
bank comprises of 8 registers named from R0 to R7. At a time, a single register bank can be selected.
Selection of a register bank is made possible through a Special Function Register (SFR) named Processor
Status Word (PSW). PSW is an 8-bit SFR where each bit can be programmed as required. Bits are
designated from PSW.0 to PSW.7. PSW.3 and PSW.4 are used to select register banks
Register Indirect Addressing Mode
In this addressing mode, the address of the data is stored in the register as operand. MOV A, @R0

Here the value inside R0 is considered as an address, which holds the data to be transferred to the
accumulator. Example: If R0 has the value 20H, and data 2FH is stored at the address 20H, then the
value 2FH will get transferred to the accumulator after executing this instruction. See the following
illustration.
So the opcode for MOV A, @R0 is E6H. Assuming that the register bank #0 is selected, the R0 of
register bank #0 holds the data 20H. Program control moves to 20H where it locates the data 2FH
and it transfers 2FH to the accumulator. This is a 1-byte instruction and the program counter
increments by 1 and moves to 0203 of the program memory.
Indexed Addressing Mode

We will take two examples to understand the concept of indexed addressing mode. Take a look at the
following instructions −
MOVC A, @A+DPTR
and
MOVC A, @A+PC
where DPTR is the data pointer and PC is the program counter (both are 16-bit registers). Consider
the first example.
MOVC A, @A+DPTR
The source operand is @A+DPTR. It contains the source data from this location. Here we are adding
the contents of DPTR with the current content of the accumulator. This addition will give a new
address which is the address of the source data. The data pointed by this address is then transferred to
the accumulator.
The opcode is 93H. DPTR has the value 01FE, where 01 is located in DPH (higher 8 bits) and FE is
located in DPL (lower 8 bits). Accumulator has the value 02H. Then a 16-bit addition is performed
and 01FE H+02H results in 0200 H. Data at the location 0200H will get transferred to lOM oARcP SD|26885763
the accumulator. The previous value inside the accumulator (02H) will be replaced with the new data
from 0200H. The new data in the accumulator is highlighted in the illustration.
This is a 1-byte instruction with 2 cycles needed for execution and the execution time required for
this instruction is high compared to previous instructions (which were all 1 cycle each).
The other example MOVC A, @A+PC works the same way as the above example. Instead of adding
DPTR with the accumulator, here the data inside the program counter (PC) is added with the
accumulator to obtain the target address.

1.4. Programming Parallel port


1.4.1. 8051 Microcontroller port programming

There are four ports P0, P1, P2 and P3 each use 8 pins, making them 8-bit ports. All the ports
upon RESET are configured as output, ready to be used as output ports. To use any of these ports
as an input port, it must be programmed.
1.4.2. Pin configuration of 8051/8031 microcontroller.
Port 0: Port 0 occupies a total of 8 pins (pins 32-39) .It can be used for input or output. To use the pins of
port 0 as both input and output ports, each pin must be connected externally to a 10K ohm pull-up
resistor. This is due to the fact that P0 is an open drain, unlike P1, P2, and P3.Open drain is a term used
for MOS chips in the same way that open collector is used for TTL chips. With external pull-up resistors
connected upon reset, port 0 is configured as an output port. For example, the following code will
continuously send out to port 0 the alternating values 55H and AAH
MOV A,#55H
BACK: MOV P0,A
ACALL DELAY
CPL A
SJMP BACK

Port 0 as Input : With resistors connected to port 0, in order to make it an input, the port must
be programmed by writing 1 to all the bits. In the following code, port 0 is configured first as an
input port by writing 1’s to it, and then data is received from the port and sent to P1.

Port 1: Port 1 occupies a total of 8 pins (pins 1 through 8). It can be used as input or output. In
contrast to port 0, this port does not need any pull-up resistors since it already has pull-up
resistors internally. Upon reset, Port 1 is configured as an output port. For example, the
following code will continuously send out to port1 the alternating values 55h & AAh
MOV A,#55H ; A = 55 hex
BACK: MOV P1,A ;send it to Port 1 ACALL DELAY ;call delay routine
CPL A ;make A=0
SJMP BACK
Port 1 as input: To make port1 an input port, it must programmed as such by writing 1 to all its
bits. In the following code port1 is configured first as an input port by writing 1’s to it, then data
is received from the port and saved in R7 ,R6 & R5

MOV A,#0FFH ;A=FF HEX


MOV P1,A ;make P1 an input port by writing all 1’s to it MOV A,P1 ;get data from P1
MOV R7,A ;save it in register R7 ACALL DELAY ;wait
MOV A,P1 ;get another data from P1 MOV R6,A ;save it in register R6 ACALL DELAY ;wait
MOV A,P1 ;get another data from P1 MOV R5,A ;save it in register R5
Port 2 : Port 2 occupies a total of 8 pins (pins 21- 28). It can be used as input or output. Just like
P1, P2 does not need any pull-up resistors since it already has pull-up resistors internally. Upon
reset,Port 2 is configured as an output port. For example, the following code will send out
continuously to port 2 the alternating values 55h and AAH. That is all the bits of port 2 toggle
continuously.
MOV A,#55H ; A = 55 hex
BACK: MOV P2,A ;send it to Port 2 ACALL DELAY ;call delay routine CPL A ;make A=0
SJMP BACK
Port 2 as input : To make port 2 an input, it must programme as such by writing 1 to all its bits.
In the following code, port 2 is configured first as an input port by writing 1’s to it. Then data is
received from that port and is sent to P1 continuously.
MOV A,#0FFH ;A=FF hex
MOV P2,A ;make P2 an input port by writing all 1’s to it BACK: MOV A,P2 ;get data from P2
MOV P1,A ;send it to Port1
SJMP BACK ;keep doing that
Dual role of port 2 : In systems based on the 8751, 8951, and DS5000, P2 is used as simple I/O.
However, in 8031-based systems, port 2 must be used along with P0 to provide the 16-bit
address for the external memory. As shown in pin configuration 8051, port 2 is also designed as
A8-A15, indicating the dual function. Since an 8031 is capable of accessing 64K bytes of
external memory, it needs a path for the 16 bits of the address. While P0 provides the lower 8
bits via A0-A7, it is the job of P2 to provide bits A8-A15 of the address. In other words, when
8031 is connected to external memory, P2 is used for the upper 8 bits of the 16 bit address, and it
cannot be used for I/O.
Port 3 : Port 3 occupies a total of 8 pins, pins 10 through 17. It can be used as input or output. P3
does not need any pull-up resistors, the same as P1 and P2 did not. Although port 3 is configured
as an output port upon reset. Port 3 has the additional function of providing some extremely
important signals such as interrupts. This information applies both 8051 and 8031 chips.
1.5. 8051 Timers
1.5.1. Introduction to 8051 Timers
8051 microcontrollers have two timers and counters which work on the clock frequency.
Timer/counter can be used for time delay generation, counting external events, etc.
8051 Clock
Every Timer needs a clock to work, and 8051 provides it from an external crystal which is the main
clock source for Timer. The internal circuitry in the 8051 microcontrollers provides a clock source to
the timers which is 1/12th of the frequency of crystal attached to the microcontroller, also called
Machine cycle frequency.

For example, suppose we have a crystal frequency of 11.0592 MHz then the microcontroller will
provide 1/12th i.e.

Timer clock frequency= (Xtal Osc.frequency)/12 = (11.0592 MHz)/12 = 921.6 KHz period T=
1/(921.6 kHz)=1.085 μS
1.5.2. 8051 Timer
8051 has two timers Timer0 (T0) and Timer1 (T1), both are 16-bit wide. Since 8051 has 8-bit
architecture, each of these is accessed by two separate 8-bit registers as shown in the figure below.
These registers are used to load timer count.
8051 has a Timer Mode Register and Timer Control Register for selecting a mode of operation and
controlling purpose.
Let's see these registers,

1.5.2.1. TMOD register


TMOD is an 8-bit register used to set timer mode of timer0 and timer1.

Bit 7,3 – GATE:


1 = Enable Timer/Counter only when the INT0/INT1 pin is high and TR0/TR1 is set.
0 = Enable Timer/Counter when TR0/TR1 is set.
Bit 6,2 - C/(Counter/Timer): Timer or Counter select bit
1 = Use as Counter
0 = Use as Timer
Bit 5:4 & 1:0 - M1:M0: Timer/Counter mode select bit
These are Timer/Counter mode select bit as per the below table

M1 M0 Mode Operation
0 0 0(13-bittimermode) 13-bittimer/counter,8-bit ofTHx&5-bit ofTLx
0 1 1(16-bittimermode) 16-bittimer/counter,THxcascadedwithTLx
8-bittimer/counter(auto-reloadmode),TLxreload with
1 0 2(8-bitauto-reloadmode)
the value held by THx each time TLx overflow
Splitthe 16-bittimer into two8-bittimersi.e.THx and
1 1 3(splittimermode)
TLx like two 8-bit timer
1.5.2.2. TCON Register

TCON is an 8-bit control register and contains a timer and interrupt flags.
Bit 7 - TF1: Timer1 Overflow Flag
1 = Timer1 overflow occurred (i.e. Timer1 goes to its max and roll over back to zero).
0 = Timer1 overflow not occurred.
It is cleared through software. In the Timer1 overflow interrupt service routine, this bit will get
cleared automatically while exiting from ISR.
Bit 6 - TR1: Timer1 Run Control Bit
1 = Timer1 start.
0 = Timer1 stop.
It is set and cleared by software.
Bit 5 – TF0: Timer0 Overflow Flag
1 = Timer0 overflow occurred (i.e. Timer0 goes to its max and roll over back to zero).
0 = Timer0 overflow not occurred.
It is cleared through software. In the Timer0 overflow interrupt service routine, this bit will get
cleared automatically while exiting from ISR.
Bit 4 – TR0: Timer0 Run Control Bit
1 = Timer0 start.
0 = Timer0 stop.
It is set and cleared by software.
Bit 3 - IE1: External Interrupt1 Edge Flag
1 = External interrupt1 occurred.
0 = External interrupt1 Processed.
It is set and cleared by hardware. lOM oARcPSD|268 857 63
Bit 2 - IT1: External Interrupt1 Trigger Type Select Bit 1 = Interrupt occurs on falling edge at INT1
pin. 0 = Interrupt occur on a low level at the INT1 pin.
Bit 1 – IE0: External Interrupt0 Edge Flag
1 = External interrupt0 occurred.
0 = External interrupt0 Processed.
It is set and cleared by hardware.
Bit 0 – IT0: External Interrupt0 Trigger Type Select Bit 1 = Interrupt occurs on falling edge at INT0
pin. 0 = Interrupt occur on a low level at INT0 pin.
Let's see the timers modes
1.5.3. 8051 Timer Modes
Timers have their operation modes which are selected in the TMOD register using M0 & M1 bit
combinations.
Mode 0 (13-bit timer mode)
The Mode 0 operation is the 8-bit timer or counter with a 5-bit pre-scaler. So it is a 13-bit
timer/counter. It uses 5 bits of TL0 or TL1 and all of the 8-bits of TH0 or TH1.
lOMoARcPSD| 26885763

UNIT II EMBEDDED C PROGRAMMING

• MemoryAnd I/Odevices Interfacing

• Programming Embedded Systems in C

• Need For RTOS

• MultipleTasks and Processes

• Context Switching

• Priority Based Scheduling Policies

1|Page
lOMoARcPSD| 26885763

MemoryandI/OInterfacing
Several memory chips and I/O devices are connected to a microprocessor. The following figure
shows a schematic diagram to interface memory chips and I/O devices to a microprocessor.

MemoryInterfacing
When we are executing any instruction, the address of memory location or an I/O device is sent
out by the microprocessor. The corresponding memory chip or I/O device is selected by a
decoding circuit.
Memory requires some signals to read from and write to registers and microprocessor transmits
some signals for reading or writing data.
The interfacing process includes matching the memory requirements with the microprocessor
signals. Therefore, the interfacing circuit should be designed in such a way that it matches the
memory signal requirements with the microprocessor's signals.

I/O interfacing
As we know, keyboard and displays are used as communication channel with outside world.
Therefore, it is necessarythat we interface keyboard and displays with the microprocessor. This
is called I/O interfacing. For this type of interfacing, we use latches and buffers for interfacing
the keyboards and displays with the microprocessor.
But the main drawback of this interfacing is that the microprocessor can perform only one
function.

2|Page
lOMoARcPSD| 26885763

8051 Microcontroller MemoryOrganization


Inthe 8051Microcontroller, wehave seenthe 8051 Microcontroller Introductionand Basics, Pin
Diagram, Pin Description and the Architecture overview. we will continue exploring 8051
Microcontroller by understanding the 8051 Microcontroller Memory Organization, Program
Memory (ROM), Data Memory (RAM), External Memory.

Differences between microprocessor and microcontroller


The main difference can be stated as on-chip memory i.e., a Microcontroller has both Program
Memory(ROM) and DataMemory(RAM)onthesame chip (IC), whereas a Microprocessor has to
be externally interfacing with the memory modules.

Hence, it is clear that the memory is an important part ofthe 8051 Microcontroller Architecture
(for that matter, any Microcontroller). So, it is important for us to understand the 8051
Microcontroller Memory Organization i.e., how memory is organized, how the processor
accesses each memory and how to interface external memory with 8051 Microcontroller.

Before going in to the details of the 8051 Microcontroller Memory Organization, we will firstsee
a little bit about the Computer Architecture and then proceed with memory organization of 8051
Microcontroller.
Types of ComputerArchitecture
Basically, Microprocessors or Microcontrollers are classified based on the two types ofComputer
Architecture: Von Neumann Architecture and Harvard Architecture.

VonNeumannArchitecture
Von Neumann Architecture or Princeton Architecture is a Computer Architecture, where the
Program i.e., the Instructions and the Data are stored in a single memory. Since the Instruction
Memory and the Data Memory are the same, the Processor or CPU cannot access both
Instructions and Data at the same time as they use a single bus. This type of architecture has
severe limitationsto the performance ofthe systemas it creates a bottleneck while accessing the
memory.

3|Page
lOMoARcPSD| 26885763

HarvardArchitecture
Harvard Architecture, in contrast to Von Neumann Architecture, uses separate memory for
Instruction (Program) and Data. Since the Instruction Memory and Data Memory are separate in
a Harvard Architecture, their signal paths i.e., buses are also different and hence, the CPU can
access both Instructions and Data at the same time.
AlmostallMicrocontrollers,including 8051 Microcontroller implement HarvardArchitecture.

8051 Microcontroller Memory Organization


The 8051 Microcontroller Memory is separated in Program Memory (ROM) and Data Memory
(RAM). The Program Memoryofthe 8051 Microcontroller is used for storing the programto be
executed i.e., instructions. The Data Memory on the other hand, is used for storing temporary
variable data and intermediate results.
8051 Microcontroller has both Internal ROM and Internal RAM. If the internal memory is
inadequate, you can add external memory using suitable circuits.

4|Page
lOMoARcPSD| 26885763

There is another way to fetch the instructions: ignore the Internal ROM and fetch all the
instructions only from the External p rogramMemory(ExternalROM). Forthis scenario, the EA
Pin must be connected to GND. Inthis case, the memoryaddresses of the externalROM will be
from 0000H to FFFFH.

Data Memory(RAM)of 8051Microcontroller


The Data Memory or RAM of the 8051 Microcontroller stores temporary data and intermediate
results that are generated and used during the normal operation of the microcontroller. Original
Intel’s 8051 Microcontroller had 128B of internal RAM.

5|Page
lOMoARcPSD| 26885763

But
almost all modern variants of 8051 Microcontroller have 256B of RAM. In this 256B, the first
128B i.e., memoryaddresses from00H to 7FH is divided in to Working Registers (organized as
Register Banks), Bit – Addressable Area and General Purpose RAM (also known as Scratchpad
area).
In the first 128B of RAM (from 00H to 7FH), the first 32B i.e., memory from addresses 00H to
1FH consists of 32 Working Registers that are organized as four banks with 8 Registers in each
Bank.

The 4 banks are named as Bank0, Bank1, Bank2 and Bank3. Each Bank consists of 8 registers
named as R0 – R7. Each Register can be addressed in two ways: either by name or by address.
To addressthe register byname, first the corresponding Bank must be selected. Inorderto select
the bank, wehaveto usetheRS0andRS1bitsofthe ProgramStatusWord(PSW) Register (RS0 and
RS1 are 3rd and 4th bits in the PSW Register).

When addressing the Register using its address i.e., 12H for example, the corresponding Bank
may or may not be selected. (12H corresponds to R2 in Bank2).

The next 16Bofthe RAM i.e., from20H to 2FH are Bit – Addressable memorylocations. There
aretotally128 bits that canbe addressed individuallyusing 00H to 7FH orthe entire byte can be
addressed as 20H to 2FH.

6|Page
lOMoARcPSD| 26885763

Interfacing External Memory with 8051Microcontroller


It is always good to have an option to expand the capabilities of a Microcontroller, whether it is
in terms of Memory or IO or anything else. Such expansion will be useful to avoid design
throttling. We have seen that a typical 8051 Microcontroller has 4KB of ROM and 128B ofRAM
(most modern 8051 Microcontroller variants have 8K ROM and 256B of RAM).

The designer of an 8051 Microcontroller based system is not limited to the internal RAM and
ROMpresent inthe8051Microcontroller. There isaprovisionofconnecting bothexternalRAM and
ROM i.e., Data Memory and Program.

The reason for interfacing external Program Memoryor ROM is that complex programs written
in high – level languages often tend to be larger and occupy more memory.
Another important reasonisthat chips like 8031 or 8032,which doesn’t have anyinternalROM,
have to be interfaced with external ROM.

A maximum of 64KB of Program Memory (ROM) and Data Memory (RAM) each can be
interface with the 8051 Microcontroller.

The following image showsthe block diagramof interfacing 64KB ofExternalRAM and 64KB of
External ROM with the 8051 Microcontroller.

8051Microcontroller is that Port 0 (P0) cannot be used as an IO Port as it will be used for
multiplexed address and data bus (A0 – A7 and D0 – D7). Not always, but Port 2 may be used as
higher byte of the address bus.

7|Page
lOMoARcPSD| 26885763

Embedded C Programming with KeilLanguage


Embedded C is most popular programming language in software field for developing electronic
gadgets. Each processor used in electronic system is associated with embedded software.

Embedded C programming plays a key role in performing specific function by the processor. In
day-to-daylife we used manyelectronic devicessuchas mobile phone, washing machine, digital
camera, etc. These all device working is based on microcontroller that are programmed by
embedded C.

o Easytounderstand
o HighReliability
o Portability
o Scalability

EmbeddedSystemProgramming:

Basic Declaration:

8|Page
lOMoARcPSD| 26885763

Function is a collection of statements that is used for performing a specific task and a collection
of one or more functions is called a programming language. Every language is consisting ofbasic
elements and grammatical rules. The C language programming is designed for function
withvariables, character set, datatypes, keywords, expressionand so onare used for writing a C
program.

The extension in C language is known as embedded C programming language. As compared to


above the embedded programming in C is also have some additional features like data types,
keywords and header file etc is represented by

#include<microcontroller

name.h>BasicEmbeddedCProgrammin

gSteps
Let'sseetheblockdiagramrepresentationofEmbeddedCProgramming Steps:

The microcontroller programming is different for each type of operating system. Even though
there are many operating system are exist such as Windows, Linux, RTOS, etc but RTOS has
several advantage for embedded system development.

Basics of Embedded C Program

9|Page
lOMoARcPSD| 26885763

Embedded C is one of the most popular and most commonly used Programming Languages in
the development of Embedded Systems. So, we will see some of the Basics of Embedded C
Program and the Programming Structure of Embedded C.

What is an EmbeddedSystem?
An Embedded System is a combination of Hardware and Software. My desktop computer also
has hardware and software. Does that mean a desktop computer is also an Embedded System?
NO. A desktop computer is considered a general purpose system as it can do many differenttasks
that too simultaneously. Some common tasks are playing videos, working on office suites,
editing images (or videos), browsing the web, etc.

An Embedded System is more of an application oriented system i.e. it is dedicated to perform a


single task (or a limited number oftasks, but all working for a single main aim).

An example for embedded system, which we use daily, is a Wireless Router. In order to get
wireless internet connectivity on our mobile phones and laptops, we often use routers. The task
of a wireless router is to take the signal from a cable andtransmit it wirelessly. Andtake wireless
data from the device (like a mobile) and send it throughthe cable.
We use washing machines almost daily but wouldn’t get the idea that it is an embedded system
consisting of a Processor (and other hardware as well) and software.

10|Page
lOMoARcPSD| 26885763

ComponentsofEmbeddedSystem
An Embedded System consists of four main components. They are the Processor
(MicroprocessororMicrocontroller), Memory(RAM and ROM), Peripherals (Input and Output)
and Software (main program).

Processor: The heart ofan Embedded System is the Processor. Based on the functionality ofthe
system, the processor can be anything like a General Purpose Processor, a single purpose
processor, an Application Specific Processor, a microcontroller or an FPGA.
Memory:Memoryisanother important partofanembedded system. It isdivided into RAMand
ROM. Memory in an Embedded System (ROM to be specific) stores the main program andRAM
stores the program variables and temporary data.

Peripherals: In order to communicate with the outside world or control the external devices, an
Embedded System must have Input and Output Peripherals. Some of these peripherals include
Input / Output Ports, Communication Interfaces, Timers and Counters, etc.

Software: All the hardware work according to the software (main program) written. Software
partofanEmbedded Systemincludes initializationof the system, controlling inputsand outputs,
error handling etc.

NOTE: Many Embedded Systems, usually small to medium scaled systems, generally consistsof
a Microcontroller as the main processor. With the help of a Microcontroller, the processor,
memory and few peripherals will be integrated in to a single device.

Introduction to Embedded C Programming Language


Before going in to the details of Embedded C Programming Language and basics of EmbeddedC
Program, we will first talk about the C Programming Language.

11|Page
lOMoARcPSD| 26885763

The C Programming Language became so popular that it is used in a wide range ofapplications
ranging from Embedded Systems to Super Computers.

Embedded C Programming Language, which is widely used in the development of Embedded


Systems, is an extension of C Program Language. The Embedded C Programming Languageuses
the same syntax and semantics of the C Programming Language like main function, declaration
of datatypes, defining variables, loops, functions, statements, etc.

The extension in Embedded C from standard C Programming Language include I/O Hardware
Addressing, fixed point arithmetic operations, accessing address spaces, etc.

Difference between C and EmbeddedC


There isactuallynotmuchdifference betweenCandEmbeddedCapart fromfewextensions and the
operating environment. Both C and Embedded C programming are ISO Standards that have
almost same syntax, datatypes, functions, etc.

Embedded C is basicallyanextensionto the Standard C Programming Language withadditional


features like Addressing I/O, multiple memory addressing and fixed-point arithmetic, etc.

C Programming Language is generally used for developing desktop applications, whereas


Embedded C is used in the development of Microcontroller based applications.

KeywordsinEmbeddedC
A Keyword isa specialword witha special meaning to the compiler (a CCompiler for example, is
a software that is used to convert programwritten in C to Machine Code). For example, ifwe take
the Keil’s Cx51 Compiler (a popular C Compiler for 8051 based Microcontrollers) the following
are some of the keywords:
• bit
• sbit
• sfr
• small
• large
ThefollowingtablelistsoutallthekeywordsassociatedwiththeCx51CCompiler.
_at_ alien bdata
bit code compact
data far idata
interrupt large pdata
_priority_ reentrant sbit
sfr sfr16 small
_task_ using xdata

12|Page
lOMoARcPSD| 26885763

DataTypesinEmbeddedC
Data Types in C Programming Language (or anyprogramming language for that matter) help us
declaring variables in the program. There are manydata types in C Programming Language like
signed int, unsigned int, signed char, unsigned char, float, double, etc. In addition to these there
few more data types in Embedded C.
.
• bit
• sbit
• sfr
• sfr16
ThefollowingtableshowssomeofthedatatypesinCx51Compileralongwiththeirranges.
DataType Bits(Bytes) Range
bit 1 0or1(bitaddressablepart ofRAM)
signedint 16(2) -32768to+32767
unsignedint 16(2) 0to65535
signedchar 8(1) -128to+127
unsigned 8(1) 0to255
float 32(4) ±1.175494E-38to±3.402823E+38
double 32(4) ±1.175494E-38to±3.402823E+38
sbit 1 0or1(bitaddressablepart ofRAM)
sfr 8(1) RAMAddresses(80hto FFh)
sfr16 16(2) 0to65535

Basic Structure of an Embedded C Program


The next thing to understand in the Basics of Embedded C Program is the basic structure or
Template of Embedded C Program. This will help us in understanding how an Embedded C
Program is written.
The following parts hows the basic structure of an Embedded C Program.

o Multiline Comments........... Denotedusing/*……*/


o SingleLine Comments ........... Denotedusing//
o Preprocessor Directives ...........#include<…>or#define
o Global Variables........... Accessible anywhere in theprogram
o Function Declarations .......... Declaring Function
o MainFunction ........... MainFunction,executionbeginshere
{
Local Variables .......... Variables confined to main function
Function Calls .......... Calling other Functions

13|Page
lOMoARcPSD| 26885763

InfiniteLoop............ Like while(1)orfor(;;)


Statements.....
….
….
}
o Function Definitions .......... Defining the Functions
{
LocalVariables ........... Local Variables confined to this Function
Statements.....
….
….
}

DifferentComponentsofanEmbeddedCProgram
Comments: Comments are readable text that are written to help us (the reader) understand the
code easily. They are ignored by the compiler and do not take up any memory in the final code
(after compilation).

There are two ways you can write comments: one is the single line comments denoted by// and
the other is multiline comments denoted by /*….*/.

Preprocessor Directive: A Preprocessor Directive in Embedded C is an indication to the


compiler that it must look in to this file for symbols that are not defined in the program.

Global Variables: Global Variables, as the name suggests, are Global to the program i.e., they
can be accessed anywhere in the program.

Local Variables: Local Variables, in contrast to Global Variables, are confined to their
respective function.

Main Function: Every C or Embedded C Program has one main function, from where the
execution of the program begins.

BasicEmbeddedCProgram
Till now, we have seen a few Basics of Embedded C Program like difference between C and
Embedded C, basic structure or template of an Embedded C Program and different components
of the Embedded C Program.

14|Page
lOMoARcPSD| 26885763

ExampleofEmbeddedCProgram
The following images hows the circuit diagram for the example circuit. It containsan8051based
Microcontroller (AT89S52) along with its basic components (like RESET Circuit, Oscillator
Circuit, etc.) and components for blinking LEDs (LEDs and Resistors).

In order to write the Embedded C Program for the above circuit, we will use the Keil C
Compiler. This compiler is a part of the Keil µVision IDE. The program is shown below.

#include<reg51.h>// Preprocessor Directive


voiddelay(int);//DelayFunctionDeclaration
void main(void) // Main Function
{
P1=0x00;
/* MakingPORT1pinsLOW.AlltheLEDsare OFF.
*(P1 isPORT1,asdefined inreg51.h)*/
while(1)//infiniteloop
{

P1=0xFF;//MakingPORT1PinsHIGHi.e.LEDsareON.
delay(1000);

15|Page
lOMoARcPSD| 26885763

/*CallingDelayfunctionwithFunctionparameteras1000.
*Thiswill causeadelayof 1000mSi.e.1second */
P1=0x00;// MakingPORT1PinsLOWi.e.LEDsareOFF.
delay(1000);
}
}
voiddelay(intd)//DelayFunction Definition
{

unsignedinti=0;//LocalVariable.Accessibleonlyinthisfunction.
/*Thisfollowing stepisresponsible forcausingdelay of1000mS
*(orasperthevalue enteredwhilecallingthedelayfunction)*/
for(;d>0;d–)
{
for(i=250;i>0;i–-);
for(i=248;i>0;i–-);
}
}

16|Page
lOMoARcPSD| 26885763

RTOS(Real-Time Operating Systems for Embedded Developers)


Embedded developers are often accustomed to bare metal programming or have reservations
towardsusing an RTOS. Here’s what theyare, and why you should consider using one. Today’s
product development cycles are becoming increasingly complex. With available development
time shrinking yet the required feature set expanding, busy developers need to find ways ofdoing
more in less time. It can often make sense to use a real-time operating system (RTOS) to gain
efficiencies in task management and resource sharing.

What is anRTOS?
Simply put, an RTOS is a piece of software designed to efficiently manage the time of a central
processing unit (CPU). This is especially relevant for embedded systems when time is critical.

The key difference between an operating system such as Windows and an RTOS often found in
embedded systems is the response time to external events. An ordinary OS provides a non-
deterministic response to events with no guarantee with respect to when they will be processed,
albeit while trying to stay responsive. The user perceiving the OS to be responsive is more
important than handling underlying tasks. On the other hand, an RTOS' goal is fast and more
deterministic reaction.

(RTOS):Components,Types,Examples
Real-time operating system (RTOS) is an operating system intended to serve real time
applicationthat process data as it comes in, mostlywithout buffer delay. The full formof RTOS is
Real time operating system.

In a RTOS, Processing time requirement are calculated in tenths of seconds increments oftime.It
is time-bound system that can be defined as fixed time constraints. In this type of system,
processing must be done inside the specified constraints. Otherwise, the systemwill fail.

Why use an RTOS?


Here are important reasons for usingRTOS:
• It offers priority-based scheduling ,which allowsyou toseparate analytical processing
from non-critical processing.
• The RealtimeOS provides API functions that allow cleaner and smaller application code.

17|Page
lOMoARcPSD| 26885763

• Abstracting timing dependencies and the task-based design results in fewer


interdependencies between modules.
• RTOSoffers modulartask-baseddevelopment, which allows modulartask-basedtesting.
• The task-based API encourages modular development as a task,will typicallyhave a
clearly defined role. It allows designers/teams to work independentlyontheir partsof the
project.
• AnRTOS is event-drivenwithno time wastageonprocessing time for the event which is
not occur

Terms used in RTOS


Here,are essential terms used inRTOS:
Task – A set of related tasks that are jointly able to provide some system functionality.

Job – A job is a small piece of work that can be assigned to a processor and that may or may not require
resources.

Release time of a job – It’s the time at which a job becomes ready for execution.

Execution time of a job – It is the time taken by a job to finish its execution.

Deadline of a job – It’s the time by which a job should finish its execution.

Processors – They are also known as active resources. They are important for the execution of a job.

Maximum (Relative Deadline) – It is the allowable response time of a job, called its relative deadline.

Response time of a job – It is the length of time from the release time of a job until the instant the job
finishes.

Absolute deadline – This is the relative deadline, which also includes the release time.

Components of RTOS

18|Page
lOMoARcPSD| 26885763

The Scheduler: This component of RTOS tells that in which order, the tasks can be executed
which is generally based on the priority.

Symmetric Multiprocessing (SMP): It is a number of multiple different tasks that can be


handled by the RTOS so that parallel processing can be done.

Function Library: It is an important element of RTOS that acts as an interface that helps youto
connect kernel and application code. This application allows you to send the requests to the
Kernel using a function library so that the application can give the desired results.

Memory Management: this element is needed in the system to allocate memory to every
program, which is the most important element of the RTOS.

Fast dispatch latency: It is an intervalbetweenthe terminationof the taskthat canbe identified by


the OS and the actual time taken by the thread, which is in the ready queue, that has started
processing.
User-defined data objects and classes: RTOS system makes use of programming languageslike
C or C++, which should be organized according to their operation.

The real-time operating systems can be of3types–

RTOS

HardReal SoftReal FirmReal-


Time OS TimeOS timeOS
RTOS RTOS RTOS

1. Hard Real-Time operating system:


These operating systems guarantee that critical tasks be completed within a range of time.
For example, a robot is hired to weld a car body. Ifthe robot welds too early or too late, the
carcannotbesold, so it is a hard real-time system that requires complete car welding by

19|Page
lOMoARcPSD| 26885763

robot hardlyonthe time., scientific experiments, medical imaging systems, industrialcontrol


systems, weapon systems, robots, air traffic control systems, etc.

2. Soft real-time operating system:


This operating system provides some relaxation in the time limit.
For example – Multimedia systems, digital audio systems etc. Explicit, programmer-defined
and controlled processes are encountered inreal-time systems. Aseparate process is changed
withhandling a single externalevent. The process is activated uponoccurrence ofthe related
event signalled by an interrupt.

Multitasking operationis accomplished byscheduling processes for execution independently


of each other. Each process is assigned a certain level of priority that corresponds to the
relative importance of the event that it services. The processor is allocated to the highest
priorityprocesses.

3. FirmReal-timeOperatingSystem:
RTOS of this type have to follow deadlines as well. In spite of its small impact, missing a
deadline can have unintended consequences, including a reduction in the quality of the
product.
Example:Multimediaapplications.

MultipleTasks And MultipleProcesses

TasksandProcesses
Many (if not most) embedded computing systems do more than one thing that is, the
environment can cause mode changes that in turn cause the embedded system to behave quite
differently. For example, when designing a telephone answering machine,We can define
recording a phone call and operating the user’s control panel as distinct tasks, because they
perform logically distinct operations and they must be performed at very different rates. These
different tasks are part of the system’s functionality, but that application-level organization of
functionality is often reflected in the structure of the program as well.

A process is a single execution of a program. If we run the same programtwo different times,
we have created two different processes.Eachprocesshasitsownstatethat includesnotonlyits
registersbut allofits memory. In some OSs, the memory management unit isused to keep each
process in a separate address space. Inothers, particularlylightweight RTOSs,the processes run
inthe same address space. Processes that share the same address space are oftencalled threads.
As shown in Figure, this device is connected to serial ports on both ends. The input tothe box is
anuncompressed streamofbytes. The boxemits a compressed string ofbits onthe output serial
line,based on a predefined compressiontable.Suchaboxmaybeused,forexample,to compress data
being sent to a modem.

20|Page
lOMoARcPSD| 26885763

The controlpanelofthe compression box may, for example, include a compression mode button
that disables or enables compression, so that the input text is passed through unchanged when
compression is disabled. We certainly do not know when the user will push the compression
mode buttonthe button may be depressed asynchronously relative to the arrival ofcharacters for
compression.
MultirateSystems
Implementing code that satisfiestiming requirements iseven more complexwhen multiple rates
of computation must be handled. Multirate embedded computing systems are very common,
including automobile engines, printers, and cell phones. In all these systems, certain operations
must be executed periodically, and each operation is executed at its own rate.

TimingRequirementsonProcesses
Processes can have several different types of timing requirements imposed on them by the
application. The timing requirements on a set of processes strongly influence the type of
scheduling that is appropriate. A scheduling policy must define the timing requirements that it
uses to determine whether a schedule is valid. Before studying scheduling proper, weoutline the
types of process timing requirements that are useful in embedded system design.

Figure illustrates different ways in which we can define two important requirements on
processes: release time and deadline.
The release time is the time at which the process becomes ready to execute; this is not
necessarily the time at which it actually takes controlofthe CPU and startsto run. An aperiodic

21|Page
lOMoARcPSD| 26885763

process is bydefinition initiated byan event, such as externaldata arriving or data computed by
another process.

The release time is generally measured fromthat event, although the system may want to make
theprocessreadyat some intervalaftertheevent itself. Foraperiodicallyexecutedprocess,there are
two common possibilities.

In simpler systems, the process may become ready at the beginning of the period. More
sophisticated systems, such as those with data dependencies between processes, may set the
release time at the arrival time of certain data, at atime after the start of the period.

A deadline specifies when a computation must be finished. The deadline for an aperiodic
process is generally measured from the release time, since that is the only reasonable time
reference. The deadline for a periodic process may in general occur at some time other than the
end of the period.

Rate requirements are also fairly common. A rate requirement specifies how quickly processes
must be initiated.

The periodofa process is the time between successive executions. For example, the period ofa
digital filter is defined by the time interval between successive input samples.

22|Page
lOMoARcPSD| 26885763

The process’s rate is the inverse ofits period. Ina multirate system, eachprocess executes at its
own distinct rate.

The most common case for periodic processes is for the initiation interval to be equal to the
period. However, pipelined execution of processes allows the initiation interval to be less than
the period. Figureillustrates process execution in a system with four CPUs.

CPU Metrics
We also need some terminology to describe how the process actually executes. The initiation
time isthetimeatwhichaprocessactuallystartsexecutingontheCPU. The completion time is the time
at which the process finishes its work.

The most basic measure of work is the amount of CPU time expended by a process. The CPU
time of process i is called Ci . Notethat the CPU time is not equalto the completion time minus
initiation time; several other processes may interrupt execution. The total CPU time consumedby
a set of processes is
T=∑Ti

We need a basic measure ofthe efficiency with which we use the CPU. The simplest and most
direct measure is utilization:

U=CPUtimeforusefulwork/totalavailableCPUtime

Utilization is the ratio of the CPU time that is being used for useful computations to the total
available CPU time. This ratio ranges between 0 and 1, with 1 meaning that all of the available
CPUtime is beingused forsystempurposes. The utilization isoftenexpressedasapercentage. If we
measure the total execution time of all processes over an interval of time t, then the CPU
utilization is
U=T/t.

23|Page
lOMoARcPSD| 26885763

Multi rate Systems


Implementing code that satisfies timing requirements is even more complex when
multiple ratesofcomputation must behandled. Multirateembedded computing systems arevery
common, including auto mobile engines, printers, and cell phones.In all these systems, certain
operations must be executed periodically and each oper-ation is executed at its own rate.
Application Example6.1 describes why auto mobile engines require multi rate control.

Timing Requirements on Processes


Processes can have several different types of timing requirements imposed on them bythe
application. The timing requirements on a set of process strongly influence the type of
scheduling that is appropriate. A scheduling policy must define the timing requirements that it
uses to determine whether a schedule is valid. Before studying scheduling proper, weoutline the
types of process timing requirements that are useful in embedded system design. Figure
illustrates different ways in which we can define two important requirements on processes: eg.
What happens when a process misses a deadline? The practical effects of a timing violation
depend on the application—the results can be catastrophic in an auto mo- tive control system,
where as a missed deadline in a multimedia system may cause an audio or video glitch. The
system can be designed to take a variety of actions when a deadline is missed. Safety-critical
systems may try to take compensatory measures such as approximating data or switching in to a
special safety mode. Systems for which safety is not as important may take simple measures to
avoid propagating bad data, such as inserting silence in a phone line, or may completely ignore
the failure.Even if the modules are functionally correct, their timing improper behavior can
introduce major execution errors. Application Example6.2 describes a timing problem in space
shuttle software that caused the delayof the first launch of the shuttle. We need a basic measure
of the efficiency with which we use the CPU. The simplest and most direct measure isutilization:

Utilization is the ratio of the CPU time that is being used for useful computations to the total
available CPUtime. This ratio ranges between 0 and 1, with 1 meaning that all of the available
CPUtime isbeing usedforsystempurposes.Theutilization isoftenexpressedasapercentage. If

24|Page
lOMoARcPSD| 26885763

we measure the total execution time of all processes over an interval of time t, then the CPU
utilization is U/T

Process State andScheduling


The first job of the OS is to determine that process runs next. The work of choosing the
order of running processes is known as scheduling. The OS considers a process to be in one of
three basic scheduling states

Schedulability means whether there exists a schedule of execution for the processes in a system
that satisfies all their timing requirements. In general, we must construct a schedule to show
schedulability, but insome caseswe caneliminate some setsofprocessesasunschedulable using
some very simple tests. Utilization is one of the key metrics in evaluating a scheduling policy.
Our most basic require- ment is that CPU utilization be no more than 100% since wecan’t use the
CPU more than100% of the time.

When we evaluate the utilization of the CPU, we generallydo soover a finite period that covers
all possible combinations of process executions. For periodic processes, the length of time that
must be considered is the hyper period, which is the least-common multiple ofthe periods ofall
the processes. If we evaluate the hyper period, we are sure to have considered all possible
combinations of the periodic processes.

Context Switch IN OperatingSystem


An operating system is a program loaded into a system or computer. and manage all the
other program which is running on that OS Program, it manages the all other application
programs. or in other words, we can say that the OS is an interface between the user and
computer hardware.
.

25|Page
lOMoARcPSD| 26885763

ContextSwitch
Context switching in an operating system involves saving the context or state of a running
process so that it can be restored later, and then loading the context or state of another. process
and run it.

Context Switching refers to the process/method used by the system to change the process from
one state to another using the CPUs present in the system to perform its job.

Example – Suppose in the OS there (N) numbers of processes are stored in a Process Control
Block(PCB). like The process isrunning using the CPUto do itsjob. While a processisrunning,
other processes with the highest priorityqueue up to use the CPU to complete their job.

The Need for ContextSwitching


Context switching enables allprocesses to share a single CPU to finish their execution and store
the status of the system’s tasks. The execution of the process begins at the same place where
there is a conflict when the process is reloaded into the system.

The operating system’s need for context switching is explained by the reasons listed below.
1. One process does not directly switch to another within the system. Context switchingmakes it
easier fortheoperating systemtousethe CPU’sresourcesto carryoutitstasksandstoreits context
while switching between multiple processes.
2. Context switching enables all processes to share a single CPU to finish their execution and
store the status of the system’s tasks. The execution of the process begins at the same place
where there is a conflict when the process is reloaded into the system.
3. Context switching enables all processes to share a single CPU to finish their execution and
store the status of the system’s tasks. The execution of the process begins at the same place
where there is a conflict when the process is reloaded into the system.
4. Context switching only allows a single CPU to handle multiple processes requests parallelly
without the need for any additional processors.

ContextChangesasaTrigger
The three different categories of context-switching triggers areas follows.
1. Interrupts
2. Multitasking
3. User/Kernelswitch

Interrupts: When a CPU requests that data be read from a disc, if any interruptions occur,
context switching automatically switches to a component of the hardware that can handle the
interruptions more quickly.

26|Page
lOMoARcPSD| 26885763

Multitasking: The abilityfor a processto be switched fromthe CPU sothat another processcan
run is known as context switching. When a process is switched, the previous state is retained so
that the process can continue running at the same spot in the system.

Kernel/User Switch: This trigger is used when the OS needed to switch between the user mode
and kernel mode.

When switching between user mode and kernel/user mode is necessary, operating systems use
the kernel/user switch.

ProcessControlBlock
The Process Control block(PCB) is also known as a Task Control Block. it represents a
process in the Operating System. A process control block (PCB) is a data structure used by a
computer to store all information about a process. It is also called the descriptive process. Whena
process is created (started or installed), the operating system creates a process manager.

StateDiagramofContext Switching

Working Process Context Switching


So the context switching of two processes, the priority-based process occurs in the ready queue
of the process control block. These are the following steps.

27|Page
lOMoARcPSD| 26885763

 The state of the current process must be saved for rescheduling.


 The process state contains records, credentials, and operating system-specific information stored on
the PCB (Process Control Block) or switch.
 The PCB can be stored in a single layer in kernel memory or in a custom OS file.
 A handle has been added to the PCB to have the system ready to run.
 The operating system aborts the execution of the current process and selects a process from the
waiting list by tuning its PCB.
 Load the PCB’s program counter and continue execution in the selected process.
 Process/thread values can affect which processes are selected from the queue; this can be important.

Priority Scheduling Algorithm: Preemptive,Non-Preemptive


What is Priority Scheduling?
Priority Scheduling is a method of scheduling processes that is based on priority. In this
algorithm, the scheduler selects the tasks to work as per the priority.
The processes with higher priority should be carried out first, whereas jobs with equal priorities
are carried out on a round-robin or FCFS basis. Priority depends upon memory requirements,
time requirements, etc.

Types of Priority Scheduling


Priority scheduling divided into two main types:

Preemptive Scheduling
In Preemptive Scheduling, the tasks are mostly assigned with their priorities. Sometimes it is
important to runatask witha higher prioritybefore another lower prioritytask, even ifthe lower
priority task is still running. The lower priority task holds for some time and resumes when the
higher priority task finishes its execution.

Non-PreemptiveScheduling
Inthis type ofscheduling method, the CPU has beenallocated to a specific process. The process
that keeps the CPU busy, will release the CPU either by switching context or terminating. It is
the only method that can be used for various hardware platforms. That’s because it doesn’t need
special hardware (for example, a timer) like preemptive scheduling.

Example of PriorityScheduling
Consider following fiveprocessesP1to P5.Eachprocesshasitsuniquepriority,bursttime,and arrival
time.

28|Page
lOMoARcPSD| 26885763

Process Priority Bursttime Arrivaltime


P1 1 4 0
P2 2 3 0
P3 1 7 6
P4 3 4 11
P5 2 2 12
Step0)Attime=0,ProcessP1andP2arrive.P1hashigherprioritythanP2.Theexecution begins with
process P1, which has burst time 4.

Step1)Attime=1,nonewprocessarrive.ExecutioncontinueswithP1.

Step2)At time2 ,no new process arrives,so you can continue with P1.P2 is in the waiting queue.

29|Page
lOMoARcPSD| 26885763

Step3)At time3,no new process arrives so you can continue with P1.P2 process still in the
waiting queue.

Step4)At time4,P1has finished its execution.P2 starts execution.

Step5)At time=5,no new process arrives,sowe continue with P2.

Step6)At time=6, P3arrives. P3isat higher priority(1)compared to P2 having priority(2).P2 is


preempted, and P3 begins its execution.

30|Page
lOMoARcPSD| 26885763

Process Priority Bursttime Arrivaltime


P1 1 4 0
P2 2 1outof3pending 0
P3 1 7 6
P4 3 4 11
P5 2 2 12

Step7)At time7,no-new process arrives,so we continue with P3.P2 is in the waiting queue.

Step8)At time=8,no new process arrives,so we can continue with P3.

Step9)At time=9, no new process comes so we can continue with P3.

31|Page
lOMoARcPSD| 26885763

Step10)At time interval10, no new process comes,so we continue with P3

Step11)At time=11,P4 arrives with priority4.P3 has higher priority,so it continues its execution.
Process Priority Bursttime Arrivaltime
P1 1 4 0
P2 2 1outof3pending 0
P3 1 2outof7pending 6
P4 3 4 11
P5 2 2 12

Step12)At time=12,P5 arrives.P3 has higher priority,so it continues execution.

32|Page
lOMoARcPSD| 26885763

Step13) Attime=13,P3 completes execution.We have P2,P4,P5 in ready queue.P2andP5 have


equal priority. Arrival time of P2 is before P5. So P2 starts execution.
Process Priority Bursttime Arrivaltime
P1 1 4 0
P2 2 1outof3pending 0
P3 1 7 6
P4 3 4 11
P5 2 2 12

Step14)Attime=14,the P2 processhas finished its execution.P4 and P5 are in the waiting state.
P5 has the highest priority and starts execution.

Step15)At time=15,P5continues execution.

33|Page
lOMoARcPSD| 26885763

Step16) At time=16,P5 is finished with its execution.P4 is the only processleft.Itstarts execution.

Step17)At time=20, P5 has completed execution and no process isleft.

Step18)Let’s calculate the average waiting time for the above example.
Waiting Time = start time – arrival time + wait time for next burst
P1=o-o=o
P2=4-o+7=11
P3=6-6=0
P4=16-11=5
Average Waiting time=(0+11+0+5+2)/5=18/5=3.

34|Page
lOMoARcPSD| 26885763

35|Page
UNIT III
IOT AND ARDUINO PROGRAMMING

Introduction to the Concept of IoT Devices – IoT Devices Versus Computers – IoT
Configurations – Basic Components – Introduction to Arduino – Types of Arduino –
Arduino Toolchain – Arduino Programming Structure – Sketches – Pins –Input/Output
From Pins Using Sketches – Introduction to Arduino Shields –Integration of Sensors
and Actuators with Arduino.

WhatIsIot:
IoT stands for Internet of Things. It refers to the interconnectedness of physical
devices, such as appliances and vehicles, that are embedded with software, sensors, and
connectivity which enables these objects to connect and exchange data. This technology
allows for the collection and sharing of data from a vast network of devices, creating
opportunities for more efficient and automated systems.

Internet of Things (IoT) is the networking of physical objects that containelectronics


embedded within their architecture in order to communicate and
senseinteractionsamongsteachotherorwithrespecttotheexternalenvironment.Inthe
upcomingyears,IoT-basedtechnologywillofferadvancedlevelsofservicesand practically change
the way people lead their daily lives. Advancements in medicine, power, gene therapies,
agriculture, smart cities, and smart homes are just a very few of thecategorical examples
where IoT is strongly established.

IoT is network of interconnected computing devices which are embedded in


everyday objects, enabling them to send and receive data. Over 9 billion „Things‟
(physical objects) are currently connected to the Internet, as of now. In the near future, this
number is expected to rise to a whopping 20 billion.

There are two ways of building IoT:


1. For ma separate internet work including only physical objects.
2. Make the Internet ever more expansive, but this requires hard-core technologies such as
rigorous cloud computing and rapid big data storage (expensive).
In the near future, IoT will become broader and more complex in terms of scope. It
will change the world in terms of “anytime, anyplace, anything in connectivity.”

IoTEnablers:
 RFIDs: uses radio waves in order to electronically track the tag attached to each physical
object.
 Sensors: devices that are able to detect changes in an environment (ex:motion detectors).
Different types of Sensors:
1. Temperature Sensors
2. Image Sensors
3. Gyro Sensors
4. Obstacle Sensors
5. RF Sensor
6. IR Sensor
7. MQ-02/05GasSensor
8. LDR Sensor
9. Ultrasonic Distance Sensor

 Nano technology: as the name suggests, these are extremely small devices with
dimensions usually less than a hundred nanometers.
 Smart networks:(ex:meshtopology).

Working with IoT Devices:


 CollectandTransmitData: Forthispurposesensorsarewidely usedtheyareusedas per
requirements in different application areas.
 Actuate device based on triggers produced by sensors or processing devices : If certain
condition is satisfied or according to user‟s requirements if certain trigger is activatedthen
which action to performed that is shown by Actuator devices.
 Receive Information : From network devices user or device can take certain information
also for their analysis and processing purposes.
 Communication Assistance : Communication assistance is the phenomena of
communication between 2 network or communication between 2 or more IoT devices of
same or different Networks. This can be achieved by different communication protocols
like : MQTT , Constrained Application Protocol, ZigBee, FTP, HTTP etc.

WorkingofIoT
CharacteristicsoftheInternetofThings

The Internet of Things (IoT) is characterized by the following key features that arementioned
below.
1. Connectivity

Connectivity is an important requirement of the IoT infrastructure. Things of IoT should be


connected to the IoT infrastructure. Anyone, anywhere, anytime can connect, this should be
guaranteedatalltimes. For example,the connectionbetweenpeople throughInternet devices like
mobile phones, and other gadgets, also a connection between Internet devices such as routers,
gateways, sensors, etc.
2. IntelligenceandIdentity

The extraction of knowledge from the generated data is very important. For example, asensor
generates data, but that data will only be useful if it is interpreted properly. Each IoT device
has a unique identity. This identification is helpful in tracking the equipment and at times for
querying its status.
3. Scalability

The number of elements connected to the IoT zone is increasing day by day. Hence, an IoT
setup should be capable of handling the massive expansion. The data generated as anoutcome
is enormous, and it should be handled appropriately.

4. Dynamic and Self-Adapting (Complexity)


IoT devices should dynamically adapt themselves to changing contexts and scenarios. Assume a camera
meant for surveillance. It should be adaptable to work in different conditions and different light situations
(morning, afternoon, and night).

1. Architecture
IoT architecture cannot be homogeneous in nature. It should be hybrid, supporting different
manufacturers' products to function in the IoT network. IoT is not owned by any one engineering
branch. IoT is a reality when multiple domains come together.
2. Safety
There is a danger of the sensitive personal details of the users getting compromised when all
his/her devices are connected to the internet. This can cause a loss to the user. Hence, data
security is the major challenge. Besides, the equipment involved is huge. IoT networks may also
be at risk. Therefore, equipment safety is also critical.
3. Self-Configuring
This is one of the most important characteristics of IoT. IoT devices are able to upgrade their
software in accordance with requirements with a minimum of user participation. Additionally,
they can set up the network, allowing for the addition of new devices to an already-existing
network.
4. Interoperability
IoT devices use standardized protocols and technologies to ensure they can communicate with
each other and other systems. Interoperability is one of the key characteristics of the Internet of
Things (IoT). It refers to the ability of different IoT devices and systems to communicate and
exchange data with each other, regardless of the underlying technology or manufacturer.
5. Embedded Sensors and Actuators
Embedded sensors and actuators are critical components of the Internet of Things (IoT). They
allow IoT devices to interact with their environment and collect and transmit data.
6. Autonomous Operation
Autonomous operation refers to the ability of IoT devices and systems to operate independently
and make decisions without human intervention. This is a crucial characteristic of the Internet of
Things (IoT) and enables a wide range of new applications and services.

Here is the paragraph with proper spacing:

**Configuring an Internet of Things (IoT)**


Identify your IoT components: Determine the devices and sensors you will be using in your
IoT network. These could include sensors, actuators, gateways, and edge devices.

**Choose a Communication Protocol:**


Decide on the communication protocol you'll use for your devices to exchange data.
Common protocols include MQTT, CoAP, HTTP, and AMQP. Choose a protocol based on
factors like the type of data you'll be transmitting, the reliability needed, and the network
environment.

**Set Up Network Infrastructure:**


Ensure you have a stable and secure network infrastructure in place. This might include Wi-
Fi, Ethernet, cellular, or even LoRaWAN for long-range low-power communication.

**Device Registration and Onboarding:**


Register each IoT device to your network. This might involve provisioning them with
necessary credentials (such as certificates) to ensure secure communication.

**Security Measures:**
Implement security mechanisms to protect your IoT ecosystem from unauthorized access,
data breaches, and cyberattacks. This could involve using encryption, secure bootstrapping,
device authentication, and firewalls.

**Data Collection and Transmission:**


Configure devices to collect the required data from sensors and other sources. Set up rules for
data transmission frequency, conditions, and thresholds. Ensure that data is sent efficiently to
minimize network usage.
Data Processing at the Edge: If you're using edge computing, configure devices or
gateways to process data locally before sending it to the cloud. This reduces latency and
conserves bandwidth.
Cloud Integration: Integrate your IoT system with cloud platforms like AWS IoT,
Microsoft Azure IoT, or Google Cloud IoT. Configure end points, authentication, and data
routing to the cloud services.
Data Storage and Analytics: Set up data storage and analytics pipelines to process and
analyze the incoming data. This might involve using databases, data lakes, and analytics tools
to gain insights from the collected data.
Remote Device Management: Implement mechanisms for remote device management, such
as firm ware updates, configuration changes, and diagnostics. Over-the-air(OTA)update scan
be critical for maintaining device security and functionality.
Scalability Planning: Consider how your IoT system will scale as you add more devices and
sensors. Design the architecture in a way that allows easy scalability without major
disruptions.
Monitoring and Maintenance: Set up monitoring tools to keep track of the health,
performance, and security of your IoT devices and network. Implement automated alerts for
abnormal conditions.
Compliance and Regulations: Ensure that your IoT system complies with relevant
regulations and standards, especially if it involves sensitive or personal data.
Testing and Iteration: Thoroughly test your IoT configuration in a controlled environment
before deploying it at scale. Make necessary adjustments based on testing results and user
feedback.
Documentation: Maintain comprehensive documentation of your IoT configuration,
including device specifications, network settings, security measures, and communication
protocols. This documentation will be valuable for trouble shooting and future
enhancements.

TypesofIoT Applications:

IoT devices span a wide range of industries and applications, including:

 Home Automation: Smart thermostats, doorbell cameras,smart lights, and connected


appliances.
 Healthcare: Wearable fitness trackers, remote patient monitoring devices, and
medical implants.
 Industrial IoT(IIoT): Sensors and monitors used in manufacturing, supply chain
management, and predictive maintenance.
 Agriculture: Soil moisture sensors, GPS trackers for livestock, and automated irrigation
systems.
 SmartCities: Connected street lights,waste management systems, and traffic monitoring.
 Automotive: Connected vehicles, vehicle-to-vehicle(V2V) communication,and self-driving
cars.

BenefitsofIoT Devices:

 Efficiency: IoTdevicescanoptimizeprocesses,reducewaste,andenhanceresource
utilization.
 Automation: Taskscanbeautomatedbasedonreal-timedata,leadingtoimproved
productivity.
 Data-DrivenInsights: IoTdevicesprovidedatathatcanbeanalyzedtogaininsights,make
informed decisions, and identify trends.
 RemoteMonitoringand Control: Devicescanbemonitoredandcontrolledremotely,
enabling real-time adjustments.
 EnhancedUserExperience: IoTdevicescreatepersonalizedexperiencesandconvenience for
users.

ChallengesandConsiderations:

 Securityand Privacy:IoTdevicescanbevulnerabletocyberattacks ifnotproperlysecured.


 Interoperability: Ensuringthatdevicesfromdifferentmanufacturerscancommunicate
seamlessly.
 Scalability: Handlingalargenumber ofdevices anddata pointscan bechallenging.
 PowerManagement: Ensuringdeviceshaveadequatepowerandoptimizingenergy
consumption.
 DataManagement: Efficientlyhandlingandprocessingthevastamountofdatagenerated by
IoT devices.

BasiccomponentsofIoT:

 Devices/Things: These are physical objects embedded with sensors, actuators, and communication
modules that enable them to collect data, perform actions, and communicate over the internet. Devices can
range from simple sensors to complex machinery.

 Sensors: Sensors are components that detect changes in the environment and convert physical
phenomena (like temperature, light, pressure, humidity, etc.) into electrical signals that can be processed by
IoT devices.
 Actuators: Actuators are devices that perform actions based on the data received from sensors or
commands from remote systems. Examples include motors, servos, solenoids, and relays.

 Computing Units: These are the computing units within IoT devices. They process data from sensors,
control actuators, and execute programmed instructions. They also manage communication with other
devices and systems.

 Communication Modules: IoT devices need communication capabilities to send and receive data over
the internet. Communication modules can include Wi-Fi, Bluetooth, Zigbee, LoRa, cellular, Ethernet, and
more.

 Network Infrastructure: This includes the underlying network that enables devices to connect to the
internet. It can be wired (like Ethernet) or wireless (like Wi-Fi, cellular, or satellite).

 Internet Connectivity: The devices need access to the internet to communicate with other devices and
central systems. This connectivity can be through Wi-Fi, cellular networks, satellite connections, or other
means.

 Cloud Platforms: Cloud platforms provide storage, computing power, and services that enable data
processing, analysis, storage, and remote control of IoT devices. Cloud services facilitate the scalability and
management of IoT solutions.

 Data Processing and Storage: IoT devices generate a vast amount of data. Data processing involves
analyzing and interpreting this data to extract meaningful insights. Data storage involves storing the
collected data for future reference and analysis.

 User Interfaces: User interfaces can be web applications, mobile apps, or dashboards that allow users to
monitor and control IoT devices remotely. These interfaces provide real-time information and enable users
to set preferences or receive alerts.

 Security: Security is critical in IoT to protect data, devices, and networks from unauthorized access and
cyberattacks. Security measures include encryption, authentication, access controls, and regular software
updates.

 Power Management: IoT devices often operate on limited power sources such as batteries. Power
management strategies are essential to optimize energy consumption and extend the device's operational
lifespan.

 Data Analysis: Analyzing the data collected from IoT devices can yield valuable insights for making
informed decisions, predicting trends, and improving operations.

 Machine Learning and Artificial Intelligence (AI): IoT systems can leverage machine learning and AI
to improve automation, anomaly detection, and decision-making based on real-time data.

ModernApplications:
 Smart Grids and energy saving
 Smart cities
 Smart homes/Home automation
 Healthcare
 Earthquake detection
 Radiation detection/hazardous gas detection
 Smartphone detection
 Water flow monitoring
 Traffic monitoring
 Wearables
 Smart door lock protection system
 Robots and Drones
 Healthcare and Hospitals, Telemedicine applications
 Security
 Biochip Transponders (For animals in farms)
 Heart monitoring implants (Example: Pacemaker, ECG real-time tracking)
AdvantagesofIoT:
1. Improved efficiency and automation of tasks.
2. Increased convenience and accessibility of information.
3. Better monitoring and controlof devices and systems.
4. Greater ability together and analyze data.
5. Improved decision-making.
6. Cost savings.

Disadvantages of IoT:
 Security concerns and potential for hacking or data breaches.
 Privacy issues related to the collection and use of personal data.
 Dependence on technology and potential for system failures.
 Limited standardization and interoperability among devices.
 Complexity and increased maintenance requirements.
 High initial investment costs.
 Limited battery life on some devices.
 Concerns about job displacement due to automation.
 Limited regulation and legal framework for IoT, which can lead to confusion and uncertainty.
Overview of IoT Vs Computers:

One big difference between IoT devices and computers is that the main function of IoT
devices is not to compute(not to be a computer) and the main function of a computer is to
compute functions and to run programs. But on IoT devices that is not its main point, it
hassomeotherfunctionbesidesthat.Asanexamplelikeincars,thefunctionofIoTdevicesare not to
compute anti-lock breaking or to do fuel injection, their main function from the point of view of
a user is to be driven and to move you from place to place and the computer is just to help that
function. For example, The main function of the car is not to compute like anti-lock breaking or
to do fuel injection their main function from the point of view of a user isto drive, to move you
from place to place. But when we embed software in it then the software can beable for fuel limit
detection.

Difference between IoT devices and Computers:

Computers
IOT Devices

IoT devices are special-purpose devices. Computers are general-purpose devices.

IoT devices can do only a particular task


Computer scan do so many tasks.
for which it is designed.

The hardware and software built-in the


The hardware and software built-in the IoT
computers are streamlined to do many
devices are streamlined for that particular
tasks(such as calculation, gaming, music
task.
player, etc. )

IoT devices can be cheaper and faster at a


particular task than computers, as IoT A computer can be expensive and slower at a
devices are made to do that particular task. particular task than an IoT device.

Examples: Music Player-iPod, Alexa,


Examples :Desktop computers, Laptops, etc.
smart cars, etc.
Introduction to Arduino

Arduino is a project, open-source hardware, and software platform used to design and
build electronic devices. It designs and manufactures microcontroller kits and single-board
interfaces for building electronics projects.

The Arduino boards were initially created to help the students with the non-technical
background. The designs of Arduino boards use a varietyof controllers and microprocessors.

The Arduino board consists of sets of analog and digital I/O (Input / Output) pins,
which are further interfaced to breadboard, expansion boards, and othercircuits. Such
boardsfeaturethemodel,UniversalSerialBus(USB),andserialcommunicationinterfaces, which
are used for loading programs from the computers.

Types ofArduino
The flexibility of the Arduino board is enormous so that one can do anything they
imagine. This board can be connected very easily to different modules such as obstacle
sensors, presence detectors, fire sensors, GSM Modules GPS modules, etc.

The main function of the Arduino board is to control electronics through reading
inputs &changing it into outputs because this board works like a tool. This boardis also used
to make different electronics projects in the field of electronics, electrical, robotics, etc.

Features of Different Types of Arduino Boards


The features of different types of Arduino boards are listed in tabular form.
Arduino Digital Analogue
Processor Memory
Board I/O I/O

6 input,
Arduino Uno 16MhzATmega328 2KBSRAM, 32KB flash 14
0 output

12 input,
Arduino Due 84MHz AT91SAM3X8E 96KBSRAM, 512KB flash 54
2 output
16 input,
Arduino Mega 16MHz ATmega2560 8KBSRAM, 256KB flash 54
0 output
12 input,
Arduino Leonardo 16MHz ATmega32u4 2.5KBSRAM, 32KB flash 20
0 output

Different Types Of Arduino Boards


The list of Arduino boards includes the following such as

 Arduino Uno(R3)
 Arduino Nano
 Arduino Micro
 ArduinoDue
 LilyPadArduinoBoard
 Arduino Bluetooth
 Arduino Diecimila
 RedBoardArduino Board
 ArduinoMega(R3) Board
 ArduinoLeonardoBoard
 Arduino Robot
 Arduino Esplora
 ArduinoPro Mic
 Arduino Ethernet
 ArduinoZero
 FastestArduino Board

Arduino Uno(R3)
The Uno is a huge option for your initial Arduino. This Arduino board depends on an
ATmega328P based microcontroller. As compared with other types of arduino boards, it is
verysimpletouseliketheArduinoMegatypeboard..Itconsistsof14-digital I/Opins, where 6-pins
can be used as PWM(pulse width modulation outputs), 6-analog inputs, a reset button, a
power jack, a USB connection, an In-Circuit Serial Programming header (ICSP), etc.

It includes everything required to hold up the microcontroller; simply attach it to a PC


with the help of a USB cable and give the supply to get started with an AC-to-DC adapter or
battery.

ArduinoUno(R3)

Arduino Uno is the most frequently used board and it is the standard form apart from
all the existing Arduino Boards. This board is very useful for beginners. Please refer to this
link to know more about Arduino Uno Board

Arduino Nano
This is a small board based on the microcontrollers like ATmega328P otherwise
ATmega628 but the connection of this board is the same as to the Arduino UNO board. This
kind of microcontroller board is very small in size, sustainable, flexible, and reliable.
ArduinoNano

As compared with the Arduino Uno board, it is small in size. The devices like mini
USB and Arduino IDE are necessaryto build the projects. This board mainlyincludes analog
pins-8, digital pins-14 with the set of an I/O pin, power pins-6 & RST (reset) pins-2. Please
refer to this link to know more about Arduino Nano Board.

Arduino Micro
The Arduino Micro board mainly depends on the ATmega32U4 based
Microcontroller that includes 20-sets of pins wherethe7-pins are PWM pins, 12-analoginput
pins. This board includes different components like an ICSP header, RST button, small USB
connection, crystal oscillator-16MHz. The USB connection is inbuilt and this board is the
shrunk version of the Leonardo board.

Arduino Micro

Arduino Due
This Arduino board depends on the ARM Cortex-M3 and it is the first Arduino
microcontroller board. This board includes digital I/O pins-54 where 12-pins are PWM o/p
pins, analog pins -12, UARTs-4, a CLK with 84 MHz, an USB OTG, DAC-2, a power jack,
TWI-2, a JTAG header, an SPI header, two buttons for reset & erase.

ArduinoDue
This board works with 3.3V where the highest voltage that the pins of input/outputcan
stand is 3.3V because providing a high voltage to any I/O pin can lead to damage the board
This board is simply connected to a computer through a small USB cable otherwise it can be
powered through an AC to DC adapter. This Arduino Due board is suitable with all shields of
Arduino at 3.3V.

LilyPad Arduino Board


The Lily Pad Arduino board is a wearable e-textile technology expanded by Leah “
Buechley” and considerately designed by “Leah and SparkFun”. Each board was
imaginatively designed with huge connecting pads & a smooth back to let them to be sewn
into clothing using conductive thread. This Arduino also comprises of I/O, power, and also
sensor boards which are built especially for e-textiles. These are even washable!

LilyPadArduinoBoards

Arduino Bluetooth
This Bluetooth mainly depends on the microcontroller like ATmega168 and thisboard
is also called Arduino BT. This kind of board includes different components likedigital pins-
16, analog pins-6, crystal oscillator-16MHz, reset button, screw terminals, ICSP header. In
this board, the screw terminals are mainly used for power. The programming ofthis Bluetooth
microcontroller can be done with Bluetooth like a wireless connection.

Arduino Diecimila
The microcontroller board like Arduino Diecimila mainly depends on the
ATmega168. This board includes digital I/O pins -14 where 6-pins can be used like PWM
outputs & analog inputs-6, a USB connection, a crystal oscillator-16 MHz, an ICSP header, a
reset button & a power jack. This board can be connected to a computer through a USB cable
and it can be activated using a battery and an AC-DC adapter.

Arduino Diecimila
As the name suggests, the meaning of Diecimila in Italian is 10,000 which means that
marks the truth that above 10k Arduino boards have been designed. In a set of USB Arduino
boards, it is the latest one as compared with other versions.

Red Board Arduino Board


The Red Board Arduino board can be programmed using a Mini-B USB cable using
the Arduino IDE. ItwillworkonWindows8withouthavingtomodifyyoursecuritysettings. It is
more constant due to the USB or FTDI chip we used and also it is entirely flat on the back.
Creating it is very simple to utilize in the project design. Just plug the board, select the menu
option to choose an Arduino UNO and you are ready to upload the program. You can control
the Red Board over a USB cable using the barrel jack.

RedBoardArduino Boards

Arduino Mega(R3)Board
The Arduino Mega is similar to the UNO‟s big brother. It includes lots of digital I/O
pins (from that, 14-pins can be used as PWM o/ps), 6-analog inputs, a reset button, a power
jack, a USB connection, and a reset button. It includes everything required to hold up the
microcontroller; simply attach it to a PC with the help of a USB cable and give the supply to
get started with an AC-to-DC adapter or battery. The huge number of pins make this Arduino
board very helpful for designing projects that need a bunch of digital i/ps or o/ps like lots of
buttons. Please refer to this link to know more about Arduino Mega (R3) Board

ArduinoMega(R3) Board

Arduino Leonardo Board


The first development board of an Arduino is the Leonardo board. This board usesone
microcontroller along with the USB. That means, it can be very simple and cheap also.
Because this board handles USB directly, program libraries are obtainable which let the
Arduino board to follow a keyboard of the computer, mouse, etc.
ArduinoLeonardoBoard

Arduino Robot
This kind of board is the first Arduino over wheels. This Arduino robot includes two
processors on each of its boards. The two boards are the motor board and control board where
the motor board controls the motors & the control board is used to read the sensors for
operating. Every board is a complete Arduino board and its programming can be done
through the Arduino IDE. These are microcontroller boards that depend on the ATmega32u4.

The pins of this Robot are mapped to actuators and sensors onboard.The process of
programming the robot is the same as the Arduino Leonardo board. It is also named a small
computer and it is extensively used in robotics.

This board includes the speaker, color screen, buttons-5, motors-2, a digital compass,
an SD card reader, potentiometers-2 & floor sensors-5. The library of this robot can be used
for controlling the sensors as well as the actuators.

Arduino Esplora

The Arduino Esplora includes a small computer known as a microcontroller including


a number of inputs & outputs. The inputs of this board are a light sensor, four buttons, a
microphone, an accelerometer, joystick, a slider, a temperature sensor, etc whereas the
outputs are a 3 color LED, a buzzer. This kind of Arduino board looks like a videogame
controller.
The programming of this board can be done using Arduino Software like IDE which
takes the data from the inputs and controls the output like a keyboard or a mouse. As
compared with all other types of Arduino boards, this esplora is totally different because the
inputs, as well as outputs, are connected to the board already.

Arduino Esplora
So connecting the components like actuators or sensors is very simple. Thus,
programming is somewhat different as compared with other types of Arduino boards. This
esplora board includes its own library so that the data from the sensors & actuators are very
easy to read and write.

Arduino ProMic
The Arduino Pro Micro board is the same as the Arduino Mini board apart from the
ATmega32U4 Microcontroller. This pro mic board includes digital I/O pins-12, pulse width
modulation (PWM) pins-5, serial connections of Tx & Rx &10-bit ADC.

Arduino Ethernet
The Arduino Ethernet board depends on the microcontroller like ATmega328. This
kind of microcontroller board includes analog pins-5, digital I/O pins-14, RST button, an
RJ45 connection, crystal oscillator, a power jack, ICSP header, etc. The connection of the
Arduino board can be done through the Ethernet shield to the internet.

Arduino Zero
This is a powerful as well as simple 32-bit board and it provides the best platform for
innovative projects like wearable technology, smart IoT devices, crazy robotics, high-tech
automation, etc. This board expands by providing improved performance, permitting a range
of project opportunities & performs like a great educational tool.

ArduinoZero
Thisboardincludesanaloginputpins-6,digitalI/Opins-14,apowerjack,AREF button,
UART port pins, a USB connector & an In-Circuit Serial Programming (ICSP) header, a
power header, etc.

This board is power-driven through the SAMD21 microcontroller based on Atmel.


The main feature of this is EDBG (Embedded Debugger) based on Atmel and it provides a
complete debug interface without using extra hardware.

Fastest Arduino Board


Designing one of the best Arduino development boards that are familiar with Arduino
MEGA & UNO is the hifive1 board that includes a 320 MHz RISC-V microcontroller unit.
This kind of fastest board has Cortex M-7 with a 400 MHz microcontroller unit.
 Flash memory– upto2Mbytes

 RAM– 1 Mbyte
 DMAcontrollers-4
 Communication peripherals-Upto 35
 16-bitMaxResolutionwith3×ADCs
 D/Aconverterswith2× 12-bit
 Hardware with JPEG Codec
 Timers-22&Watchdogs– 200Mhz
 HW Calendar &RTC with Sub-second Accuracy
 Cryptographic Acceleration

Toolchain(IDE)
A toolchain is a set of programming tools that is used to perform a complex set of
operations. In the Arduino Software (IDE), the toolchain is hidden from the user, but it is
used to compile and upload the user Sketch. It includes a compiler, assembler, linker, and
Standard C & math libraries.The source code for the Java environment is released under the
GPL and the C/C++ microcontroller libraries are under the LGPL.

Sketch− Program coded in Arduino IDE is called a SKETCH

1. To create a new sketch: File -> New

 To open an existing sketch: File -> Open


 There are some basic ready-to-use sketches available in the EXAMPLES section
 File -> Examples -> Select any program

2. Verify: Checks the code for compilation errors


3. Upload: Uploads the final code to the controller board
4. New: Creates a new blank sketch with basic structure
5. Open: Opens an existing sketch
6. Save: Saves the current sketch

Compilation and Execution


SerialMonitor: Opens the serial console
All the data printed to the console are displayed here

StructureofSketch
A sketch can be divided into two parts:
 Setup()
 Loop()
Thefunctionsetup()isthepointwherethecodestarts,justlikethemain()functionin C and
C++
I/OVariables, pinmodes are initializedintheSetup() function
Loop()function, as the namesuggests, iterates the specified task in the program
Structure
Arduino programs can be divided in three main parts: Structure, Values (variables
and constants), and Functions. In this tutorial, we will learn about the Arduino software
program, step by step, and how we can write the program without any syntax or compilation
error.
Let us start with the structure. Software structure consists of two main functions. −
 Setup( ) function - The setup() function is called when a sketch starts. Use it to
initializethe variables (not declaration),pin modes, start using libraries, etc. Thesetup
function will only run once, after each power up or reset of the Arduino board.
 Loop( ) function - After creating a setup() function, which initializes and sets theinitial
values, the loop() function does precisely what its name suggests, and loops
consecutively, allowing your program to change and respond. Use it to activelycontrol
the Arduino board
Voidsetup ( ){

}
PURPOSE− Thesetup()function is called when a sketch starts. Use it to initializethe
variables, pin modes, start using libraries, etc. The setup function will only run once,
after each power up or reset of the Arduino board.
 INPUT −-
 OUTPUT−-
 RETURN−-
VoidLoop( ){

}
 PURPOSE− After creating asetup()function, which initializes and sets the initial
values, theloop()function does precisely what its name suggests, and loops
consecutively, allowing your program to change and respond. Use it to activelycontrol
the Arduino board.
 INPUT −-
 OUTPUT−-
 RETURN−-
ArduinoUnoPinsDiagram

ARDUINOI/O(Input,Output)Functions

1. Pin Mode()-The pin Mode()function is used to configure a specific pin to behave either
as an input or an output.

2. digitalWrite()-
ThedigitalWrite()functionisusedtowriteaHIGHoraLOWvaluetoadigitalpin.
3. digitalRead()-Readsthevaluefromaspecifieddigitalpin,eitherHIGHorLOW.

4. analogRead( ) function- we can read the voltage applied to one of the pins. This
functionreturnsanumberbetween0and1023,whichrepresentsvoltagesbetween0 and 5 volts.

5. analogWrite()function-Writesananalogvaluetoapin.
Input/Ouput(I/O)inArduino

 These functions allow access to the pins

void pinMode(pin, Mode)

 Setsapintoactaseitheraninputoranoutput
 pinisthenumberofthepin
 1-13forthedigitalpins
 A0-A5fortheanaloginputpins
 ModeistheI/Omodethepinissetto
 INPUT,OUTPUT

DigitalInput

Int digital Read(pin)

 Returns the state of an input pin


 Returns either LOW(0volts)or HIGH(5volts) int pin

val;

Pin val=digitalRead(3);

 pinvalissettothestateofdigitalpin3

Digital Output

Void digital Write(pin,value)

 Assigns thestateofanoutputpin
 AssignseitherLOW(0volts)orHIGH(5volts)

digitalWrite(3, HIGH);

 Digitalpin3issetHIGH(5volts)

Analog Input

Int analog Read(pin)

 Returns the state of analog input pin


 Returns an integer from 0to1023
 0 for 0 volts, 1023for 5volts int

pin val;

Pin val=analogRead(A3);

 P in must be an analog pin


Analog Output

 No pins can generate a true analog output


 But PWMc an be used

ARDUINO SHIELDS

The advantages of using Arduino shields are listed below:

 It adds new functionalities to the Arduino projects.


 The shields can be attached and detached easily from the Arduino board. It does not require any
complex wiring.
 It is easy to connect the shields by mounting them over the Arduino board.
 The hardware components on the shields can be easily implemented.

TypesofShields

The popular Arduino shields are listed below:

 Ethernet shield
 XBee shield
 Proto shield
 Relay shield
 Motor shield
 LCD shield
 Bluetooth shield
 Capacitive Touchpad shield
 The Ethernet shields are used to connect the Arduino board to the Internet. We need to mount the
shield on the top of the specified Arduino board.
 The USB port will play the usual role to upload sketches on the board.
 The latest version of Ethernet shields consists of a micro SD card slot. The micro SD card slot can
be interfaced with the help of the SD card library.

The Ethernet shield is shown below:


o We can also connect another shield on the top of the Ethernet shield. It means that we
can also mount two shields on the top of the Arduino board.

Xbee Shield
o WecancommunicatewirelesslywiththeArduinoboardbyusingtheXbeeShield with
Zigbee.
o Itreducesthehassleofthecable,whichmakesXbeeawirelesscommunication model.
o TheXbeewirelessmoduleallowsustocommunicateoutdoorupto300feetand indoor upto
100 feet.
o TheXbeeshield is shown below:

 It can also be used with different models of XBee.

Proto shield

 Proto shields are designed for custom circuits.


 We can solder electronic circuits directly onto the shield.
 The shield consists of two LED pads, two power lines, and SPI signal pads.
 The IOREF (Input Output voltage REFerence) and GND (Ground) are the two power lines on the
board.

The proto shield is shown below:


o We can also solder the SMD (Surface Mount Device) ICs on the prototyping area. A
maximum of 24 pins can be integrated onto the SMD area.

Relay shield

Here is the text with proper spacing:

 The Arduino digital I/O pins cannot bear the high current due to its voltage and current limits. The
relay shield is used to overcome such situations. It provides a solution for controlling the devices
carrying high current and voltage.
 The shield consists of four relays and four LED indicators.
 It also provides NO/NC interfaces and a shield form factor for simple connection to the Arduino
board.
 The LED indicators depict the ON/OFF condition of each relay.
 The relay used in the structure is of high quality.
 The NO (Normally Open), NC (Normally Closed), and COM pins are present on each relay.

The relay shield is shown below:

o The applications of the Relay shield include remote control, etc.

Motor shield

 The motor shield helps us to control the motor using the Arduino board.
 It controls the direction and working speed of the motor. We can power the motor shield either by
the external power supply through the input terminal or directly by the Arduino.We can also
measure the absorption current of each motor with the help of the motor shield.
o The motor shield is based on the L298 chip that can drive a step motor or two DC
motors. L298 chip is a full bridge IC. It also consists of the heat sinker, which
increases the performance of the motor shield.
o It can drive inductive loads, such as solenoids, etc.
o Theoperatingvoltageisfrom5Vto12V.

The Motor shield is shown below:

o Theapplications of themotor shieldareintelligentvehicles, micro-robots, etc.

LCDshield

 The keypad of the LCD (Liquid Crystal Display) shield includes five buttons called up, down, left,
right, and select.
 There are 6 push buttons present on the shield that can be used as a custom menu control panel.
 It consists of the 1602 white characters, which are displayed on the blue backlight LCD.
 The LED present on the board indicates the power ON.
 The five keys present on the board help us to make selections on menus and from the board to our
project.

The LCD shield is shown below:

o The LCD shield is popularly designed for the classic boards such as Duemilanove,
UNO, etc.
Bluetooth shield
o The Bluetooth shield can be used as a wireless module for transparent serial
communication.
o It includes a serial Bluetooth module. D0 and D1 are the serial hardware ports in the
Bluetooth shield, which can be used to communicate with the two serial ports (from
D0 to D7) of the Arduino board.
o We can install Groves through the two serial ports of the Bluetooth shield called a
Grove connector. One Grove connector is digital, while the other is analog.

The Bluetooth shield is shown below:

 The communication distance of the Bluetooth shield is up to 10 m at home without any obstacle in
between.

Capacitive Touchpad shield

 It has a touchpad interface that allows integration of the Arduino board with the touch shield.
 The Capacitive touchpad shield consists of 12 sensitive touch buttons, which include 3 electrode
connections and 9 capacitive touch pads.

The capacitive shield is shown below:

 The board can work with the logic level of 3.3 V or 5 V.


 We can establish a connection to the Arduino project by touching the shield.

INTEGRATION OF SENSORS AND ACTUATORS WITH ARDUINO.


Arduino is a popular microcontroller platform that allows you to easily interface with
various sensors and actuators to create interactive projects. Integrating sensors and actuators
with Arduino involves the following steps:

Selecting the appropriate sensors and actuators: Identify the specific sensors and
actuators you need for your project. Arduino supports a wide range of sensors such as
temperature sensors, motion sensors, light sensors, and actuators such as motors, servos, and
LEDs.

Actuators are basically mechanical or electro mechanical devices. They convert


energy or signals into motion. And mainly use to provide controlled motion to other
components of various mechanical structures or devices.
Power supply: Ensure that your sensors and actuators have a suitable power supply.
Arduino boards can usually provide power to low-power sensors and actuators directly from
theirdigitaloranalogpins.However,high-powerdeviceslikemotorsmayrequirean external power
source.

Wiring connections: Connect the sensors and actuators to the Arduino board using
jumper wires or appropriate connectors. Arduino boards typically have digital input/output
(I/O) pins, analog input pins, and power pins that you can use for wiring.

For digital sensors and actuators, you can connect them to the digital I/O pins. These
pins can be configured as either input or output. Analog sensors can be connected to the
analog input pins, which can read continuous voltage values.

Power and ground connections should be made to provide appropriate voltage and
common reference for the sensors and actuators.

Library installation: Some sensors and actuators require specific libraries to be


installed in the Arduino Integrated Development Environment (IDE). These libraries provide
pre-written code and functions that make it easier to interface with the devices. You can
install libraries by navigating to Sketch -> Include Library -> Manage Libraries in the
Arduino IDE.

Code development: Write the Arduino code to read sensor data and control the
actuators. The code should include appropriate functions and commands to initialize the
sensors, read their values, and control the actuators based on the sensor inputs. The specific
code will depend on the sensors and actuators you are using, so refer to their respective
documentation and examples.

Uploading and testing: Upload the code to the Arduino board and test the integration.
Use the Serial Monitor in the Arduino IDE to view sensor readings or debug any issues.Make
sure the sensors and actuators are functioning as expected.

By following these steps, you can integrate sensors and actuators with Arduino to
create interactive projects and prototypes. The possibilities are vast, ranging from simple
projects like temperature monitoring and LED control to complex robotics and automation
systems.
UNIT- 4 IOT COMMUNICATION AND OPEN PLATFORMS

IoT Communication Models and APIs – IoT Communication Protocols – Bluetooth –


WiFi – ZigBee– GPS – GSM modules – Open Platform (like Raspberry Pi) –
Architecture – Programming – Interfacing – Accessing GPIO Pins – Sending and
Receiving Signals Using GPIO Pins – Connecting to the Cloud.

Communication Models in IoT (Internet of Things )

IoT devices are found everywhere and will enable circulatory intelligence in the future. For
operational perception, it is important and useful to understand how various IoT devices
communicate with each other. Communication models used in IoT have great value. The
IoTs allow people and things to be connected any time, any space, with anything and
anyone, using any network and any service.

Types of Communication Model :

1.Request & Response Model

This model follows a client-server architecture.


 The client, when required, requests the information from the server. This request is
usually in the encoded format.
 This model is stateless since the data between the requests is not retained and each
request is independently handled.
 The server Categories the request, and fetches the data from the database and its
resource representation. This data is converted to response and is transferred in an
encoded format to the client. The client, in turn, receives the response.
 On the other hand — In Request-Response communication model client sends a
request to the server and the server responds to the request. When the server receives
the request it decides how to respond, fetches the data retrieves resources, and prepares
the response, and sends it to the client.
2. Publisher-Subscriber Model

This model comprises three entities: Publishers, Brokers, and Consumers.

 Publishers are the source of data. It sends the data to the topic which are
managed by the broker. They are not aware of consumers.
 Consumers subscribe to the topics which are managed by the broker.
 Hence, Brokers responsibility is to accept data from publishers and send it to the
appropriate consumers. The broker only has the information regarding the
consumer to which a particular topic belongs to which the publisher is unaware
of.
3. Push-Pull Model

The push-pull model constitutes data publishers, data consumers, and data queues.

 Publishers and Consumers are not aware of each other.


 Publishers publish the message/data and push it into the queue. The consumers,
present on the other side, pull the data out of the queue. Thus, the queue acts as
the buffer for the message when the difference occurs in the rate of push or pull
of data on the side of a publisher and consumer.
 Queues help in decoupling the messaging between the producer and consumer.
Queues also act as a buffer which helps in situations where there is a mismatch
between the rate at which the producers push the data and consumers pull the
data.

4. Exclusive Pair

 Exclusive Pair is the bi-directional model, including full-duplex communication among


client and server. The connection is constant and remains open till the client sends a
request to close the connection.
 The Server has the record of all the connections which has been opened.
 This is a state-full connection model and the server is aware of all open connections.
 WebSocket based communication API is fully based on this model.
IoT Communication APIs
Generally we used Two APIs For IoT Communication. These IoT Communication APIs are:

 REST Based Communication APIs


 Web Socket Based Communication APIs
Web service can either be implemented using REST principles or using Web Socket
Protocol –

1. REST Based Communication API :

REpresentational State Transfer (REST) is a set of architectural principles by which you


can design web services and web APIs that focus on a system’s resources and how resource
states are addressed and transferred. REST APIs follow the request-response
communication model. The REST architectural constraints apply to the components,
connectors, and data elements, within a distributed hypermedia system.

Advantages of REST API:

 Simplicity: REST APIs are relatively simple to design and implement, making them a
popular choice for building APIs for web applications.
 Flexibility: REST APIs can be used to support a wide range of applications and
services, from simple web applications to complex enterprise systems.
 Caching: REST APIs can leverage caching to improve performance and reduce server
load.
 Stateless: REST APIs are stateless, meaning that each request is processed
independently of any previous requests, making them easy to scale and distribute.

Disadvantages of REST API:

 Limited real-time support: REST APIs do not support real-time communication


between the server and client, making them less suitable for applications that require
real-time updates.
 Performance overhead: REST APIs require more overhead than WebSocket APIs, as
each request and response must contain all the necessary information to complete the
request.
 Complexity: REST APIs can be complex to design and implement for large, distributed
systems.

2. Web Socket Based Communication APIs :

Web Socket APIs allow bi-directional, full-duplex communication between clients and
servers. It follows the exclusive pair communication model. This Communication API does
not require a new connection to be set up for each message to be sent between client s and
servers. Once the connection is set up the messages can be sent and received continuously
without any interruption. WebSocket APIs are suitable for IoT Applications with low
latency or high throughput requirements.
Advantages of WebSocket API:

 Real-time communication: WebSocket APIs enable real-time communication between


the server and client, making them ideal for applications that require real-time updates.
 Efficiency: WebSocket APIs are more efficient than REST APIs for real-time
applications, as they use a persistent connection to enable bidirectional communication.
 Scalability: WebSocket APIs are highly scalable, as they can support thousands of
connections per server.
 Reduced overhead: WebSocket APIs have lower overhead than REST APIs, as they use
a single connection to transmit data.

Disadvantages of WebSocket API:

 Complexity: WebSocket APIs are more complex to design and implement than REST
APIs, requiring additional programming skills and knowledge.
 Security: WebSocket APIs can be vulnerable to security threats if not properly secured.
 Compatibility: WebSocket APIs are not supported by all browsers, requiring fallback
mechanisms for older browsers.

Similarities between REST API and WebSocket API:

 Both REST API and WebSocket API are used to build APIs for web applications.
 Both REST API and WebSocket API are standardized interfaces that enable
communication between the server and client.
 Both REST API and WebSocket API can be customized to suit the specific needs of a
particular application or system.
 Both REST API and WebSocket API can be secured using various authentication and
encryption methods.
Difference between Rest API and Web Socket API :

S.NO. REST API WEB SOCKET API

It is Stateless protocol. It will not store It is Stateful protocol. It will store the
1.
the data. data.

It is Bi-directional. Messages can be


It is Uni-directional. Only either
2. received or sent by both server or
server or client will communicate.
client.

3. It is Request-response model. It is Full duplex model.

HTTP request contains headers like It is suitable for real-time applications.


4.
head section, title section. It does not have any overhead.

New TCP connection will be set up


5. Only Single TCP connection.
for each HTTP request.

Both horizontal and vertical scaling


(we can add many resources and Only vertical scaling (we can add
6.
number of users both horizontally and resources only vertically).
vertically).

It depends upon the HTTP methods to It depends upon the IP address and
7.
retrieve the data.. port number to retrieve the data

It is slower than web socket regarding web socket transmits messages very
8.
the transmission of messages. fastly than REST API.

It does not need memory or buffers to It requires memory and buffers to


9.
store the data. store the data.
MQTT

Message Queuing Telemetry Transport (MQTT): The message query telemetry transport
protocol is a communication-based protocol that is used for IoT devices. This protocol is
based on the publish-subscribe methodology in which clients receive the information
through a broker only to the subscribed topic. A broker is a mediator who categorizes
messages into labels before being delivered.

Characteristics of the Protocol

 Light-weight and reliable: The MQTT message is compact, which can realize stable
transmission on severely limited hardware equipment and network with low bandwidth
and high delay.

 Publish/subscribe mode: Based on the publish/subscribe mode, the advantage of


publishing and subscribing mode is that the publisher and subscriber are decoupled:
Subscribers and publishers do not need to establish a direct connection or be online at
the same time.

 Created for the IoT: It provides comprehensive IoT application features such as
heartbeat mechanism, testament message, QoS quality level

 Better ecosystem: It covers all-language platform's clients and SDKs, and it has mature
Broker server software, which can support massive Topic and ten-million-level device
access and provide rich enterprise integration capabilities.

CoAP
Constrained Application Protocol (COAP): The constrained application protocol is a
client server-based protocol. With this protocol, the COAP packet can be shared between
different client nodes which are commanded by the COAP server. The server is responsible
to share the information depending on its logic but has not acknowledged it. This is used
with the applications which support the state transfer model.

Characteristics of the Protocol


CoAP refers to many design ideas of HTTP, and it also improves many design details and
adds many practical functions according to the specific situation of limited resource-limited
devices.

 It is based on message model


 Based on UDP Protocol, transport layer supports restricted devices
 It uses request/response model similar to HTTP request, and HTTP is text format, while
CoAP is binary format, which is more compact than HTTP
 It supports two-way communication
 It has the characteristics of light-weight and low power consumption
 It supports reliable transmission, data re-transmission, and block transmission to ensure
reliable arrival of data

 It supports IP multicast
 It supports observation mode
 It supports asynchronous communication

LoRaWAN
LoRaWAN refers to Long Rage Wide Area Network which is a wide area network
protocol. It is an optimized low-power consumption protocol design to support large-scale
public networks with millions of low-power devices. A single operator operates the
LoRaWAN. The LoRaWAN network is a bi-directional communication for IoT application
with low cost, mobility, and security..

An end device can connect to a network with LoRaWAN in two ways:

 Over-the-air Activation (OTAA): A device has to establish a network key and an application
session key to connect with the network.
 Activation by Personalization (ABP): A device is hardcoded with keys needed to communicate
with the network, making for a less secure but easier connection.

Properties of LoRaWAN protocol

o Standard: LoRaWAN
o Frequency: Various
o Range: 2-5km (urban environment), 15km (suburban environment)
o Data Rates: 0.3-50 kbps.
6LoWPAN
The 6LoWPAN protocol refers to IPv6 Low Power Personal Area Network which uses a
lightweight IP-based communication to travel over low data rate networks. It has limited
processing ability to transfer information wirelessly using an internet protocol. So, it is
mainly used for home and building automation. The 6LoWPAN protocol operates only
within the 2.4 GHz frequency range with 250 kbps transfer rate. It has a maximum length of
128-bit header packets.

6LowPAN Security Measure

Security is a major issue for 6LowPAN communication Protocol. There are several attacks
issues at the security level of 6LoWPAN which aim is to direct destruction of the network.
Since it is the combination of two systems, so, there is a possibility of attack from two sides
that targets all the layer of the 6LoWPAN stack (Physical layer, Data link layer, Adaptation
layer, Network layer, Transport layer, Application layer).

Basic Requirements of 6LoWPAN:

1. The device should be having sleep mode in order to support the battery saving.
2. Minimal memory requirement.
3. Routing overhead should be lowered.

Features of 6LoWPAN:

1. It is used with IEEE 802.15,.4 in the 2.4 GHz band.


2. Outdoor range: ~200 m (maximum)
3. Data rate: 200kbps (maximum)
4. Maximum number of nodes: ~100

Advantages of 6LoWPAN:

1. 6LoWPAN is a mesh network that is robust, scalable, and can heal on its own.
2. It delivers low-cost and secure communication in IoT devices.
3. It uses IPv6 protocol and so it can be directly routed to cloud platforms.
4. It offers one-to-many and many-to-one routing.
5. In the network, leaf nodes can be in sleep mode for a longer duration of time.

Disadvantages of 6LoWPAN:

1. It is comparatively less secure than Zigbee.


2. It has lesser immunity to interference than that Wi-Fi and Bluetooth.
3. Without the mesh topology, it supports a short range.

Applications of 6LoWPAN:

1. It is a wireless sensor network.


2. It is used in home-automation,
3. It is used in smart agricultural techniques, and industrial monitoring.
4. It is utilised to make IPv6 packet transmission on networks with constrained power and
reliability resources possible.

Difference between COAP and MQTT protocols:

Basis of COAP MQTT

Message Queuing Telemetry


Constrained Application Protocol
Abbreviation Transport

Communication
It uses Request-Response model. It uses Publish-Subscribe model
Type

This uses both Asynchronous and


This uses only Asynchronous
Messaging Mode Synchronous.

Transport layer This mainly uses User Datagram This mainly uses Transmission
protocol protocol(UDP) Control protocol(TCP)
Basis of COAP MQTT

It has 4 bytes sized header It has 2 bytes sized header


Header size

No it does not uses REST


Yes it uses REST principles
RESTful based principles

It supports and best used for live


It does not has such support
Persistence support data communication

It provides by adding labels to the


It has no such feature.
Message Labelling messages.

It is used in Utility area networks It is used in IoT applications


Usability/Security and has secured mechanism. and is secure

Effectiveness in LNN is
Effectiveness in LNN is low.
Effectiveness excellent.

Communication Communication model is one- Communication model is many-


Model one. many.

Bluetooth

Bluetooth is universal for short-range wireless voice and data communication. It is a


Wireless Personal Area Network (WPAN) technology and is used for exchanging data over
smaller distances. This technology was invented by Ericson in 1994. It operates in the
unlicensed, industrial, scientific, and medical (ISM) band from 2.4 GHz to 2.485 GHz.
Maximum devices that can be connected at the same time are 7. Bluetooth ranges up to 10
meters. It provides data rates up to 1 Mbps or 3 Mbps depending upon the versio n. The
spreading technique that it uses is FHSS (Frequency-hopping spread spectrum). A
Bluetooth network is called a piconet and a collection of interconnected piconets is
called scatternet.

Bluetooth Architecture:

The architecture of Bluetooth defines two types of networks:


1. Piconet
2. Scatternet

Piconet:

Piconet is a type of Bluetooth network that contains one primary node called the
master node and seven active secondary nodes called slave nodes. Thus, we can say
that there is a total of 8 active nodes which are present at a distance of 10 meters.
The communication between the primary and secondary nodes can be one-to-one or
one-to-many. Possible communication is only between the master and slave; Slave-
slave communication is not possible. It also has 255 parked nodes, these are
secondary nodes and cannot take participation in communication unless it gets
converted to the active state.

Scatternet:

It is formed by using various piconets. A slave that is present in one piconet can act as
master or we can say primary in another piconet. This kind of node can receive a message
from a master in one piconet and deliver the message to its slave in the other piconet where
it is acting as a master. This type of node is referred to as a bridge node. A station cannot be
mastered in two piconets.

Advantage:

 It is a low-cost and easy-to-use device.


 It can also penetrate through walls.
 It creates an Ad-hoc connection immediately without any wires.
 It is used for voice and data transfer.

Disadvantages:

 It can be hacked and hence, less secure.


 It has a slow data transfer rate: of 3 Mbps.
 It has a small range: 10 meters.
 Bluetooth communication does not support routing.
 The issues of handoffs have not been addressed.

Applications:

 It can be used in laptops, and in wireless PCs, printers.


 It can be used in wireless headsets, wireless PANs, and LANs.
 It can connect a digital camera wirelessly to a mobile phone.
 It can transfer data in terms of videos, songs, photographs, or files from one cell phone
to another cell phone or computer.
 It is used in the sectors of Medical health care, sports and fitness, Military.

WIFI - Wireless Fidelity

Wifi is also known as Wireless Fidelity.

We are all familiar with Wi-Fi, which is available on our mobile phones, laptops, or wherever
Wi-Fi is supported. Wi-Fi is a wireless networking technology that permits to connect
wirelessly to a network or to other computer or mobile device. A circular radio frequency
range is used to transmit data in Wi-Fi.

Wireless Fidelity (Wi-Fi) is a generic term for the wireless network in the communication
norm. Wifi operates like a local area network without the use of a wire or cables.

WLAN stands for Wireless Local Area Network. IEEE 802.11 is the rule for
communication. WiFi uses the Physical Data Link Layer (PDLL) to operate.

Types or Kinds of Wifi

As mentioned earlier, Wi-Fi has numerous kinds or standards. Here, the names of the
standards are defined.

o Wi-Fi-1 (802.11b, launched in 1999) - This version has link speed from 2Mb/s to 11
Mb/s over 2.4 GHz frequency band
o Wi-Fi-2 (802.11a) launched in 1999. After a month of releasing the previous
version, 802.11a, was released, and it provides upto 54 Mb/s link speed over the 5
GHz band
o Wi-Fi-3 (802.11g) was launched in 2003. In this version, the speed was risen up to
54 to 108 Mb/s over 2.4 GHz
o 802.11i launched in 2004. This is equivalentto802.11g, but only the security feature
was enhanced in this version
o 802.11e launched in 2004. This is also the same as 802.11g; only Voice over
Wireless LAN and multimedia streaming are included.
o Wi-Fi-4 (802.11n) launched in 2009. This version holds up both 2.4 GHz and 5 GHz
radio frequencies, and it provides up to 72 to 600 Mb/s speed.
o Wi-Fi-5 (802.11ac) launched in 2014. It supports a speed of 1733 Mb/s in the 5 GHz
band.

Advantages of WIFI

The advantages of Wi-Fi Tt include

o A versatile network connection and the absence of complicated wiring requirements


for installation.
o Everywhere in the Wi-Fi range can access it.
o Independent users are not required to obtain regulatory approval.
o In addition, Wi-Fi Extenders make it possible to expand the network.
o It's easy and quick to set up.
o Only the SSID and password need to be configured.
o As part of its security measures, Wi-Fi networks encrypt radio signals using WPA
encryption.
o It is also more affordable.
o Hotspots are another feature that it offers.
o Roaming is supported as well.

Wi-Fi Disadvantages
o Mobile phones, laptops, and other devices with batteries consume a lot of power when
using Wi-Fi.
o Even when encryption is in place, security issues can still arise.
o Wi-Fi can be attacked and accessed in the same way that recognised devices become
unidentified to the router.
o In comparison to a direct cable connection, the speed is slower.
o People can be harmed by it because it emits radiation like cell phones.
o Thunderstorms, for example, can interfere with Wi-Fi signals.
o Because it lacks a firewall, unauthorised access to Wi-Fi is possible.
o Since a router is required to access the internet via Wi-Fi, we can't access the internet
if the power goes out.

Zigbee

What is Zigbee? – Zigbee is a low power, low data rate (250kbps) wireless protocol used
primarily for Home automation and industrial control, building automation,sensor data
collection etc

Zigbee devices have a range (1 hop) of 80 to 100m.


Devices can be split into:

 Full Function Device (FFD)

Full Function Device (FFD)- Can communicates with all node types and can
operate in one of three modes:

 Zigbee Coordinator Device: It communicates with routers. This device is used


for connecting the devices.
 Zigbee Router: It is used for passing the data between devices.

Zigbee End Device: It is the device that is going to be controlled.


There must be 1 coordinator on a Zigbee network.

Reduced Function Device (RFD): Can only talk to a single


FFD. These are end nodes. Example a smart lock,switch ect
General Characteristics of Zigbee Standard:

 Low Power Consumption


 Low Data Rate (20- 250 kbps)
 Short-Range (75-100 meters)
 Network Join Time (~ 30 msec)
 Support Small and Large Networks (up to 65000 devices (Theory); 240 devices
(Practically))
 Low Cost of Products and Cheap Implementation (Open Source Protocol)
 Extremely low-duty cycle.
 3 frequency bands with 27 channels.

Operating Frequency

1. Channel 0: 868 MHz (Europe)


2. Channel 1-10: 915 MHz (the US and Australia)
3. Channel 11-26: 2.4 GHz (Across the World)

Features of Zigbee:

1. Stochastic addressing: A device is assigned a random address and announced.


Mechanism for address conflict resolution. Parents node don’t need to maintain
assigned address table.
2. Link Management: Each node maintains quality of links to neighbors. Link
quality is used as link cost in routing.
3. Frequency Agility: Nodes experience interference report to channel manager,
which then selects another channel
4. Asymmetric Link: Each node has different transmit power and sensitivity. Paths
may be asymmetric.
5. Power Management: Routers and Coordinators use main power. End Devices
use batteries.
Advantages of Zigbee:
1. Designed for low power consumption.
2. Provides network security and application support services operating on the top of
IEEE.
3. Zigbee makes possible completely networks homes where all devices are able to
communicate and be
4. Use in smart home
5. Easy implementation
6. Adequate security features.
7. Low cost: Zigbee chips and modules are relatively inexpensive, which makes it a cost-
effective solution for IoT applications.
8. Mesh networking: Zigbee uses a mesh network topology, which allows for devices to
communicate with each other without the need for a central hub or router. This makes it
ideal for use in smart home applications where devices need to communicate with each
other and with a central control hub.
9. Reliability: Zigbee protocol is designed to be highly reliable, with robust mechanisms
in place to ensure that data is delivered reliably even in adverse conditions.

Disadvantages of Zigbee :

1. Limited range: Zigbee has a relatively short range compared to other wireless
communications protocols, which can make it less suitable for certain types of
applications or for use in large buildings.
2. Limited data rate: Zigbee is designed for low-data-rate applications, which can make
it less suitable for applications that require high-speed data transfer.
3. Interoperability: Zigbee is not as widely adopted as other IoT protocols, which can
make it difficult to find devices that are compatible with each other.
4. Security: Zigbee’s security features are not as robust as other IoT protocols, making it
more vulnerable to hacking and other security threats.
Zigbee Applications:

1. Home Automation
2. Medical Data Collection
3. Industrial Control Systems
4. meter reading system
5. light control system
6. Commercial
7. Government Markets Worldwide
8. Home Networking

GPS

Global Positioning System (GPS) is a navigation system based on satellite. It has created the
revolution in navigation and position location. It is mainly used in positioning, navigation,
monitoring and surveying applications.

GPS receiver basically consists of three components:

 An Antenna ( tuned to the frequencies transmitted by the satellites).


 Receiver processor.
 Highly Stable Clock ( Commonly a Crystal oscillator).
 Receiving Antenna receives the satellite signals. It is mainly, a circularly polarized
antenna.
 Low Noise Amplifier (LNA) amplifies the weak received signal
 Down converter converts the frequency of received signal to an Intermediate
Frequency (IF) signal.
 IF Amplifier amplifies the Intermediate Frequency (IF) signal.
 ADC performs the conversion of analog signal, which is obtained from IF amplifier to
digital. Assume, the sampling & quantization blocks are also present in ADC (Analog
to Digital Converter).
 DSP (Digital Signal Processor) generates the C/A code.
 Microprocessor performs the calculation of position and provides the timing signals
in order to control the operation of other digital blocks. It sends the useful information
to Display unit in order to display it on the screen.

Usage of GPS:
There are five most uses of the GPS.

 Location:- with the help of GPS we can find the exact position of the object.
 Navigation:– we can navigate one location to another with the help of GPS.GPS
technology is also useful for Transportation Management and breathing of Ship at
docks.
 Tracking: -with the help of GPS we can Monitor object movement like speed, distance,
position.
 Mapping:– GPS also helps in creating maps of the World.
 Timing:- GPS also provides the estimated time for reaching destination measurement
its depend on speed and object movement.

GSM

GSM stands for Global System for Mobile Communication. GSM is an open and digital
cellular technology used for mobile communication. It uses 4 different frequency bands of
850 MHz, 900 MHz, 1800 MHz and 1900 MHz . It uses the combination of FDMA and
TDMA.
GSM is having 4 different sizes of cells are used in GSM :

1. Macro : In this size of cell, Base Station antenna is installed.


2. Micro : In this size of cell, antenna height is less than the average roof level.
3. Pico : Small cells’ diameter of few meters.
4. Umbrella : It covers the shadowed (Fill the gaps between cells) regions.

Features of GSM are :

1. Supports international roaming


2. Clear voice clarity
3. Ability to support multiple handheld devices.
4. Spectral / frequency efficiency
5. Low powered handheld devices.
6. Ease of accessing network
7. International ISDN compatibility.
8. Low service cost.
9. New features and services.

1. BSS : BSS stands for Base Station Subsystem. BSS handles traffic and signaling
between a mobile phone and the network switching subsystem. BSS having two
components BTS and BSC.
2. NSS : NSS stands for Network and Switching Subsystem. NSS is the core network of
GSM. That carried out call and mobility management functions for mobile phone
present in network. NSS have different components like VLR, HLR and EIR.
3. OSS : OSS stands for Operating Subsystem. OSS is a functional entity which the
network operator monitor and control the system. OMC is the part of OSS. Purpose of
OSS is to offer the customer cost-effective support for all GSM related maintenance
services.
Suppose there are 3 Mobile stations which are connected with the tower and that tower is
connected to BTS through TRX, then further connected to BSC and MSC. Let’s understand
the functionality of different components.

1. MS : MS stands for Mobile System. MS comprises user equipment and software needed
for communication with a mobile network. Mobile Station (MS) = Mobile
Equipment(ME) + Subscriber Identity Module (SIM). Now, these mobile stations are
connected to tower and that tower connected with BTS through TRX. TRX is a transceiver
which comprises transmitter and receiver. Transceiver has two performance of sending and
receiving.
2. BTS : BTS stands for Base Transceiver Station which facilitates wireless communication
between user equipment and a network. Every tower has BTS.
3. BSC : BSC stands for Base Station Controller. BSC has multiple BTS. You can consider
the BSC as a local exchange of your area which has multiple towers and multiple towers
have BTS.
4. MSC : MSC stands for Mobile Switching Center. MSC is associated with
communication switching functions such as call setup, call release and routing. Call tracing,
call forwarding all functions are performed at the MSC level.
Services of GSM:

 Telephony services or teleservices


 Data services or bearer services
 Supplementary services

Advantages:

Compatibility: GSM is widely used around the world, so it is compatible with many
different networks and devices.
Security: GSM offers enhanced security features such as authentication, encryption and
confidentiality, which helps to protect the user’s privacy and data.
Efficient use of bandwidth: GSM uses a time-division multiplexing (TDM) technique
which enables many users to share the same frequency channel at different times, making it
an efficient use of the available bandwidth.
Roaming: GSM allows users to roam internationally and use their mobile phones in other
countries that use the same GSM standard.
Wide range of features: GSM supports a wide range of features, including call
forwarding, call waiting, voicemail, conference calling, and more.

Disadvantages:

Limited coverage: GSM networks may have limited coverage in some remote areas, which
can make it difficult for users to make calls or access the internet.
Network congestion: GSM networks may become congested during peak hours, which can
lead to dropped calls or poor call quality.
Security vulnerabilities: Although GSM offers enhanced security features, it is still
vulnerable to certain types of attacks, such as eavesdropping and spoofing.
Data transfer speed: GSM networks offer relatively slow data transfer speeds compared to
newer technologies such as 3G and 4G.
Limited capacity: GSM networks have a limited capacity for handling large volumes of
data, which can be a disadvantage for users who require high-speed internet access or other
data-intensive applications.
Single Board Computers -Raspberry-Pi

Raspberry Pi is developed by Raspberry Pi Foundation in the United Kingdom. The


Raspberry Pi is a series of powerful, small single-board computers.

Raspberry Pi is launched in 2012 and there have been several iterations and variations
released since then.

Various versions of Raspberry Pi have been out till date. All versions consist of a
Broadcom system on a chip (SoC) with an integrated ARM-compatible CPU and on-chip
graphics processing unit (GPU).

Block Diagram of Raspberry Pi

 A low-cost, credit-card-sized minicomputer.

 Plugs into a computer monitor or TV.

 Uses a standard keyboard and mouse.

 Use for explore computing as for programmings like Scratch and Python
languages.

 Capable as a normal desktop computer to browsing the internet and playing


high-definition video, to making spreadsheets, word-processing, and playing
games.”
 Allowing interface sensors and actuators through the general purpose IO
pins

 Supports Python out of box

Structure of board

Raspberry Pi board uses various components and peripherals as follows:-

Processor and Ram


 Based on an ARM processor.

 The latest version of Raspberry Pi (model B, revision 2) comes with a 700 MHz low-
power ARM 1176JZ-F processor And a 512 MB SD Ram.

USB ports
 Two USB 2.0 USB ports on Raspberry pi can provide a current of up to 100 mA.

 For connecting devices that draw a current of more than 100 mA, an external USB-
powered hub is required.

Ethernet port
 Standard RJ45 Ethernet port.

 Connect an ethernet cable or USB Wi-Fi adaptor to provide internet connectivity.


HDMI outputs

 The HDMI port on Raspberry Pi provides both video and audio output.

 Connect the Raspberry Pi to a monitor by an HDMI cable.

 For monitors that have a DVI port but no HDMI port so use an HDMI to DVI adaptor
or cable.

Composite video output with RCA jack


 Support both PAL and NTSC video output.
 RCA jack is used to connect old television that has an RCA input only.

Audio output
 3.5 mm audio output jack is used for audio output to old television along with the
RCA Jack for video.
 The audio quality is inferior to the HDMI output.

Display serial interface( DSI)


 Used to connect an LCD panel to Raspberry Pi.

Camera serial interface( CSI)


 Used to connect a camera module to Raspberry Pi.

Status LEDs
 Raspberry Pi has 5 status LED is which are:-

 ACT:- SD card access.

 PWR:- 3.3 V power is present.

 FDX:- Full duplex LAN connected.

 LNK:- link/ network activity.

 100:- 100 Mbit LAN connected.

SD card slot
 Not have a built-in operating system and storage so plug in an SD card
loaded with a Linux image to an SD card slot.
 Required at least an 8GB SD card for the setting up NOOBS software
(new out-of-the-box software)

Power input
 A micro-USB connector for power input.

GPIO Pin
 A number of general-purpose Input / Output pins are used by Raspberry Pi.

 There are four types of pins on Raspberry Pi:- True GPIO pins, SPI interface
pins, 12C interface pins, and Serial RX and TX pins.

Voltages

From the above diagram, we can see that there are two 5V pins and two 3V3 pins on the
board. It also has several ground pins (0V). All these pins are unconfigurable.

Outputs

A GPIO pin can be designated as an output pin. The pin set as output pin can be set
to 3V(high) or 0V(low).
Inputs

A GPIO pin can be designated as an input pin. The pin set as input pin can be read as
3V(high) or 0V(low). You can use internal pull-up or pull-down resistors.

above diagram, GPIO2 and GPIO3 pins have fixed pull-up resistors but for the other pins,
you can configure it in software.

Alternative Functions

GPIO pins can be used with a variety of alternative functions. Among them, some are
available on all pins and others on specific pins.

PWM: Pulse-width modulation

Software PWM are available on all the pins whereas Hardware PWM are available on
GPIO12, GPIO13, GPIO18, and GPIO19.

SPI: Serial Peripheral Interface

The SPI are available on the following −

SPI0: MOSI (GPIO10); MISO (GPIO9); SCLK (GPIO11); CE0 (GPIO8), CE1 (GPIO7)
SPI1: MOSI (GPIO20); MISO (GPIO19); SCLK (GPIO21); CE0 (GPIO18); CE1 (GPIO17);
CE2 (GPIO16)

I2C: Inter-integrated Circuit

The I2C are available on the following −

Data: (GPIO2); Clock (GPIO3)


EEPROM Data: (GPIO0); EEPROM Clock (GPIO1)

Serial

The serial function is available at the following −

TX(GPIO14)
RX(GPIO15)
Raspberry pi Connecting to the Cloud

Connecting a Raspberry Pi to the cloud allows you to access and manage your Raspberry Pi
remotely, exchange data with cloud services, and perform various tasks such as data logging,
remote control, and automation. Here's a general overview of how to connect a Raspberry Pi
to the cloud:

1. Select a Cloud Service Provider: Choose a cloud service provider that fits your needs.
Some popular options include AWS (Amazon Web Services), Microsoft Azure, Google
Cloud Platform, and various IoT-focused platforms like AWS IoT, Azure IoT, or Google
Cloud IoT. Each has its own set of features, pricing, and capabilities.
2. Set Up Your Raspberry Pi: Ensure your Raspberry Pi is set up correctly, connected to the
internet, and running an appropriate operating system like Raspbian (now called Raspberry Pi
OS).
3. Install Necessary Software: Depending on your chosen cloud platform, you may need to
install specific libraries or SDKs on your Raspberry Pi. For example, if you're using AWS,
you would install the AWS SDK for Python (Boto3). If you're using Azure, you might use
the Azure IoT SDK or Azure Python SDK.
4. Create Cloud Resources: Create the necessary resources on your cloud platform. For
example, if you're using AWS IoT, you'd create an IoT Thing, a policy, and certificates.
5. Connect to the Cloud: Write code on your Raspberry Pi to connect to your cloud platform
of choice. This typically involves using the SDK you installed earlier and providing the
necessary authentication credentials (e.g., API keys, certificates, or access tokens).
6. Publish and Subscribe to Topics (MQTT): Many IoT applications use the publish-
subscribe model for communication. MQTT (Message Queuing Telemetry Transport) is a
common protocol for this purpose. You can publish data from your Raspberry Pi to specific
MQTT topics and subscribe to topics to receive commands or data from the cloud.
7. Data Handling and Processing: Once your Raspberry Pi is connected, you can send and
receive data between the Raspberry Pi and the cloud. You may want to implement data
processing, storage, or analytics depending on your project's requirements.
8. Security Considerations: Ensure proper security practices. Use secure connections (HTTPS,
MQTT over TLS), secure your IoT devices and cloud resources, and regularly update your
Raspberry Pi's software to patch any security vulnerabilities.
9. Monitoring and Management: Set up monitoring and management tools provided by your
cloud platform to keep an eye on your Raspberry Pi's health and performance. This might
include dashboards, alerts, and logging.
10. Scale and Optimize: As your project grows, you may need to scale your cloud resources and
optimize your code and infrastructure for performance and cost-efficiency.
UNIT 5 - APPLICATIONS DEVELOPMENT

Complete Design of Embedded Systems – Development of IoT Applications – Home


Automation –Smart Agriculture – Smart Cities – Smart Healthcare.

Embedded System

As its name suggests, Embedded means something that is attached to another thing. An
embedded system can be thought of as a computer hardware system having software
embedded in it. An embedded system can be an independent system or it can be a part of a
large system. An embedded system is a microcontroller or microprocessor based system
which is designed to perform a specific task. For example, a fire alarm is an embedded
system; it will sense only smoke.

An embedded system has three components −

 It has hardware.
 It has application software.
 It has Real Time Operating system (RTOS) that supervises the application software
and provide mechanism to let the processor run a process as per scheduling by
following a plan to control the latencies. RTOS defines the way the system works. It
sets the rules during the execution of application program. A small scale embedded
system may not have RTOS.

So we can define an embedded system as a Microcontroller based, software driven, reliable,


real-time control system.

Basic Structure of an Embedded System

The following illustration shows the basic structure of an embedded system −


 Sensor − It measures the physical quantity and converts it to an electrical signal
which can be read by an observer or by any electronic instrument like an A2D
converter. A sensor stores the measured quantity to the memory.
 A-D Converter − An analog-to-digital converter converts the analog signal sent by
the sensor into a digital signal.
 Processor & ASICs − Processors process the data to measure the output and store it
to the memory.
 D-A Converter − A digital-to-analog converter converts the digital data fed by the
processor to analog data
 Actuator − An actuator compares the output given by the D-A Converter to the actual
(expected) output stored in it and stores the approved output.

Advantages

 Easily Customizable
 Low power consumption
 Low cost
 Enhanced performance

Disadvantages

 High development effort


 Larger time to market
Home Automation

Home Automation is a system that allows users to control various appliances of varying
kinds and also makes controlling of home appliances easier and saves energy. Nowadays,
home automation is used more and more. On the other hand, it provides increased comfort
especially when everyone is busy with their work. Home automation installed in houses
does not only increase comfort but also allows centralized control of heating, ventilation,
air-condition, and lighting. Hence, they contribute to an overall cost reduction and also
useful in energy saving which is certainly the main problem today.
In present years, wireless systems like Wi-Fi, Bluetooth have become more and more
common in home networking. Also in home automation, the use of wireless technologies
gives several advantages that could not be achieved using a wired network only.

Home Automation Components: At the most initial level, home automation systems are
made up of three elements-
1. A smart device.
2. A hub.
3. A connected application.
While some other home automation systems work with just two elements which include a
single device that works with the help of an app on mobile or a tablet or a system that
includes a hands-free hub that controls home automation system while most of the systems
work using all the above three components.

1. Smart Devices: These are the real powerhouse of any home automation system. These
are the main parts that actually implement the whole system commands. Examples of the
smart devices which can be added to any home automation to complete the whole system
are as follows:
 Access Control
 Security Devices: This includes security cameras, smart locks.
 Home Appliances: Smart refrigerators, washing machines, dishwashers, and ovens
already exist.
 Smaller Appliances: As automatic coffee pots and electric kettle have been also around
for a while too
 Climate Controls: Climate control system with energy management systems
 Smart Thermostats.
 Entertainment Pieces: Entertainment includes smart TVs, wireless speakers, and film
projectors
 Health Care Devices: Smart humidifiers and smart scales are two common examples
of health care devices.
 Lighting Controls: They include dimmers, light bulbs, light strips, and switches, etc.
A high-speed internet plays an important role in smooth connectivity and also plays an
important reliable performance between Wi-Fi-enabled devices.

2. Smart Hubs: The hub is the controlling center of the home automation system. It is the
piece that connects your individual devices and helps them talk to one another.
3. Mobile Apps: The mobile application provides an interface between the user and the
system. It gives you the ability to control or monitor your smart devices remotely. They can
be easily downloaded with the help of a provided application on mobile and provide access
control of the system, power controls, timer access, and many more things.

How Home Automation Works?

Home automation works with the help of a network of devices that are connected to the
Internet through different communication systems like Wi-Fi, Bluetooth, ZigBee, and
others. Through these devices can be managed remotely through controllers through an app.
Many of these IoT devices have sensors that monitor changes in motion, temperature, and
light so the user can gain information about the device’s surroundings.

Three steps are followed in Home automation as follows:

1. Monitoring: This means keeping the control of the system using an app on a device
remotely.
2. Control: This means that the system can be controlled remotely from anywhere through
the app by the user.
3. Automation: Automation means making almost all devices automatic for making it a
better system.

Applications: Some of the most common applications of home automation are as follows-
 Heating, ventilation, and air conditioning.
 Lighting control system.
 Occupancy-aware control system.
 Leak detection.
 Smoke sensors.
 Indoor positioning systems.
 Home automation for the elderly and disabled.
 Air quality control.
 Smart Kitchen.
 Connected Cooking.
 Voice control devices like Amazon Alexa or Google Home used to control home
appliances or systems etc.

Advantages of Home Automation:

 Energy Savings: Self-automated light bulbs, fans, and switchboards save energy,
cutting utility costs over time.
 Home Safety: Home automation provides the best technologies for home security.
Consumers purchase these devices because they want to make their homes safer and
more secure. Automatic lighting systems and motion sensors help people to enter doors
and walk late at night.
 User Convenient: Because home automation performs role tasks automatically, end-
users experience great convenience. For instance, you could use sensors indoors to turn
on your smart lighting when you unlock the front door.
 Better Control: Consumers also choose smart home devices to better control functions
within the home. With home automation technology, you can know easily what’s
happening inside your home at all times.
 Comfortable Atmosphere: All Connected devices around our home can also help to
create a comfortable atmosphere—they provide intelligent and reliable lighting, sound,
and temperature, which can all help to create a comfortable environment.
 Provide Peace of Mind: This system may help consumers to invest in home
automation for peace of mind.
 Remote Access: Being able to control devices remotely means things like unlocking the
door for a plant sitter without having to leave a key under the mat.
Disadvantages Of Home Automation:

 Costs: These are more expensive than their non-WiFi-connected counterparts.


 Security Issues: There are many security issues like the doorbell can be started ringing
automatically etc.
 New Technology: Since IoT is a relatively new technology, you may run into some
bugs, like devices having trouble connecting to the Internet or experiencing lag,
depending on the device make and model.
 Surveillance: If privacy is a huge concern, then smart security is probably not for you,
as users can live stream footage from the camera’s respective app. Instead, you might
want to opt for a local alarm system.

IOT in Agriculture

Agriculture is another important domain for IOT. IOT systems play an important role for
crop and soil monitoring and give a proper solution accordingly. IOT leads to smart farming.
Using IOT, farmers can minimize waste and increase productivity. The system allows the
monitoring of fields with the help of sensors. Farmers can monitor the status of the area.
Challenges in the modern agriculture industry

The challenges faced by the farming industry and agriculture are listed as follows -

o Lack of workforce and manpower


o Environmental challenges and global warming
o Requirement of large manual intervention
o Lack of proper monitoring
o Challenges in analyzing the large scale unstructured data

There are various uses of IOT in agriculture that are discussed as follows -

IOT analytics in agriculture

The data from smart sensors can be further analyzed for automated decision-making and
predictive analysis. Machine learning and predictive analysis will be helpful for farmers to
cope up with the weather conditions such as drought, flood, etc.

Drone-based uses

Drones are also useful in smart farming. On one side, drones are useful to monitor the soil,
air, moisture quality, and on another side, they can also be used for physical activities such as
prevention of physical breakouts in farms, automated spraying of fertilizers, and many more.
Although there are some limitations of using a drone, but it is useful to reduce the manual
workforce.
Real-time crop monitoring

Motion detectors, light detectors, smart-motion sensing sensors, smart sensors are useful to
provide real-time data to farmers of their farms. It will be helpful in the monitoring of the
quality of their products.

Smart Irrigation system


It is one of the parts of smart agriculture using IOT. In it, IOT checks the water lanes created
by the farmer or the moisture level in the environment.

Infrastructure requirements

There are some infrastructure requirements for adopting smart farming in IOT. Some of the
requirements are listed as follows -

o Hardware maintenance cost


o Continuous connectivity to the internet
o Required high investments in drones, sensors
o The requirement to hire highly trained staff for management and to operate
o Requirement of power connectivity to operate and charge the robots and drones

IoT in Smart Cities

1. Water Level Checking

The water supply is one of the most significant perspectives for legislatures. With intelligent
sensors, the water levels can be checked progressively.

These sensors can send triggers and alarms to key chiefs for low or high water levels. The
spillages and water dispersion can be combined using IoT sensors and ICT frameworks.

All regions with a plentiful water supply can be set apart on the guide; correspondingly, the
guides can feature regions with water spillage or deficiency.

A complete outline of the water supply with GPS directions can be given to water specialists with
IoT frameworks.

2. Health Cards

Clinics and medical services frameworks are significant marks of administration. The smart
city requires a state−of−the−art medical services framework that can follow quantifiable
advancement concerning residents' well−being.
A shrewd card−based framework can be utilized by people that might be utilized in all
administration and approved clinics.

This card will have the verifiable subtleties of the medicines and so on for people. The robust
medical care framework will empower the public authority to look at the clinics and their
administrations to residents.

The smart card empowers the framework to work with simple information assortment. The
cloud−based framework can give essential knowledge to Medical services experts for a
further progressive organization.

3. Waste & Garbage Management

The waste and trash the executive's exercises can be improved with intelligent sensors and
IoT Frameworks.

The trash containers can utilize intelligent sensors to demonstrate when they should be
discharged. This diminishes the times that vehicles are expected to gather the trash from the
receptacles and evades what is going on of waste flood.

Metropolitan organizations can involve shrewd receptacles and IoT frameworks for trash
assortment.

4. Transport Systems

The transportation framework for the residents can be improved with IoT−empowered
frameworks. The armadas can be overseen and followed utilizing GPS beacons.

Legislatures can finish armadas' organization, planning, ongoing situating, support, and free
time for executives with IoT frameworks.

The residents can likewise benefit from transportation administrations with a card−based
framework for tickets and so on.

5. Smart Traffic Management

Traffic is one of the significant problem areas for residents. With IoT sensors, traffic can be
controlled better.
The sensors are associated with traffic lights and send data to an incorporated server. The
approaching vehicles are followed utilizing these sensors.

When the quantity of vehicles arrives at a limit, signals are shipped off to the drivers to
redirect. These signs are shown with electronic showcase sheets.

Constant traffic cautions and GIS planning of the streets can further develop gridlocks and
blockage during top hours.

6. Infrastructure Assets Management

The brilliant city requires advanced usage of framework resources. The plants, apparatus, and
gear are labeled and observed with the brought−together resource of the executive's
framework.

The continuous undertaking stock for different advancement works can be followed utilizing
the brought−together framework.

The situation with framework resources, their usage, upkeep, and the complete lifecycle of
the board should be possible with the brought−together IoT framework.

7. Surveillance Systems

IP cameras and reconnaissance frameworks can assist the public authority with controlling
crime percentages in a city.

The IP cameras can be utilized for surveying and monitoring essential foundations. These
cameras can be associated with unified frameworks with reinforcements for verifiable
information.

A versatile reconnaissance framework can be set up with IoT video arrangements


safeguarding individuals, spots, and resources.

8. Pollution Control With Sensors

Urbanization has prompted an uncommon expansion in contamination levels. The rising


contamination levels are causing medical problems for residents.
With IoT−empowered sensors, contamination can be estimated progressively. The
contamination sensors send data to an incorporated server.

The public authority can make a move given the contamination levels; e.g., they can establish
trees in a specific area.

The plant life and contamination levels can likewise be portrayed online with google maps
for executives.

9. Smart Energy Management

One of the critical difficulties for state−run administrations is to decrease energy utilization
and introduce a proficient appropriation framework set up.

Brilliant framework arrangements, electronic meters, and intelligent lighting frameworks are
a portion of the components that are utilized by legislatures to oversee energy effectively.

The power dispersion guides can show on going energy utilization levels, spillages, and
upkeep plans. The IoT−empowered arrangements can improve the energy of the board for
urban areas.

10. E-Services

This can be overseen through biometric confirmation or smart cards. Residents can benefit
from all taxpayer−driven organizations through this card.

The public authority can collect data through these cards for proactive preparation and the
executives.

All taxpayer−supported organizations can be incorporated through the e−administrations


gateway.

The residents can benefit from these offices for paying their water and power bills, local
charges, medical clinic check−ups, etc. Coordinated information additionally helps in
strategy−making and organization.
Internet of Things (IoT) in Healthcare

IoT technology brings numerous applications in healthcare, from remote monitoring to smart
sensors to medical device integration. It keeps the patients safe and healthy as well as
improves the physician delivers care towards the patients.

Healthcare devices collect diverse data from a large set of real-world cases that increases the
accuracy and the size of medical data.

Factor affecting IoT Healthcare Application

There are various factors that affect the IoT healthcare application. Some of them are mention
below:

o Continuous Research: It requires continuous research in every field (smart devices,


fast communication channel, etc.) of healthcare to provide a fast and better facility for
patients.
o Smart Devices: Need to use the smart device in the healthcare system. IoT opens the
potential of current technology and leads us toward new and better medical device
solutions.

o Better Care: Using IoT technology, healthcare professionals get the enormous data
of the patient, analysis the data and facilitate better care to the patient.

o Medical Information Distribution: IoT technology makes a transparency of


information and distributes the accurate and current information to patients. This leads
the fewer accidents from miscommunication, better preventive care, and improved
patient satisfaction.

Simple Healthcare System Architecture

The application of the Internet of Things (IoT ) in healthcare transforms it into more smart,
fast and more accurate. There is different IoT architecture in healthcare that brings start
health care system.
Product Infrastructure: IoT product infrastructure such as hardware/software component
read the sensors signals and display them to a dedicated device.

Sensors: IoT in healthcare has different sensors devices such as pulse-oximeter,


electrocardiogram, thermometer, fluid level sensor, sphygmomanometer (blood pressure) that
read the current patient situation (data).

Connectivity: IoT system provides better connectivity (using Bluetooth, WiFi, etc.) of
devices or sensors from microcontroller to server and vice-versa to read data.

Analytics: Healthcare system analyzes the data from sensors and correlates to get healthy
parameters of the patient and on the basis of their analyze data they can upgrade the patient
health.

Application Platform: IoT system access information to healthcare professionals on their


monitor device for all patients with all details.
IoT challenges in Healthcare
o Data security & privacy
o Integration: multiple devices & protocols
o Data overload & accuracy
o Cost

You might also like