CS3691 EMBEDDED SYSTEMS AND IOTl 1 To 4 Unit
CS3691 EMBEDDED SYSTEMS AND IOTl 1 To 4 Unit
3024
COURSE OBJECTIVES:
To learn the internal architecture and programming of an embedded processor.
To introduce interfacing I/O devices to the processor.
To introduce the evolution of the Internet of Things (IoT).
To build a small low-cost embedded and IoT system using Arduino/RaspberryPi/
openplatform.
To apply the concept of Internet of Things in real world scenario.
1|Page
lOMoAR cPSD| 26885763
UNIT I
▪ 8-Bit Microcontroller
▪ Architecture
▪ Interrupt Handling.
2|Page
lOMoAR cPSD| 26885763
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.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.
3|Page
lOMoAR cPSD| 26885763
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.
•
Out of the 128-byte RAM, first, 32 bytes is held by the working registers. Basically, these
are 4 banks which separately has 8 registers. These registers are accessed either by its
4|Page
lOMoAR cPSD| 26885763
name or address. It is to be noted here that at a particular time only a single register bank
can be used.
• As in 8051, the data and program memory i.e., RAM and ROM hold a definite memory
space. However, for some applications there exist the need for external memory to
enhance the memory space, thus external RAM, ROM/EPROM is used by the 8051
microcontrollers.
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.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.
Basically, microcontrollers use hardware delays in which a physical device is used by the
processor to produce the respective delay. And this physical device is known as a timer.
The timer produces the delay according to the demand of the processor and sends the signal
to the processor once the respective delay gets produced.
5|Page
lOMoAR cPSD| 26885763
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
6|Page
lOMoAR cPSD| 26885763
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.
7|Page
lOMoAR cPSD| 26885763
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.
8|Page
lOMoAR cPSD| 26885763
used for direct hardware manipulations. It is also used to write the 8051 programming
code efficiently with less number of clock cycles by consuming less memory compared to
the other high-level languages.
Microcontrollers or processors can understand only binary language in the form of ‘0s or
1s’; An assembler converts the assembly language to binary language, and then stores it in
the microcontroller memory to perform the specific task.
The 8051 microcontroller is the CISC based Harvard architecture, and it has peripherals like
32 I/O, timers/counters, serial communication and memories. The microcontroller requires a
program to perform the operations that require a memory for saving and to read the
functions. The 8051 microcontroller consists of RAM and ROM memories to
store instructions.
9|Page
lOMoAR cPSD| 26885763
A Register is the main part in the processors and microcontrollers which is contained in the
memory that provides a faster way of collecting and storing the data. The 8051 assembly
language programming is based on the memory registers. If we want to manipulate data to a
processor or controller by performing subtraction, addition, etc., we cannot do that directly in
the memory, but it needs registers to process and to store the data. Microcontrollers contain
several types of registers that can be classified according to their instructions or content that
operate in them.
The assembly language is made up of elements which all are used to write the program
in sequential manner. Follow the given rules to write programming in assembly language.
10 | P a g e
lOMoAR cPSD| 26885763
Op-code: The op-code is a single instruction that can be executed by the CPU. Here the op-
code is a MOV instruction.
Operands: The operands are a single piece of data that can be operated by the op-code.
Example, multiplication operation is performed by the operands that are multiplied by the
operand.
Syntax: MUL a,b;
• Assembler Directives
• Instruction Set
• Addressing Modes
ORG(origin): This directive indicates the start of the program. This is used to set the register
address during assembly. For example; ORG 0000h tells the compiler all subsequent code
starting at address 0000h.
Syntax: ORG 0000h
11 | P a g e
lOMoAR cPSD| 26885763
(define byte): The define byte is used to allow a string of bytes. For example, print the
“EDGEFX” wherein each character is taken by the address and finally prints the “string” by
the DB directly with double quotes.
Syntax:
ORG 0000h
MOV a, #00h
————-
————-
DB”EDGEFX”
EQU (equivalent): The equivalent directive is used to equate address of the variable.
Syntax:
reg equ,09h
—————–
—————–
MOV reg,#2h
12 | P a g e
lOMoAR cPSD| 26885763
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
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
13 | P a g e
lOMoAR cPSD| 26885763
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.
14 | P a g e
lOMoAR cPSD| 26885763
As shown in the above illustration, this is a 2-byte instruction which requires 1 cycle to
complete. The PC will be incremented by 2 and will point to 0204. The opcode for the
instruction MOV A, address is E5H. When the instruction at 0202 is executed (E5H), the
accumulator is made active and ready to receive data. Then the PC goes to the next address
as 0203 and looks up the address of the location of 04H where the source data (to be
transferred to accumulator) is located. At 04H, the control finds the data 1F and transfers it to
the accumulator and hence the execution is completed.
15 | P a g e
lOMoAR cPSD| 26885763
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.
Now, take a look at the following illustration to get a clear understanding of how it works.
Opcode EC is used for MOV A, R4. The opcode is stored at the address 0202 and when it is
executed, the control goes directly to R4 of the respected register bank (that is selected in
PSW). If register bank #0 is selected, then the data from R4 of register bank #0 will be
moved to the accumulator. Here 2F is stored at 04H. 04H represents the address of R4 of
register bank #0.
Data (2F) movement is highlighted in bold. 2F is getting transferred to the accumulator from
data memory location 0C H and is shown as dotted line. 0CH is the address location of
Register 4 (R4) of register bank #1. The instruction above is 1 byte and requires 1 cycle for
complete execution. What it means is, you can save program memory by using register direct
addressing mode.
Register Indirect Addressing Mode
In this addressing mode, the address of the data is stored in the register as operand.
MOV A, @R0
16 | P a g e
lOMoAR cPSD| 26885763
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.
Note − Only R0 and R1 are allowed to form a register indirect addressing instruction. In
other words, the programmer can create an instruction either using @R0 or @R1. All register
banks are allowed.
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
17 | P a g e
lOMoAR cPSD| 26885763
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 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.3.4.3. Instruction Set
18 | P a g e
lOMoAR cPSD| 26885763
In the program in Example, the R2 register is used as a counter. The counter is first set to 10.
In each iteration the instruction DJNZ decrements R2 and checks its value. If R2 is not zero,
it jumps to the target address associated with the label “AGAIN”. This looping action
continues until R2 becomes zero. After R2 becomes zero, it falls through the loop and
executes the instruction immediately below it, in this case the “MOV R5 , A” instruction.
Notice in the DJNZ instruction that the registers can be any of RO – R7. The counter can also
be a RAM location
Example
Write a program to (a) load the accumulator with the value 55H, and (b) complement the
ACC 700 times.
Solution:
Since 700 is larger than 255 (the maximum capacity of any register), we use two registers to
hold the count. The following code shows how to use R2 and R3 for the count.
19 | P a g e
lOMoAR cPSD| 26885763
In this program, R2 is used to keep the inner loop count. In the instruction “DJNZ R2 ,
AGAIN”, whenever R2 becomes 0 it falls through and “DJNZ R3 , NEXT” is executed. This
instruction forces the CPU to load R2 with the count 70 and the inner loop starts again. This
process will continue until R3 becomes zero and the outer loop is finished.
JZ (jump if A = 0)
In this instruction the content of register A is checked. If it is zero, it jumps to the target
address. For example, look at the following code.
20 | P a g e
lOMoAR cPSD| 26885763
In this program,. if either RO or Rl is zero, it jumps to the label OVER. Notice that the JZ
instruction can be used only for register A. It can only check to see whether the accumulator
is zero, and it does not apply to any other register. More importantly, you don’t have to
perform an arithmetic instruction such as decrement to use the JNZ instruction. See Example
3-4.
Example
21 | P a g e
lOMoAR cPSD| 26885763
Remember that although the program counter in the 8051 is 16-bit, thereby giving a ROM
address space of 64K bytes, not all 8051 family members have that much on-chip program
ROM. The original 8051 had only 4K bytes of on-chip ROM for program space;
consequently, every byte was precious. For this reason there is also an SJMP (short jump)
instruction, which is a 2-byte instruction as opposed to the 3-byte LJMP instruction. This can
save some bytes of memory in many applications where memory space is in short supply.
SJMP is discussed next.
Shifting Operators
The shift operators are used for sending and receiving the data efficiently. The
8051 microcontroller consist four shift operators:
• RR —> Rotate Right
• RRC —>Rotate Right through carry
• RL —> Rotate Left
• RLC —>Rotate Left through carry
Syntax:
MOV A, #25h
RR A
22 | P a g e
lOMoAR cPSD| 26885763
Syntax:
MOV A, #25h
RL A
Syntax:
MOV A, #27h
RRC A
Syntax:
MOV A, #27h
RLC A
The microcontroller programming differs for each type of operating system. There are many
operating systems such as Linux, Windows, RTOS and so on. However, RTOS has several
23 | P a g e
lOMoAR cPSD| 26885763
advantages for embedded system development. Some of the Assembly levels programming
examples are given below.
1.3.5. Example Program for LED blinking using with 8051 microcontroller:
• Number Displaying on 7-segment display using 8051 microcontroller
• Timer/Counter calculations and program using 8051 microcontroller
• Serial Communication calculations and program using 8051 microcontroller
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.
24 | P a g e
lOMoAR cPSD| 26885763
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
25 | P a g e
lOMoAR cPSD| 26885763
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.
Dual role of port 0: Port 0 is also designated as AD0-AD7, allowing it to be used for both address
and data. When connecting an 8051/31 to an external memory, port 0 provides both address and data.
The 8051 multiplexes address and data through port 0 to save pins. ALE indicates if P0 has address or
data. When ALE = 0, it provides data D0-D7, but when ALE =1 it has address and data with the help
of a 74LS373 latch.
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
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.
26 | P a g e
lOMoAR cPSD| 26885763
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.
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.
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.
27 | P a g e
lOMoAR cPSD| 26885763
Read-modify-write feature : The ports in the 8051 can be accessed by the read-modify-write
technique. This feature saves many lines of code by combining in a single instruction all three action
of (1) reading the port, (2) modifying it, and (3) writing to the port. The following code first places
01010101 (binary) into port 1. Next, the instruction “XLR P1,#0FFH” performs an XOR logic
operation on P1 with 1111 1111 (binary), and then writes the result back into P1.
1.4.3. Addition of two 8-bit numbers in 8051 Microcontroller Using Ports Introduction:
To perform addition of two 8-bit numbers using ports in 8051 microcontroller, we
need to connect the two 8-bit numbers to be added to two ports of the microcontroller. We
can use any two ports of the microcontroller, for example, P1 and P2.
The first step is to load the two numbers into two different ports. For example, we can
load the first number into port P1 and the second number into port P2. We can use the MOV
instruction to load the numbers into the ports.
Once the numbers are loaded into the ports, we can use the ADD instruction to add
the two numbers. The ADD instruction adds the contents of the accumulator and the
specified operand and stores the result in the accumulator. Since the two numbers are already
loaded into the ports, we can simply use the ADD instruction with the accumulator and the
appropriate port.
After the addition is complete, we can retrieve the result from the accumulator and
store it in another port or memory location for further processing or display. 8051
microcontroller is a microcontroller designed by Intel in 1981. It is an 8-bit microcontroller
with 40 pins DIP (dual inline package), 4kb of ROM storage and 128 bytes of RAM storage,
16-bit timers. It consists of four parallel 8-bit ports, which are programmable as well as
addressable as per the requirement.
28 | P a g e
lOMoAR cPSD| 26885763
2. Input validation: Before performing the addition, it is important to validate the input to
ensure that the numbers are within the range of 0 to 255. If the input is not validated, the
result may be incorrect.
3. Port initialization: The ports used for input and output must be properly initialized before
use. If the ports are not properly initialized, the data may not be transferred correctly.
4. Endianness: The order in which the bytes of the numbers are stored in memory can affect
the result of the addition. It is important to ensure that the bytes are stored in the correct
order before performing the addition.
5. Interrupts: If interrupts are enabled during the addition operation, the result may be
affected. It is important to disable interrupts during critical operations to ensure the
correct result.
6. Timing: The timing of the addition operation can affect the result. It is important to
ensure that the necessary delays are added between instructions to ensure correct
operation.
7. Code optimization: The code used to perform the addition should be optimized to ensure
that it uses the least number of instructions and takes the least amount of time. This is
important to avoid potential timing issues and to ensure that the microcontroller can
perform other tasks while the addition is being performed.
Problem: To write an assembly language program to add two 8 bit numbers in 8051
microcontroller using ports.
Example:
Block diagram:
29 | P a g e
lOMoAR cPSD| 26885763
Algorithm:
• Initialize Ports P0 and P1 as input ports.
• Initialize Ports P2 and P3 as output ports.
• Initialize the R1 register.
• Move the contents from Port 0 to B register.
• Move the contents from Port 1 to A register.
• Add contents in A and B.
• If carry is present increment R1.
• Move contents in R1 to Port 2.
• Move the sum in step 6 to Port 3.
Program:
ORG 00H // Indicates starting address
30 | P a g e
lOMoAR cPSD| 26885763
Explanation:
• ORG 00H is the starting address of the program.
• Giving the values as #0FFH and #00H initializes the ports as input and output ports
respectively.
• R1 register is initialized to 0 so as to store any carry produced during the sum.
• MOV B, P0 moves the value present in P0 to the B register.
• MOV A, P1 moves the value present in P1 to Accumulator.
• ADD AB adds the values present in Accumulator and B register and stores the result in
Accumulator.
• JNC L2 refers to jump to label L2 if no carry is present by automatically checking
whether the carry bit is set or not.
• If the carry bit is set to increment register R1.
• MOV P2, R1, and MOV P3, A refers to moving the carry bit to P2 and result in
Accumulator to P3.
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.
31 | P a g e
lOMoAR cPSD| 26885763
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
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.
Its lower 4 bits are used for Timer0 and the upper 4 bits are used for 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
32 | P a g e
lOMoAR cPSD| 26885763
These are Timer/Counter mode select bit as per the below table
M1 M0 Mode Operation
0 0 0 (13-bit timer mode) 13-bit timer/counter, 8-bit of THx & 5-bit of TLx
0 1 1 (16-bit timer mode) 16-bit timer/counter, THx cascaded with TLx
8-bit timer/counter (auto-reload mode), TLx reload
1 0 2 (8-bit auto-reload mode)
with the value held by THx each time TLx overflow
Split the 16-bit timer into two 8-bit timers i.e. THx
1 1 3 (split timer mode)
and 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.
33 | P a g e
lOMoAR cPSD| 26885763
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.
In this example the Timer1is selected, in this case, every 32 (25)event for counter operations
or 32 machine cycles for timer operation, the TH1 register will be incremented by 1. When
the TH1overflows from FFH to 00H, then the TF1 of TCON register will be high, and it
stops the timer/counter. So for an example, we can say that if the TH1 is holding F0H, and it
is in timer mode, then TF1will be high after 10H * 32 = 512 machine cycles.
MOVTMOD, #00H
MOVTH1, #0F0H
MOVIE, #88H
SETB TR1
34 | P a g e
lOMoAR cPSD| 26885763
In the above program, the Timer1 is configured as timer mode 0. In this case Gate = 0. Then
the TH1 will be loaded with F0H, then enable the Timer1 interrupt. At last set the TR1 of
TCON register, and start the timer.
Mode1 (16-bit timer mode)
The Mode 1 operation is the 16-bit timer or counter. In the following diagram, we are using
Mode 1 for Timer0.
In this case every event for counter operations or machine cycles for timer operation, the
TH0– TL0 register-pair will be incremented by 1. When the register pair overflows from
FFFFH to 0000H, then the TF0 of TCON register will be high, and it stops the
timer/counter. So for an example, we can say that if the TH0 – TL0 register pair is holding
FFF0H, and it is in timer mode, then TF0 will be high after 10H = 16 machine cycles. When
the clock frequency is 12MHz, then the following instructions generate an interrupt 16 µs
after Timer0 starts running.
MOVTMOD, #01H
MOVTL0, #0F0H
MOVTH0, #0FFH
MOVIE, #82H
SETB TR0
In the above program, the Timer0 is configured as timer mode 1. In this case Gate = 0. Then
the TL0 will be loaded with F0H and TH0 is loaded with FFH, then enable the Timer0
interrupt. At last set the TR0 of TCON register, and start the timer.
Mode2 (8-bit auto-reload timer mode)
The Mode 2 operation is the 8-bit auto reload timer or counter. In the following diagram, we
are using Mode 2 for Timer1.
In this case every event for counter operations or machine cycles for timer operation, the
TL1register will be incremented by 1. When the register pair overflows from FFH to 00H,
then the TF1 of TCON register will be high, also theTL1 will be reloaded with the content of
TH1 and starts the operation again.
35 | P a g e
lOMoAR cPSD| 26885763
So for an example, we can say that if the TH1 and TL1 register both are holding F0H and it
is in timer mode, then TF1 will be high after 10H= 16 machine cycles. When the clock
frequency is 12MHz this happens after 16 µs, then the following instructions generate an
interrupt once every 16 µs after Timer1 starts running.
MOVTMOD, #20H
MOVTL1, #0F0H
MOVTH1, #0F0H
MOVIE, #88H
SETBTR1
In the above program, the Timer1 is configured as timer mode 2. In this case Gate = 0. Then
the TL1 and TH1 are loaded with F0H. then enable the Timer1 interrupt. At last set the TR1
of TCON register, and start the timer.
Mode 3 of Timer/Counter
Mode 3 is different for Timer0 and Timer1. When the Timer0 is working in mode 3, the TL0
will be used as an 8-bit timer/counter. It will be controlled by the standard Timer0 control
bits, T0 and INT0 inputs. The TH0 is used as an 8-bit timer but not the counter. This is
controlled by Timer1 Control bit TR1. When the TH0 overflows from FFH to 00H, then
TF1 is set to 1. In the following diagram, we can Timer0 in Mode 3.
36 | P a g e
lOMoAR cPSD| 26885763
When the Timer1 is working in Mode 3, it simply holds the count but does not run. When
Timer0 is in mode 3, the Timer1 is configured in one of the mode 0, 1 and 2. In this case, the
Timer1 cannot interrupt the microcontroller. When the TF1 is used by TH0 timer, the
Timer1 is used as Baud Rate Generator.
The meaning of gate bit in Timer0 and Timer1 for mode 3 is as follows
It controls the running of 8-bit timer/counter TL0 as like Mode 0, 1, or 2. The running of
TH0 is controlled by TR1 bit only. So the gate bit in this mode for Timer0 has no specific
role.
The mode 3 is present for applications requiring an extra 8-bit timer/counter. In Mode 3
of Timer0, the 8051 has three timers. One 8-bit timer by TH0, another8-bit timer/counter by
TL0, and one 16-bit timer/counter by Timer1.
If the Timer0 is in mode3, and Timer1 is working on either 0, 1 or 2, then the gun control of
the Timer1 is activated when the gate bit is low or INT1 is high. The run control is
deactivated when the gate is high and INT1 is low.
37 | P a g e
lOMoAR cPSD| 26885763
TxD:
This pin basically acts as a transmitter ( sending data ), but in some other modes it doesn’t do
the job of transmitter. As it is serial communication, it sends bit by bit, the processor gives 8-
bit at 1 time and those 8-bits are stored in a register named SBUF. Processor gives 1 byte of
data that is to be transmitted to SBUF and from there bit by bit is transferred , firstly LSB
and then at last MSB of the byte stored in SBUF. Once the total byte is transmitted, an
interrupt is sent to the processor by making some flag 1, so that the processor can send more
data for transmission as soon as the interrupt is received.
After every bit is transmitted, it requires delay for next bit transmission. So SBUF needs
triggering which is provided by
• Timer T1 ( here T1 only needs to trigger, T1 does not require its overflow flag , mode
3 in timers ). Here we can vary the delay, so data transmission delay can be varied (
frequency can be varied ). It has a variable baud rate.
• There is an internal clock in 8051 ( fosc / 12 = 1Mhz ) , where delay cannot be varied,
this has fixed trigger delay. So frequency cannot be varied.It has a fixed baud rate.
Whenever SBUF transferred 8bit of data , Ti flag becomes 1. Whenever processors go to
ISR( in other interrupts the flag is auto cleared whenever processor goes to ISR ) , in this the
Ti flag is not auto cleared.
RxD:
This pin is basically for data reception . It received data bit by bit ( as the transmitter sends
LSB first, it received LSB first ). There is also a register SBUF which stores 8 received bits.
Once the 8 bits are received, instead of sending an interrupt it firstly checks for errors ( errors
caused due to transmission). Once there is no error in the received information Ri flag is set
38 | P a g e
lOMoAR cPSD| 26885763
and an interrupt is sent to the processor. Processor goes to ISR ( here also R i is not cleared
automatically ).
How are SBUF in TxD and RxD different from each other ?
In SBUF of TxD, data is sent from processor to SBUF
In SBUF of RxD, data is sent from SBUF to the processor.
In this way both registers are differentiated by the processor.
39 | P a g e
lOMoAR cPSD| 26885763
Receiver assumes blue data ( when there was no communication ) also as data.
Here green is the start bit which is zero. And then the yellow colored is stop bit which is 1.
Whenever the first 0 bit comes, the receiver discards the start bit and accepts the next 8 bits
and stores in SBUF. Then the 9th bit is 1 , this bit is stored in RB8 ( will be discussed later ).
Then after this whenever the next zero bit comes ( that zero bit is discarded and accepts the
next 8 bits and so on ).
Stop bit is also used for error checking. Whenever SM2=1, It checks for error, If the RB8 = 1
( which means stop = 1 received, so the data is received correctly ) and if RB8=0 (
transmitter generated stop as 1, but received as 0 ) so there is an error. If there is an error in
received data, no interrupt is sent to the processor.
40 | P a g e
lOMoAR cPSD| 26885763
The 9th bit is a programmable bit and it is given through TB8. Here 9th bit is 1 and it is used
for error checking and stop bit for triggering the data high ( so start bit gets 0 and so on ).
Why the 9th bit , when the already stop bit exists?
Standard value of 9th bit is 1 and can be made 0.
Whenever SM2 = 1( receiver accepts only errorless data ) and if 9th bit is 1, then only
errorless data is accepted or else discarded. Discarding data is a purpose.
Mode 0 :
Totally there were four modes in serial port of 8051, but for better understanding mode 0 is
explained after three modes. In this mode data is transferred and received only through the
RxD channel. TxD is used for clocks. This is synchronous mode of communication.
Such a system is also known as half duplex mode. It has fixed baud rate.
SCON register:
41 | P a g e
lOMoAR cPSD| 26885763
Ti :
When 8-bits are received in SBUF , then Ri = 1, that would send an interrupt to the
processor.
Ri :
When 8-bits are sent from SBUF,and SBUF is empty , then Ri = 1, that would send an
interrupt to the processor. Before Ri=1, it checks for error based on SM2.
Interrupts are events detected by the MCU which cause normal program flow to be pre-
empted. Interrupts pause the current program and transfer control to a specified user-written
firmware routine called the Interrupt Service Routine (ISR). The ISR processes the interrupt
event, then resumes normal program flow.
Interrupt occurs
When an interrupt request flag is set and the interrupt is properly enabled, the interrupt
process begins:
1. Global Interrupts are disabled by clearing GIE to 0.
2. The current program context is saved to the shadow registers.
3. The value of the Program Counter is stored on the return stack.
4. Program control is transferred to the interrupt vector at address 04h.
42 | P a g e
lOMoAR cPSD| 26885763
ISR runs
The ISR is a function written by the user and placed at address 04h. The ISR does the
following:
1. Checks the interrupt-enabled peripherals for the source of the interrupt request.
2. Performs the necessary peripheral tasks.
3. Clears the appropriate interrupt request flag.
4. Executes the Return From Interrupt instruction (RETFIE) as the final ISR instruction.
43 | P a g e
lOMoAR cPSD| 26885763
44 | P a g e
lOMoAR cPSD| 26885763
The INTEDG flag in OPTION_REG is used to set a rising or falling edge on the INT pin as
the trigger for an INTE interrupt.
Enabling Interrupts
Core Interrupts
45 | P a g e
lOMoAR cPSD| 26885763
Three interrupt sources (Timer0, External Interrupt, and Interrupt on Change) have interrupt
enable bits located in INTCON. These interrupts are referred to as core interrupts.
46 | P a g e
lOMoAR cPSD| 26885763
UNIT II
EMBEDDED C PROGRAMMING
• Context Switching
47 | P a g e
lOMoAR cPSD| 26885763
48 | P a g e
lOMoAR cPSD| 26885763
In the 8051 Microcontroller, we have seen the 8051 Microcontroller Introduction and 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.
Hence, it is clear that the memory is an important part of the 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
first see a little bit about the Computer Architecture and then proceed with memory
organization of 8051 Microcontroller.
49 | P a g e
lOMoAR cPSD| 26885763
Harvard Architecture
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.
Almost all Microcontrollers, including 8051 Microcontroller implement Harvard
Architecture.
The 8051 Microcontroller Memory is separated in Program Memory (ROM) and Data
Memory (RAM). The Program Memory of the 8051 Microcontroller is used for storing the
program to be executed i.e., instructions. The Data Memory on the other hand, is used for
storing temporary variable data and intermediate results.
50 | P a g e
lOMoAR cPSD| 26885763
8051 Microcontroller has both Internal ROM and Internal RAM. If the internal memory is
inadequate, you can add external memory using suitable circuits.
In 8051 Microcontroller, the code or instructions to be executed are stored in the Program
Memory, which is also called as the ROM of the Microcontroller. The original 8051
Microcontroller by Intel has 4KB of internal ROM.
Some variants of 8051 like the 8031 and 8032 series doesn’t have any internal ROM
(Program Memory) and must be interfaced with external Program Memory with instructions
loaded in it.
Almost all modern 8051 Microcontrollers, like 8052 Series, have 8KB of Internal Program
Memory (ROM) in the form of Flash Memory (ROM) and provide the option of
reprogramming the memory.
In case of 4KB of Internal ROM, the address space is 0000H to 0FFFH. If the address space
i.e., the program addresses exceed this value, then the CPU will automatically fetch the code
from the external Program Memory.
For this, the External Access Pin (EA Pin) must be pulled HIGH i.e., when the EA Pin is
high, the CPU first fetches instructions from the Internal Program Memory in the address
range of 0000H to 0FFFFH and if the memory addresses exceed the limit, then the
instructions are fetched from the external ROM in the address range of 1000H to FFFFH.
51 | P a g e
lOMoAR cPSD| 26885763
There is another way to fetch the instructions: ignore the Internal ROM and fetch all the
instructions only from the External Program Memory (External ROM). For this scenario, the
EA Pin must be connected to GND. In this case, the memory addresses of the external ROM
will be from 0000H to FFFFH.
52 | P a g e
lOMoAR cPSD| 26885763
But almost all modern variants of 8051 Microcontroller have 256B of RAM. In this 256B,
the first 128B i.e., memory addresses from 00H 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 address the register by name, first the corresponding Bank must be selected.
In order to select the bank, we have to use the RS0 and RS1 bits of the Program Status Word
(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 16B of the RAM i.e., from 20H to 2FH are Bit – Addressable memory locations.
There are totally 128 bits that can be addressed individually using 00H to 7FH or the entire
byte can be addressed as 20H to 2FH.
53 | P a g e
lOMoAR cPSD| 26885763
The designer of an 8051 Microcontroller based system is not limited to the internal RAM and
ROM present in the 8051 Microcontroller. There is a provision of connecting both external
RAM and ROM i.e., Data Memory and Program.
The reason for interfacing external Program Memory or ROM is that complex programs
written in high – level languages often tend to be larger and occupy more memory.
Another important reason is that chips like 8031 or 8032, which doesn’t have any internal
ROM, 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 shows the block diagram of interfacing 64KB of External RAM and
64KB of External ROM with the 8051 Microcontroller.
54 | P a g e
lOMoAR cPSD| 26885763
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.
Embedded C programming plays a key role in performing specific function by the processor.
In day-to-day life we used many electronic devices such as mobile phone, washing machine,
digital camera, etc. These all device working is based on microcontroller that are
programmed by embedded C.
In embedded system programming C code is preferred over other language. Due to the
following reasons:
o Easy to understand
o High Reliability
o Portability
o Scalability
Let's see the block diagram representation of embedded system programming:
55 | P a g e
lOMoAR cPSD| 26885763
Basic Declaration
Let's see the block diagram of Embedded C Programming development:
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 of basic elements and grammatical rules. The C language programming is
designed for function with variables, character set, data types, keywords, expression and so
on are used for writing a C program.
#include<microcontroller name.h>
56 | P a g e
lOMoAR cPSD| 26885763
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.
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 and transmit it wirelessly. And take
wireless data from the device (like a mobile) and send it through the 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.
57 | P a g e
lOMoAR cPSD| 26885763
It takes some inputs from the user like wash cycle, type of clothes, extra soaking and rinsing,
spin rpm, etc., performs the necessary actions as per the instructions and finishes washing
and drying the clothes. If no new instructions are given for the next wash, then the washing
machines repeats the same set of tasks as the previous wash.
Embedded Systems can not only be stand-alone devices like Washing Machines but also be a
part of a much larger system. An example for this is a Car. A modern day Car has several
individual embedded systems that perform their specific tasks with the aim of making a
smooth and safe journey.
Some of the embedded systems in a Car are Anti-lock Braking System (ABS), Temperature
Monitoring System, Automatic Climate Control, Tire Pressure Monitoring System, Engine
Oil Level Monitor, etc.
All these devices have one thing in common: they are programmable i.e., we can write a
program (which is the software part of the Embedded System) to define how the device
actually works.
From the above statement, it is clear that the Software part of an Embedded System is
equally important as the Hardware part. There is no point in having advanced Hardware
Components with poorly written programs (Software).
There are many programming languages that are used for Embedded Systems like Assembly
(low-level Programming Language), C, C++, JAVA (high-level programming languages),
Visual Basic, JAVA Script (Application level Programming Languages), etc.
58 | P a g e
lOMoAR cPSD| 26885763
In the process of making a better embedded system, the programming of the system plays a
vital role and hence, the selection of the Programming Language is very important.
• Size: The memory that the program occupies is very important as Embedded
Processors like Microcontrollers have a very limited amount of ROM (Program
Memory).
• Speed: The programs must be very fast i.e., they must run as fast as possible. The
hardware should not be slowed down due to a slow running software.
• Portability: The same program can be compiled for different processors.
• Ease of Implementation
• Ease of Maintenance
• Readability
Earlier Embedded Systems were developed mainly using Assembly Language. Even though
Assembly Language is closest to the actual machine code instructions and produces small
size hex files, the lack of portability and high amount of resources (time and man power)
spent on developing the code, made the Assembly Language difficult to work with.
There are other high-level programming languages that offered the above mentioned features
but none were close to C Programming Language. Some of the benefits of using Embedded
C as the main Programming Language:
59 | P a g e
lOMoAR cPSD| 26885763
• Starting from consumer electronics like Digital Cameras, DVD Players to high end
and advanced systems like Flight Controllers and Missile Guidance Systems,
embedded systems are omnipresent and became an important part of our life.
• The way we live our life has been significantly improved with the utilization of
Embedded Systems and they will continue to be an integral part of our lives even
tomorrow.
• Another important concept we are hearing these days is Real – Time Systems. In
a real time system, Real Time Computing takes place, where a computer (an
Embedded System) must generate response to events within certain time limits.
• Before going in to the details of Real Time Applications of Embedded Systems, we
will first see what an Embedded System is, what is a real time system and what is real
time operating system.
Processor: The heart of an Embedded System is the Processor. Based on the functionality of
the 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: Memory is another important part of an embedded system. It is divided in to RAM
and ROM. Memory in an Embedded System (ROM to be specific) stores the main program
and RAM 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.
60 | P a g e
lOMoAR cPSD| 26885763
Software: All the hardware work according to the software (main program) written. Software
part of an Embedded System includes initialization of the system, controlling inputs and
outputs, error handling etc.
NOTE: Many Embedded Systems, usually small to medium scaled systems, generally
consists of 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.
61 | P a g e
lOMoAR cPSD| 26885763
• bit
• sbit
• sfr
• small
• large
The following table lists out all the keywords associated with the Cx51 C Compiler.
_at_ alien bdata
bit code compact
data far idata
interrupt large pdata
_priority_ reentrant sbit
sfr sfr16 small
_task_ using xdata
62 | P a g e
lOMoAR cPSD| 26885763
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 part shows the basic structure of an Embedded C Program.
There are two ways you can write comments: one is the single line comments denoted by //
and the other is multiline comments denoted by /*….*/.
63 | P a g e
lOMoAR cPSD| 26885763
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.
64 | P a g e
lOMoAR cPSD| 26885763
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.
65 | P a g e
lOMoAR cPSD| 26885763
It is very cheap and easily available in variety of shape, color and size. The LEDs are also
used in designing of message display boards and traffic control signal lights etc.
Consider the Proteus Software based simulation of LED blinking using 8051
Microcontroller is shown below:-
In above Proteus based simulation the LEDs are interfaced to the PORT0 of the 8051
microcontroller.
Let's see the Embedded C Program for generating the LED output sequence as shown
below:
00000001
00000010
00000100.....
.... And so on up to 10000000.
#include<reg51.h>
void main()
{
unsigned int k;
unsigned char l,b;
while(1)
{
P0=0x01;
66 | P a g e
lOMoAR cPSD| 26885763
b=P0;
for(l-0;l<3000;l++);
for(k=0;k<8;k++)
{
b=b<<1;
P0=b;
}
}
}
Consider the Embedded C Program for generating the LED output sequence as shown
below is:-
00000001
00000011
00000111.....
.... And so on up to 11111111.
#include<reg51.h>
void main()
{
unsigned int i;
unsigned char j,b;
while(1)
{
P0=0x01;
b=P0;
for(j-0;j<3000;j++);
for(j=0;j<8;j++)
{
bb=b<<1;
b=0x01;
P0=b;
}
}
}
Displaying Number on 7-Segment Display using 8051 Microcontroller
Electronic display used for displaying alphanumeric character is known as 7-Segment display
it is used in many systems for displaying the information.
67 | P a g e
lOMoAR cPSD| 26885763
It is constructed using eight LEDs which are connected in sequential way so as to display
digits from 0 to 9, when certain combinations of LEDs are switched on. It displays only one
digit at a time.
Consider the program for displaying the number from '0 to F' on 7-segment display is:-
10s
#include<reg51.h>
sbit a= P3^0;
sbit x= P3^1;
sbit y= P3^2;
sbit z= P3^3;
void main()
{
unsigned char m[10]={0?40,0xF9,0?24,0?30,0?19,0?12,0?02,0xF8,0xE00,0?10};
unsigned int i,j;
a=x=y=z=1;
while(1)
{
for(i=0;i<10;i++)
{
P2=m[i];
for(j=0;j<60000;j++);
}
68 | P a g e
lOMoAR cPSD| 26885763
}
}
Consider the program for displaying numbers from '00 to 10' on a 7segment display is:-
#include<reg51.h>
sbit x= P3^0;
sbit y= P3^1;
void display1();
void display2();
void delay();
void main()
{
unsigned char m[10]={0?40,0xF9,0?24,0?30,0?19,0?12,0?02,0xF8,0xE00,0?10};
unsigned int i,j;
ds1=ds2=0;
while(1)
{
for(i=0,i<20;i++)
display1();
display2();
}
}
void display1()
{
x=1;
y=0;
P2=m[ds1];
delay();
x=1;
y=0;
P2=m[ds1];
delay();
}
void display2()
{
ds1++;
if(ds1>=10)
{
ds1=0;
ds2++;
if(ds2>=10)
69 | P a g e
lOMoAR cPSD| 26885763
{
ds1=ds2=0;
}
}
}
void delay()
{
unsigned int k;
for(k=0;k<30000;k++);
}
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.
Developers used to OS’s such as Windows or Linux will be quite familiar with the
characteristics of an embedded RTOS. They are designed to run in systems with limited
memory, and to operate indefinitely without the need to be reset.
Because an RTOS is designed to respond to events quickly and perform under heavy loads, it
can be slower at big tasks when compared to another OS.
70 | P a g e
lOMoAR cPSD| 26885763
An RTOS is valued for how quickly it can respond and in that, the advanced scheduling
algorithm is the key component.
The time-criticality of embedded systems vary from soft-real time washing machine control
systems through hard-real time aircraft safety systems. In situations like the latter, the
fundamental demand to meet real-time requirements can only be made if the OS scheduler’s
behavior can be accurately predicted.
Many operating systems give the impression of executing multiple programs at once, but this
multi-tasking is something of an illusion. A single processor core can only run a single thread
of execution at any one time. An operating system’s scheduler decides which program, or
thread, to run when. By rapidly switching between threads, it provides the illusion of
simultaneous multitasking.
The flexibility of an RTOS scheduler enables a broad approach to process priorities, although
an RTOS is more commonly focused on a very narrow set of applications. An RTOS
scheduler should give minimal interrupt latency and minimal thread switching overhead.
This is what makes an RTOS so relevant for time-critical embedded systems.
Using an RTOS means you can run multiple tasks concurrently, bringing in the basic
connectivity, privacy, security, and so on as and when you need them. An RTOS allows you
to create an optimized solution for the specific requirements of your project.
71 | P a g e
lOMoAR cPSD| 26885763
72 | P a g e
lOMoAR cPSD| 26885763
Function Library: It is an important element of RTOS that acts as an interface that helps
you to 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 interval between the termination of the task that can be
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 languages
like C or C++, which should be organized according to their operation.
73 | P a g e
lOMoAR cPSD| 26885763
74 | P a g e
lOMoAR cPSD| 26885763
RTOS
75 | P a g e
lOMoAR cPSD| 26885763
2. Task Shifting
Time assigned for shifting tasks in these systems is very less. For example, in older
systems, it takes about 10 microseconds. Shifting one task to another and in the latest
systems, it takes 3 microseconds.
3. Focus On Application –
Focus on running applications and less importance to applications that are in the queue.
5. Error Free –
These types of systems are error-free.
6. Memory Allocation –
Memory allocation is best managed in these types of systems.
1. Limited Tasks –
Very few tasks run simultaneously, and their concentration is very less on few
applications to avoid errors.
3. Complex Algorithms –
The algorithms are very complex and difficult for the designer to write on.
76 | P a g e
lOMoAR cPSD| 26885763
5. Thread Priority –
It is not good to set thread priority as these systems are very less prone to switching tasks.
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 program two different
times, we have created two different processes. Each process has its own state that includes
not only its registers but all of its memory. In some OSs, the memory management unit is
used to keep each process in a separate address space. In others, particularly lightweight
RTOSs, the processes run in the same address space. Processes that share the same address
space are often called threads.
As shown in Figure, this device is connected to serial ports on both ends. The input to the
box is an uncompressed stream of bytes. The box emits a compressed string of bits on the
77 | P a g e
lOMoAR cPSD| 26885763
output serial line, based on a predefined compression table. Such a box may be used, for
example, to compress data being sent to a modem.
The program’s need to receive and send data at different rates for example, the program
may emit 2 bits for the first byte and then 7 bits for the second byte will obviously find itself
reflected in the structure of the code. It is easy to create irregular, ungainly code to solve this
problem; a more elegant solution is to create a queue of output bits, with those bits being
removed from the queue and sent to the serial port in 8-bit sets.
But beyond the need to create a clean data structure that simplifies the control structure of the
code, we must also ensure that we process the inputs and outputs at the proper rates. For
example, if we spend too much time in packaging and emitting output characters, we may
drop an input character. Solving timing problems is a more challenging problem.
The text compression box provides a simple example of rate control problems. A control
panel on a machine provides an example of a different type of rate control problem,
the asynchronous input.
The control panel of the 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 button the button may be depressed asynchronously relative to the
arrival of characters for compression.
78 | P a g e
lOMoAR cPSD| 26885763
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 control of the CPU and starts to run. An
aperiodic process is by definition initiated by an event, such as external data arriving or data
computed by another process.
79 | P a g e
lOMoAR cPSD| 26885763
The release time is generally measured from that event, although the system may want to
make the process ready at some interval after the event itself. For a periodically executed
process, 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 a time 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 period of a process is the time between successive executions. For example, the period
of a digital filter is defined by the time interval between successive input samples.
The process’s rate is the inverse of its period. In a multirate system, each process 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. Figure illustrates process execution in a system with four CPUs.
CPU Metrics
80 | P a g e
lOMoAR cPSD| 26885763
We also need some terminology to describe how the process actually executes.
The initiation time is the time at which a process actually starts executing on the CPU.
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 . Note that the CPU time is not equal to the completion
time minus initiation time; several other processes may interrupt execution. The total CPU
time consumed by a set of processes is
T= ∑ Ti
We need a basic measure of the efficiency with which we use the CPU. The simplest and
most direct measure is utilization:
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 CPU time is being used for system purposes. The utilization is often expressed as a
percentage. If we measure the total execution time of all processes over an interval of time t,
then the CPU utilization is
U=T/t.
It is easy to create irregular, ungainly code to solve this problem; a more elegant
solution is to create a queue of out put bits, with those bits being removed from the queue
and sent to the serial port in 8-bit sets. But beyond the need to create a clean data structure
81 | P a g e
lOMoAR cPSD| 26885763
that simplifies the control structure of the code, we must also ensure that we process the
inputs and outputs at the proper rates. For example, if we spend too much time in packaging
and emitting output characters, we may drop an input character. Solving timing problems is a
more challenging problem.
The text compression box provides a simple example of rate control problems. A
control panel on a machine provides an example of a different type of rate con- troll problem,
the asynchronous input. The control panel of the compression box may, for example, include
a compression mode button that disables or enables com- pression, 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 modebutton— the button may be depressed a
synchronously relative to the arrival of characters for compression. We do know, however,
that the button will be depressed at a much lower rate than characters will be received, since
it is not physically possible for a person to repeatedly depress a button at even slow serial
line rates. Keeping up with the input and output data while checking on the button can
introduce some very complex control code in to the program. Sampling the button’s state too
slowly can cause the machine to miss a button depression entirely, but sampling it too
frequently and duplicating a data value can cause the machine to in correctly compress data.
One solution is to introduce a counter in to the main compression loop, so that a subroutine
to check the input button is called once every times the compression loop is executed. But
this solution does not work when either the compression loop or the button-handling routine
has highly variable execution times—if the execution time of either varies significantly, it
will cause the other to execute later than expected, possibly causing data to be lost. We need
to be able to keep track of these two different tasks separately, applying different timing
requirements to each.
This is the sort of control that processes allow. The above two examples illustrate how
requirements on timing and execution rate can create major problems in programming. When
code is written to satisfy several different timing requirements at once, the control structures
necessary to get any sort of solution become very complex very quickly. Worse, such
complex control is usually quite difficult to verify for either functional or timing properties.
82 | P a g e
lOMoAR cPSD| 26885763
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 CPU time is being used for system purposes. The utilization is often expressed as a
percentage. If we measure the total execution time of all processes over an interval of time t,
then the CPU utilization is U/T
83 | P a g e
lOMoAR cPSD| 26885763
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 in some cases we can eliminate some sets of processes as
unschedulable 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 we can’t use the CPU more than100% of the time.
When we evaluate the utilization of the CPU, we generally do so over 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 of the
periods of all the processes. If we evaluate the hyper period, we are sure to have considered
all possible combinations of the periodic processes.
designer. Here is a very simple program that runs our process subroutines repeatedly: A timer
is a much more reliable way to control execution of the loop. We would probably use the
timer to generate periodic interrupts. Let’s assume for the moment that the pall() function is
called by the timer’s interrupt handler. Then this code will execute each process once after a
timer interrupt:
voidpall()
{
p1();
p2();
}
But what happens when a process runs too long? The timer’s interrupt will cause the CPU’s
interrupt system to mask its interrupts, so the interrupt will not occur until after the pall()
routine returns. As a result, the next iteration will start late. This is a serious problem, but we
will have to wait for further refinements before we can fix it.
Our next problem is to execute different processes at different rates. If we have several
timers, we can set each timer to a different rate. We could then use a function to collect all
the processes that run at that rate:
voidpA()
84 | P a g e
lOMoAR cPSD| 26885763
{
/*processesthatrunatrateA*/
p1();
p3();
}
void pB()
{
/*processesthatrunatrateB*/
}
This solution allows us to execute processes at rates that are simple multiples of each other.
However, when the rates are n’t related by a simple ratio, the counting process becomes more
complex and more likely to contain bugs. We have developed somewhat more reliable code,
but this programming style is still limited in capability and prone to bugs. To improve both
the capabilities and reliability of our systems, we need to invent the RTOS.
Context Switch
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 is running using the CPU to do its job. While a process is
running, other processes with the highest priority queue up to use the CPU to complete their
job.
85 | P a g e
lOMoAR cPSD| 26885763
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.
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
switching makes it easier for the operating system to use the CPU’s resources to carry out
its tasks and store its 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.
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.
Multitasking: The ability for a process to be switched from the CPU so that another process
can 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.
86 | P a g e
lOMoAR cPSD| 26885763
a computer to store all information about a process. It is also called the descriptive process.
When a process is created (started or installed), the operating system creates a process
manager.
87 | P a g e
lOMoAR cPSD| 26885763
88 | P a g e
lOMoAR cPSD| 26885763
P2 2 3 0
P3 1 7 6
P4 3 4 11
P5 2 2 12
Step 0) At time=0, Process P1 and P2 arrive. P1 has higher priority than P2. The execution
begins with process P1, which has burst time 4.
Step 2) At time 2, no new process arrives, so you can continue with P1. P2 is in the waiting
queue.
Step 3) At time 3, no new process arrives so you can continue with P1. P2 process still in the
waiting queue.
89 | P a g e
lOMoAR cPSD| 26885763
Step 6) At time=6, P3 arrives. P3 is at higher priority (1) compared to P2 having priority (2).
P2 is preempted, and P3 begins its execution.
Process Priority Burst time Arrival time
P1 1 4 0
P2 2 1 out of 3 pending 0
P3 1 7 6
P4 3 4 11
P5 2 2 12
90 | P a g e
lOMoAR cPSD| 26885763
Step 7) At time 7, no-new process arrives, so we continue with P3. P2 is in the waiting
queue.
Step 10) At time interval 10, no new process comes, so we continue with P3
91 | P a g e
lOMoAR cPSD| 26885763
Step 11) At time=11, P4 arrives with priority 4. P3 has higher priority, so it continues its
execution.
Process Priority Burst time Arrival time
P1 1 4 0
P2 2 1 out of 3 pending 0
P3 1 2 out of 7 pending 6
P4 3 4 11
P5 2 2 12
Step 13) At time=13, P3 completes execution. We have P2,P4,P5 in ready queue. P2 and P5
have equal priority. Arrival time of P2 is before P5. So P2 starts execution.
Process Priority Burst time Arrival time
P1 1 4 0
92 | P a g e
lOMoAR cPSD| 26885763
Step 14) At time =14, the P2 process has finished its execution. P4 and P5 are in the waiting
state. P5 has the highest priority and starts execution.
Step 16) At time= 16, P5 is finished with its execution. P4 is the only process left. It starts
execution.
93 | P a g e
lOMoAR cPSD| 26885763
Step 17) At time =20, P5 has completed execution and no process is left.
Step 18) 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.6
94 | P a g e
lOMoAR cPSD| 26885763
• This scheduling algorithm may leave some low priority processes waiting
indefinitely.
• A process will be blocked when it is ready to run but has to wait for the CPU because
some other process is running currently.
• If a new higher priority process keeps on coming in the ready queue, then the process
which is in the waiting state may need to wait for a long duration of time.
Each thread in the system may run using any method. The methods are effective on a per-
thread basis, not on a global basis for all threads and processes on a node.
Remember that the FIFO and round-robin scheduling policies apply only when two or more
threads that share the same priority are READY (i.e., the threads are directly competing with
each other). The sporadic method, however, employs a “budget” for a thread's execution. In
all cases, if a higher-priority thread becomes READY, it immediately preempts all lower-
priority threads.
In the following diagram, three threads of equal priority are READY. If Thread A blocks,
Thread B will run. Although a thread inherits its scheduling policy from its parent process,
the thread can request to change the algorithm applied by the kernel.
95 | P a g e
lOMoAR cPSD| 26885763
96 | P a g e
lOMoAR cPSD| 26885763
UNIT III
• IoT Configurations
• Basic Components
• Introduction to Arduino
• Types of Arduino
• Arduino Toolchain
• Sketches
• Pins
97 | P a g e
lOMoAR cPSD| 26885763
IoT stands for Internet of Things, which means accessing and controlling daily usable
equipments and devices using Internet.
Connecting everyday things embedded with electronics, software, and sensors to internet
enabling to collect and exchange data without human interaction called as the Internet of
Things (IoT).
The term "Things" in the Internet of Things refers to anything and everything in day to day
life which is accessed or connected through the internet.
IoT is an advanced automation and analytics system which deals with artificial intelligence,
sensor, networking, electronic, cloud messaging etc. to deliver complete systems for the
product or services. The system created by IoT has greater transparency, control, and
performance.
As we have a platform such as a cloud that contains all the data through which we connect all
the things around us. For example, a house, where we can connect our home appliances such
as air conditioner, light, etc. through each other and all these things are managed at the same
platform. Since we have a platform, we can connect our car, track its fuel meter, speed level,
and also track the location of the car.
98 | P a g e
lOMoAR cPSD| 26885763
If there is a common platform where all these things can connect to each other would be
great because based on my preference, I can set the room temperature. For example, if I love
the room temperature to to be set at 25 or 26-degree Celsius when I reach back home from
my office, then according to my car location, my AC would start before 10 minutes I arrive
at home. This can be done through the Internet of Things (IoT).
Connectivity: Connectivity refers to establish a proper connection between all the things of
IoT to IoT platform it may be server or cloud. After connecting the IoT devices, it needs a
99 | P a g e
lOMoAR cPSD| 26885763
high speed messaging between the devices and cloud to enable reliable, secure and bi-
directional communication.
Analyzing: After connecting all the relevant things, it comes to real-time analyzing the data
collected and use them to build effective business intelligence. If we have a good insight into
data gathered from all these things, then we call our system has a smart system.
Integrating: IoT integrating the various models to improve the user experience as well.
Artificial Intelligence: IoT makes things smart and enhances life through the use of data.
For example, if we have a coffee machine whose beans have going to end, then the coffee
machine itself order the coffee beans of your choice from the retailer.
Sensing: The sensor devices used in IoT technologies detect and measure any change in the
environment and report on their status. IoT technology brings passive networks to active
networks. Without sensors, there could not hold an effective or true IoT environment.
Active Engagement: IoT makes the connected technology, product, or services to active
engagement between each other.
Endpoint Management: It is important to be the endpoint management of all the IoT system
otherwise, it makes the complete failure of the system. For example, if a coffee machine
itself order the coffee beans when it goes to end but what happens when it orders the beans
from a retailer and we are not present at home for a few days, it leads to the failure of the IoT
system. So, there must be a need for endpoint management.
100 | P a g e
lOMoAR cPSD| 26885763
101 | P a g e
lOMoAR cPSD| 26885763
An embedded device system generally runs as a single application. However, these devices
can connect through the internet connection, and able communicate through other network
devices.
The essential component of the embedded system is a RISC family microcontroller like
Motorola 68HC11, PIC 16F84, Atmel 8051 and many more. The most important factor that
differentiates these microcontrollers with the microprocessor like 8085 is their internal read
and writable memory. The essential embedded device components and system architecture
are specified below.
102 | P a g e
lOMoAR cPSD| 26885763
The IoT decision framework provides a structured approach to create a powerful IoT product
strategy. The IoT decision framework is all about the strategic decision making. The IoT
Decision Framework helps us to understand the areas where we need to make decisions and
ensures consistency across all of our strategic business decision, technical and more.
The IoT decision framework is much more important as the product or services
communicates over networks goes through five different layers of complexity of technology.
1. Device Hardware
2. Device Software
3. Communications
4. Cloud Platform
5. Cloud Application
The IoT decision framework pays attention to six key decision areas in any IoT product.
These decision areas are:
1. User Experience (UX)
2. Data
3. Business
4. Technology
5. Security
6. Standards & Regulations
103 | P a g e
lOMoAR cPSD| 26885763
Each of these decision areas is evaluated at each of the IoT Technology Stack. The User
Experience will be evaluated at Device Hardware, Device Software and so to provide the
better user experience. Then at the next step Data Decision Area, we have to explore data
considerations for all the stages of IoT Technology Stack.r
Let's see each of the Decision Area of IoT Decision Framework in detail:
1. User Experience Decision Area: This is the area where we concentrate about who
are the users, what are their requirements and how to provide a great experience at
each step of IoT stack without worrying about the technical details.
2. Data Decision Area: In this area, we make the overall data strategy such as the data
flow over the entire IoT stack to fulfill the user's requirements.
3. Business Decision Area: Based on the previous decisions area, we make the decision
how product or services will became financial potential. At each of the IoT Stack
level are monetized about the costs of providing services.
4. Technology Decision Area: In this area, we work with the technology for each layer
to facilitate the final solution.
5. Security Decision Area: After going through the implementation of technology it is
important to decide and provide the security at each stage of the IoT Stack.
6. Standards & Regulations Decision Area: At the last stage of IoT Decision Area, we
identify the standards and regulations of product or services that will affect your
product at each layer of the IoT Stack.
There are several layers of IoT built upon the capability and performance of IoT elements
that provides the optimal solution to the business enterprises and end-users. The IoT
architecture is a fundamental way to design the various elements of IoT, so that it can
deliver services over the networks and serve the needs for the future.
104 | P a g e
lOMoAR cPSD| 26885763
Following are the primary stages (layers) of IoT that provides the solution for IoT
architecture.
1. Sensors/Actuators: Sensors or Actuators are the devices that are able to emit, accept
and process data over the network. These sensors or actuators may be connected
either through wired or wireless. This contains GPS, Electrochemical, Gyroscope,
RFID, etc. Most of the sensors need connectivity through sensors gateways. The
connection of sensors or actuators can be through a Local Area Network (LAN) or
Personal Area Network.
2. Gateways and Data Acquisition: As the large numbers of data are produced by this
sensors and actuators need the high-speed Gateways and Networks to transfer the
data. This network can be of type Local Area Network (LAN such as WiFi, Ethernet,
etc.), Wide Area Network (WAN such as GSM, 5G, etc.).
3. Edge IT: Edge in the IoT Architecture is the hardware and software gateways that
analyze and pre-process the data before transferring it to the cloud. If the data read
from the sensors and gateways are not changed from its previous reading value then it
does not transfer over the cloud, this saves the data used.
4. Data center/ Cloud: The Data Center or Cloud comes under the Management
Services which process the information through analytics, management of device and
security controls. Beside this security controls and device management the cloud
transfer the data to the end users application such as Retail, Healthcare, Emergency,
Environment, and Energy, etc.
105 | P a g e
lOMoAR cPSD| 26885763
we will discuss the overview of the Internet of Things and Computers and mainly will focus
on the difference between IoT devices and Computers. Let’s discuss it one by one.
Function of Computer
106 | P a g e
lOMoAR cPSD| 26885763
To get started with IoT device discovery in your network, all you need is a security device
connected to Juniper ATP Cloud.
107 | P a g e
lOMoAR cPSD| 26885763
As shown in the topology, the network includes some IoT devices connected to an SRX
Series device through wireless access point (AP). The security device is connected to the
Juniper Cloud ATP server, and to a host device.
The security device collects IoT device metadata and streams the relevant information to the
Juniper ATP Cloud. To enable streaming of IoT metadata, you'll need to create security
metadata streaming policies and attach these policies to security policies. Streaming of the
IoT device traffic pauses automatically when Juniper Cloud server has sufficient details to
classify the IoT device.
Juniper ATP cloud discovers and classifies IoT devices. Using the inventory of discovered
IoT devices, you'll create threat feeds in the form of dynamic address groups. Once the
security device downloads dynamic address groups, you can use the dynamic address groups
to create and enforce security policies for the IoT traffic.
Requirements
• SRX Series device or NFX Series device
• Junos OS Release 22.1R1 or later
• Juniper Advanced Threat Prevention Cloud Account. We've verified and tested the
configuration using a vSRX instance with Junos OS Release 22.1R1.
108 | P a g e
lOMoAR cPSD| 26885763
109 | P a g e
lOMoAR cPSD| 26885763
110 | P a g e
lOMoAR cPSD| 26885763
111 | P a g e
lOMoAR cPSD| 26885763
IoT Gateway manages the bidirectional data traffic between different networks and
protocols. Another function of the gateway is to translate different network protocols and
make sure interoperability of the connected devices and sensors.
Gateways can be configured to perform pre-processing of the collected data from thousands
of sensors locally before transmitting it to the next stage. In some scenarios, it would be
necessary due to the compatibility of the TCP/IP protocol.
IoT gateway offers a certain level of security for the network and transmitted data with
higher-order encryption techniques. It acts as a middle layer between devices and the cloud
to protect the system from malicious attacks and unauthorized access.
3. Cloud
The Internet of Things creates massive data from devices, applications, and users,
which has to be managed in an efficient way. IoT cloud offers tools to collect, process,
manage and store huge amounts of data in real time. Industries and services can easily access
these data remotely and make critical decisions when necessary.
Cloud system integrates billions of devices, sensors, gateways, protocols, and data storage
and provides predictive analytics. Companies use these analytics data to improve products
and services, preventive measures for certain steps, and build their new business model
accurately.
4. Analytics
Analytics is the process of converting analog data from billions of smart devices and
sensors into useful insights which can be interpreted and used for detailed analysis. Smart
112 | P a g e
lOMoAR cPSD| 26885763
analytics solutions are inevitable for IoT systems for the management and improvement of
the entire system.
One of the major advantages of an efficient IoT system is real-time smart analytics which
helps engineers to find out irregularities in the collected data and act fast to prevent an
undesired scenario. Service providers can prepare for further steps if the information is
collected accurately at the right time.
Big enterprises use the massive data collected from IoT devices and utilize the insights for
their future business opportunities. Careful analysis will help organizations to predict trends
in the market and plan ahead for a successful implementation.
Information is very significant in any business model, and predictive analysis ensures success
in the concerned area of the business line.
5. User interface
User interfaces are the visible, tangible part of the IoT system which users can access.
Designers will have to make sure of a well-designed user interface for minimum effort for
users and encourage more interactions.
Modern technology offers much interactive design to ease complex tasks into simple touch
panel controls. Multicolor touch panels have replaced hard switches in our household
appliances, and the trend is increasing for almost every smart home device.
113 | P a g e
lOMoAR cPSD| 26885763
The user interface design has higher significance in today’s competitive market; it often
determines the user whether to choose a particular device or appliance. Users will be
interested in buying new devices or smart gadgets if it is very user-friendly and compatible
with common wireless standards.
114 | P a g e
lOMoAR cPSD| 26885763
3.5. Arduino
A decade ago, working around electronics involved knowledge in physics and math,
expensive lab equipment, a laboratory type setup and important of all, love for electronics.
But the picture has changed over the decade or so where the above-mentioned factors
became irrelevant to work around electronics except for the last part: love for electronics.
One such product which made use of the above specified and many other reasons and made
electronics be able reach anyone regardless of their background is “Arduino”.
3.5.1. Introduction
Arduino is an open-source prototyping platform in electronics based on easy-to-use hardware
and software. Subtly speaking, Arduino is a microcontroller based prototyping board which
can be used in developing digital devices that can read inputs like finger on a button, touch
on a screen, light on a sensor etc. and turning it in to output like switching on an LED,
rotating a motor, playing songs through a speaker etc.
The aim of Arduino is to introduce the world of electronics to people who have small to no
experience in electronics like hobbyists, designers, artists etc.
115 | P a g e
lOMoAR cPSD| 26885763
Arduino is based on open source electronics project i.e. all the design specifications,
schematics, software are available openly to all the users. Hence, Arduino boards can bought
from vendors as they are commercially available or else you can make your own board by if
you wish i.e. you can download the schematic from Arduino’s official website, buy all the
components as per the design specification, assemble all the components, and make your
own board.
The important feature of the Arduino boards is the standard connectors. Using these
connectors, we can connect the Arduino board to other devices like LEDs or add-on modules
called Shields.
The Arduino boards also consists of on board voltage regulator and crystal oscillator. They
also consist of USB to serial adapter using which the Arduino board can be programmed
using USB connection.
In order to program the Arduino board, we need to use IDE provided by Arduino. The
Arduino IDE is based on Processing programming language and supports C and C++.
Arduino boards are available in different sizes, form factors, different no. of I/O pins etc.
Some of the commonly known and frequently used Arduino boards are Arduino
UNO, Arduino Mega, Arduino Nano, Arduino Micro and Arduino Lilypad.
116 | P a g e
lOMoAR cPSD| 26885763
There are add-on modules called Arduino Shields which can be used to extend the
functionalities of the Arduino boards. Some of the commonly used shields are Arduino Proto
shield, Arduino WiFi Shield and Arduino Yun Shield.
117 | P a g e
lOMoAR cPSD| 26885763
118 | P a g e
lOMoAR cPSD| 26885763
down to a small footprint capable of fitting into tight spaces. It can also be inserted directly
into a breadboard, making it easy to prototype with.
(Note that some of the links on this page are affiliate links. This does not change the cost of
the item for you. I reinvest whatever proceeds I receive into making new projects. If you
would like any suggestions for alternative suppliers, please let me know.)
The nice thing about the Arduino board is that it is relatively cheap, plugs straight into a
computer's USB port, and it is dead-simple to setup and use (compared to other development
boards).
Some of the key features of the Arduino Uno include:
An open source design. The advantage of it being open source is that it has a large
community of people using and troubleshooting it. This makes it easy to find someone to
help you debug your projects.
119 | P a g e
lOMoAR cPSD| 26885763
• An easy USB interface . The chip on the board plugs straight into your USB port and
registers on your computer as a virtual serial port. This allows you to interface with it as
through it were a serial device. The benefit of this setup is that serial communication is an
extremely easy (and time-tested) protocol, and USB makes connecting it to modern
computers really convenient.
• Very convenient power management and built-in voltage regulation. You can connect an
external power source of up to 12v and it will regulate it to both 5v and 3.3v. It also can be
powered directly off of a USB port without any external power.
• An easy-to-find, and dirt cheap, microcontroller "brain." The ATmega328 chip retails for
about $2.88 on Digikey. It has countless number of nice hardware features like timers, PWM
pins, external and internal interrupts, and multiple sleep modes. Check out the
official datasheet for more details.
• A 16mhz clock. This makes it not the speediest microcontroller around, but fast enough for
most applications.
• 32 KB of flash memory for storing your code.
• 13 digital pins and 6 analog pins. These pins allow you to connect external hardware to your
Arduino. These pins are key for extending the computing capability of the Arduino into the
real world. Simply plug your devices and sensors into the sockets that correspond to each of
these pins and you are good to go.
• An ICSP connector for bypassing the USB port and interfacing the Arduino directly as a
serial device. This port is necessary to re-bootload your chip if it corrupts and can no longer
talk to your computer.
• An on-board LED attached to digital pin 13 for fast an easy debugging of code.
• And last, but not least, a button to reset the program on the chip.
Before you can start doing anything with the Arduino, you need to download and install
the Arduino IDE (integrated development environment). From this point on we will be
referring to the Arduino IDE as the Arduino Programmer.
120 | P a g e
lOMoAR cPSD| 26885763
The Arduino Programmer is based on the Processing IDE and uses a variation of the C and
C++ programming languages.
You can find the most recent version of the Arduino Programmer on this page.
Step 4: Plug It In
It is also good to know that every single Arduino has a unique virtual serial port address.
This means that every time you plug in a different Arduino board into your computer, you
will need to reconfigure the serial port that is in use.
Step 5: Settings
Before you can start doing anything in the Arduino programmer, you must set the board-type
and serial port.
To set the board, go to the following:
Tools --> Boards
121 | P a g e
lOMoAR cPSD| 26885763
Select the version of board that you are using. Since I have an Arduino Uno plugged in, I
obviously selected "Arduino Uno."
To set the serial port, go to the following:
Tools --> Serial Port
Select the serial port that looks like:
/dev/tty.usbmodem [random numbers]
122 | P a g e
lOMoAR cPSD| 26885763
Arduino programs are called sketches. The Arduino programmer comes with a ton of
example sketches preloaded. This is great because even if you have never programmed
anything in your life, you can load one of these sketches and get the Arduino to do
something.
To get the LED tied to digital pin 13 to blink on and off, let's load the blink example.
The blink example can be found here:
Files --> Examples --> Basics --> Blink
The blink example basically sets pin D13 as an output and then blinks the test LED on the
Arduino board on and off every second.
Once the blink example is open, it can be installed onto the ATMEGA328 chip by pressing
the upload button, which looks like an arrow pointing to the right.
Notice that the surface mount status LED connected to pin 13 on the Arduino will start to
blink. You can change the rate of the blinking by changing the length of the delay and
pressing the upload button again.
123 | P a g e
lOMoAR cPSD| 26885763
The serial monitor allows your computer to connect serially with the Arduino. This is
important because it takes data that your Arduino is receiving from sensors and other devices
and displays it in real-time on your computer. Having this ability is invaluable to debug your
code and understand what number values the chip is actually receiving.
For instance, connect center sweep (middle pin) of a potentiometer to A0, and the outer pins,
respectively, to 5v and ground. Next upload the sketch shown below:
File --> Examples --> 1.Basics --> AnalogReadSerial
124 | P a g e
lOMoAR cPSD| 26885763
Click the button to engage the serial monitor which looks like a magnifying glass. You can
now see the numbers being read by the analog pin in the serial monitor. When you turn the
knob the numbers will increase and decrease.
The numbers will be between the range of 0 and 1023. The reason for this is that the analog
pin is converting a voltage between 0 and 5V to a discreet number.
Step 8: Digital In
The Arduino has two different types of input pins, those being analog and digital.
To begin with, lets look at the digital input pins.
Digital input pins only have two possible states, which are on or off. These two on and off
states are also referred to as:
• HIGH or LOW
• 1 or 0
• 5V or 0V.
This input is commonly used to sense the presence of voltage when a switch is opened or
closed.
Digital inputs can also be used as the basis for countless digital communication protocols. By
creating a 5V (HIGH) pulse or 0V (LOW) pulse, you can create a binary signal, the basis of
all computing. This is useful for talking to digital sensors like a PING ultrasonic sensor, or
communicating with other devices.
For a simple example of a digital input in use, connect a switch from digital pin 2 to 5V, a
10K resistor** from digital pin 2 to ground, and run the following code:
File --> Examples --> 2.Digital --> Button
**The 10K resistor is called a pull-down resistor because it connects the digital pin to ground
when the switch is not pressed. When the switch is pressed, the electrical connections in the
switch has less resistance than the resistor, and the electricity no longer connects to ground.
125 | P a g e
lOMoAR cPSD| 26885763
Instead, electricity flows between 5V and the digital pin. This is because electricity always
chooses the path of least resistance. To learn more about this, visit the Digital Pins page.
Step 9: Analog In
Aside from the digital input pins, the Arduino also boasts a number of analog input pins.
Analog input pins take an analog signal and perform a 10-bit analog-to-digital (ADC)
conversion to turn it into a number between 0 and 1023 (4.9mV steps).
This type of input is good for reading resistive sensors. These are basically sensors which
provide resistance to the circuit. They are also good for reading a varying voltage signal
between 0 and 5V. This is useful when interfacing with various types of analog circuitry.
If you followed the example in Step 7 for engaging the serial monitor, you have already tried
using an analog input pin.
A digital out pin can be set to be HIGH (5v) or LOW (0v). This allows you to turn things on
and off.
126 | P a g e
lOMoAR cPSD| 26885763
Aside from turning things on and off (and making LEDs blink), this form of output is
convenient for a number of applications.
Most notably, it allows you to communicate digitally. By turning the pin on and off rapidly,
you are creating binary states (0 and 1), which is recognized by countless other electronic
devices as a binary signal. By using this method, you can communicate using a number of
different protocols.
Digital communication is an advanced topic, but to get a general idea of what can be done,
check out the Interfacing With Hardware page.
If you followed the example in Step 6 for getting an LED to blink, you have already tried
using a digital output pin.
As mentioned earlier, the Arduino has a number of built in special functions. One of these
special functions is pulse width modulation, which is the way an Arduino is able to create an
analog-like output.
Pulse width modulation - or PWM for short - works by rapidly turning the PWM pin high
(5V) and low (0V) to simulate an analog signal. For instance, if you were to blink an LED on
and off rapidly enough (about five milliseconds each), it would seem to average the
brightness and only appear to be receiving half the power. Alternately, if it were to blink on
for 1 millisecond and then blink off for 9 millisecond, the LED would appear to be 1/10 as
bright and only be receiving 1/10 the voltage.
PWM is key for a number of applications including making sound, controlling the brightness
of lights, and controlling the speed of motors.
To try out PWM yourself, connect an LED and 220 ohm resistor to digital pin 9, in series to
ground. Run the following example code:
File --> Examples --> 3.Analog --> Fading
Step 12: Write Your Own Code
127 | P a g e
lOMoAR cPSD| 26885763
To write your own code, you will need to learn some basic programming language syntax. In
other words, you have to learn how to properly form the code for the programmer to
understand it. You can think of this kind of like understanding grammar and punctuation.
You can write an entire book without proper grammar and punctuation, but no one will be
abler to understand it, even if it is in English.
Some important things to keep in mind when writing your own code:
• An Arduino program is called a sketch.
• All code in an Arduino sketch is processed from top to bottom.
• Arduino sketches are typically broken into five parts.
1. The sketch usually starts with a header that explains what the sketch is doing, and who
wrote it.
2. Next, it usually defines global variables. Often, this is where constant names are given
to the different Arduino pins.
128 | P a g e
lOMoAR cPSD| 26885763
3. After the initial variables are set, the Arduino begins the setup routine. In the setup
function, we set initial conditions of variables when necessary, and run any
preliminary code that we only want to run once. This is where serial communication is
initiated, which is required for running the serial monitor.
4. From the setup function, we go to the loop routine. This is the main routine of the
sketch. This is not only where your main code goes, but it will be executed over and
over, so long as the sketch continues to run.
5. Below the loop routine, there is often other functions listed. These functions are user-
defined and only activated when called in the setup and loop routine. When these
functions are called, the Arduino processes all of the code in the function from top to
bottom and then goes back to the next line in the sketch where it left off when the
function was called. Functions are good because they allow you to run standard
routines - over and over - without having to write the same lines of code over and over.
You can simply call upon a function multiple times, and this will free up memory on
the chip because the function routine is only written once. It also makes code easier to
read.
• All of that said, the only two parts of the sketch which are mandatory are the Setup and
Loop routines.
• Code must be written in the Arduino Language, which is roughly based on C.
• Almost all statements written in the Arduino language must end with a ;
• Conditionals (such as if statements and for loops) do not need a ;
• Conditionals have their own rules and can be found under "Control Structures" on
the Arduino Language
• Variables are storage compartments for numbers. You can pass values into and out of
variables. Variables must be defined (stated in the code) before they can be used and need to
have a data type associated with it. To learn some of the basic data types, review
the Language Page.
Shields are expansion apdapter boards that plug in over top of the Arduino Uno and gives it
special functions.
129 | P a g e
lOMoAR cPSD| 26885763
Since the Arduino is open hardware, anyone who has the inclination is free to make an
Arduino shield for whatever task they wish to accomplish. On account of this, there are
countless number of Arduino shields out in the wild. You can find an ever-growing list
of Arduino shields in the Arduino playground. Keep in mind that there will be more shield in
existence than you will find on listed on that page (as always, Google is your friend).
As your projects get more complex, you will want to build your own circuits to interfacewith
the Arduino. While you won't learn electronics overnight, the internet is an unbelievable
resource for electronic knowledge and circuit diagrams.
To get started with electronics, visit the Basic Electronics Instructable.
130 | P a g e
lOMoAR cPSD| 26885763
A tool chain is simply a set of software tools that work together to complete a task. for
example, if we were going to hang a picture, the tool chain might include a hammer, maybe a
tape measure and some nails.
The problem is that a microcontroller (like the ATmega328 on the Uno) can only execute
simple, low-level instructions. These simple instructions include things like add variable a to
variable b or take variable b and put it in register x.
And, to complicate matters, microcontrollers only speak in binary. For those who don’t
know, binary numbers are long strings of 1s and 0s. If you need to brush up on binary
numbers, see A Bit of Fun with Binary Number Basics.
The statement here may make total sense to you if you’ve been working with Arduino for a
while. Or, if not, it may not make any sense at all. Either way, just go with me here for a
minute. This is just an illustration which does not require complete understanding of the
code.
Int Temp = analogRead(sensorPin);
If (Temp > 500)
{
//more complex instructions go here
}
131 | P a g e
lOMoAR cPSD| 26885763
A good way to think of binary numbers and digital signals is like a single pole light switch.
The light is either on or its off, there is nothing in between. Zero is off and one is on.
Going from complex instructions to simple ones the microcontroller understands requires
several layers of software that translate the high-level operations into simpler instructions.
The assembler, which come with the IDE with the compiler, then translates the assembly
language program into machine language. It then creates object files, which combine
machine language, data, and information it needs to place instructions properly in memory.
Often, the assembler creates multiple files which will eventually be put together.
This is where the linker — another part of the compiler software package — shines. The
linker will take all the independently assembled machine language programs and object files
and put them together. This produces a .hex file that the microprocessor can understand and
run.
The two figures below, though they apply to C/C++ programming in general, are a good
illustration of this process.
132 | P a g e
lOMoAR cPSD| 26885763
Another piece of software, called AVR Dude (for Downloader UploaDEr) starts when we
press the upload button. This software sends the .hex file to the ATMega328 on the Arduino
board. On the chip resides the bootloader. This bootloader was put there on purpose by the
folks at Arduino and works with AVR Dude to get the .hex into the flash memory on the
chip.
All of this happens very quickly and seamlessly behind the scenes of the Arduino IDE.
133 | P a g e
lOMoAR cPSD| 26885763
Programming in C vs Arduino
A few words are in order on this subject due to the enormous popularity of Arduino boards
and the C/C++ language in general.
Others use platforms or ecosystems such as the Arduino almost (or entirely) exclusively.
Finally, some of you may use both depending on your goals and background.
For hobbyists, the number of people who use platforms like Arduino has exceeded those who
only use naked microcontrollers.
When we talk about programming the Arduino, we’ll talk about the C/C++ languages. The
truth is, sketches are written in a language similar to C, though a sketch itself is not
completely compatible with C.
In Arduino, the main() function is hidden from view and added for you when you compile or
“verify” your sketch. Also, there are two functions which the Arduino ecosystem absolutely
requires: setup() and loop(). The only function C requires is main().
C also lacks built-in functions for using microcontroller I/O such as digitalWrite().
To make learning simple, the Arduino IDE designers hide a lot of detail and functionality
behind layers of abstraction, many of which come in the form of libraries. Note that the C
programming language also uses libraries. The linker adds them during the linking process.
Sketch: The first new terminology is the Arduino program called “sketch”.
3.7.1. Structure
Arduino programs can be divided in three main parts: Structure, Values (variables and
constants), and Functions. 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 consist of two main functions:
Setup( ) function
Loop( ) function
134 | P a g e
lOMoAR cPSD| 26885763
PURPOSE: After creating a setup() function, which initializes and sets the initial
values, the loop() function does precisely what its name suggests, and loops consecutively,
allowing your program to change and respond. Use it to actively control the Arduino
board.
2. Arduino – DataTypes
Data types in C refers to an extensive system used for declaring variables or
functions of different types. The type of a variable determines how much space it occupies
in the storage and how the bit pattern stored is interpreted.
The following table provides all the data types that you will use during Arduino
programming.
Void, Boolean , char, Unsigned, Unsigned, char , byte, int, Unsigned, int, word
String. Array, long, long, short , float , double , array, char, String, object
135 | P a g e
lOMoAR cPSD| 26885763
void
The void keyword is used only in function declarations. It indicates that the
function is expected to return no information to the function from which it was
called.
Boolean
A Boolean holds one of two values, true or false. Each Boolean variable
occupies one byte of memory.
Char
A data type that takes up one byte of memory that stores a character value.
Character literals are written in single quotes like this: 'A' and for multiple
characters, strings use double quotes: "ABC".
However, characters are stored as numbers. You can see the specific encoding in the
ASCII
chart. This means that it is possible to do arithmetic operations on characters, in
which the ASCII value of the character is used. For example, 'A' + 1 has the
value 66, since the ASCII value of the capital letter A is 65.
136 | P a g e
lOMoAR cPSD| 26885763
byte
Example
Unsigned Char chr_y = 121 ; // declaration of variable with type Unsigned char and
initialize it with character y
137 | P a g e
lOMoAR cPSD| 26885763
Int
Example
byte m = 25 ;//declaration of variable with type byte and initialize it with
25
Integers are the primary data-type for number storage. int stores a 16-bit (2-byte) value.
This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of
(2^15) - 1).
The int size varies from board to board. On the Arduino Due, for example, an int stores a
32-bit (4-byte) value. This yields a range of -2,147,483,648 to 2,147,483,647 (minimum
value of -2^31 and a maximum value of (2^31) - 1).
Example
int counter = 32 ;// declaration of variable with type int and initialize it with
32
Unsigned int
Unsigned ints (unsigned integers) are the same as int in the way that they store a 2 byte
value. Instead of storing negative numbers, however, they only store positive values, yielding
a useful range of 0 to 65,535 (2^16) - 1). The Due stores a 4 byte (32-bit) value, ranging from
0 to 4,294,967,295 (2^32 - 1).
Example
Unsigned int counter= 60 ; // declaration of variable with type unsigned int and
initialize it with 60
Word
On the Uno and other ATMEGA based boards, a word stores a 16-bit unsigned number. On
the Due and Zero, it stores a 32-bit unsigned number.
Example
word w = 1000 ;//declaration of variable with type word and initialize it with
1000
Long
Long variables are extended size variables for number storage, and store 32 bits (4 bytes),
from 2,147,483,648 to 2,147,483,647.
138 | P a g e
lOMoAR cPSD| 26885763
Example
Long velocity= 102346 ;//declaration of variable with type Long and initialize it with
102346
unsigned long
Unsigned long variables are extended size variables for number storage and store 32 bits (4
bytes). Unlike standard longs, unsigned longs will not store negative numbers, making
their range from 0 to 4,294,967,295 (2^32 - 1).
Unsigned Long velocity = 101006 ;// declaration of variable with type Unsigned
Long and initialize it with 101006
short
A short is a 16-bit data-type. On all Arduinos (ATMega and ARM based), a short stores a
16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and
a maximum value of (2^15) - 1).
Float
short val= 13 ;//declaration of variable with type short and initialize it with
13
Data type for floating-point number is a number that has a decimal point. Floating-point
numbers are often used to approximate the analog and continuous values because they have
greater resolution than integers.
float num = 1.352;//declaration of variable with type float and initialize it with 1.352
double
On the Uno and other ATMEGA based boards, Double precision floating-point
number occupies four bytes. That is, the double implementation is exactly the same
as the float, with no gain in precision. On the Arduino Due, doubles have 8-byte (64 bit)
precision.
double num = 45.352 ;// declaration of variable with type double and initialize it
with 45.352
139 | P a g e
lOMoAR cPSD| 26885763
Before we start explaining the variable types, a very important subject we need to make sure,
you fully understand is called the variable scope.
Local Variables
Variables that are declared inside a function or block are local variables. They can be used
only by the statements that are inside that function or block of code. Local variables are not
known to function outside their own. Following is the example using local variables:
Global Variables
Global variables are defined outside of all the functions, usually at the top of the
program. The global variables will hold their value throughout the life-time of your
program.
A global variable can be accessed by any function. That is, a global variable is available
for use throughout your entire program after its declaration.
140 | P a g e
lOMoAR cPSD| 26885763
Arithmetic Operators
Assume variable A holds 10 and variable B holds 20 then −
Operator Operator Description Example
name simple
141 | P a g e
lOMoAR cPSD| 26885763
subtraction - Subtracts second operand from the first A - B will give -10
Comparison Operators
Assume variable A holds 10 and variable B holds 20 then −
Boolean Operators
Assume variable A holds 10 and variable B holds 20 then −
142 | P a g e
lOMoAR cPSD| 26885763
Bitwise Operators
Assume variable A holds 60 and variable B holds 13 then −
Operator Operator Description Example
name simple
Binary AND Operator copies a bit to the result (A & B) will give 12
and &
if it exists in both operands. which is 0000 1100
Compound Operators
Assume variable A holds 10 and variable B holds 20 then −
143 | P a g e
lOMoAR cPSD| 26885763
Arduino IDE
The Arduino IDE is very simple and easy to use.
Let’s see how to use it with the help of Blink example that comes in the Built-In examples
with the IDE.
1. Open the Arduino IDE from the folder you installed/unzipped it in.
144 | P a g e
lOMoAR cPSD| 26885763
2. In the File tab, go to the Examples option. Here you will find a list of all the Built-In
examples that come along with the IDE. You will also see Examples For Any Board in below
the Built-In examples.
Here, we will see the Blink example which blinks the LED on the Arduino board.
3. Once you click on Blink, a new window will open with the sketch (Arduino refers to
codes written in its IDE as sketch) for Blink.
4. Before burning this code into the Arduino board, we need to configure the IDE for the
board we need to burn this sketch into. We also need to select the appropriate communication
port and the method used for burning the code.
5. Go to the Tools tab and find the Board option in it. It will have a list of all the Arduino
Boards in it. Select the board you are using from that list. Here, we have used
Arduino/Genuino Uno Board.
145 | P a g e
lOMoAR cPSD| 26885763
Arduino and Genuino are one and the same thing. Outside the USA, the Arduino boards are
called Genuino.
6. Now we need to select the appropriate communication port over which the
computer/laptop will communicate with the Arduino board. Under the Tools tab, you will
find the Port option. Select the port you have connected the Arduino board to from the Ports
available in this list.
146 | P a g e
lOMoAR cPSD| 26885763
7. Now that we have selected the board and the communication port, we need to select the
appropriate programmer.
We will be using the AVR ISP mk2 programmer.
147 | P a g e
lOMoAR cPSD| 26885763
8. On the Arduino IDE, you will find 6 unique buttons. These are described below.
• This is used to open the serial monitor that comes with the Arduino IDE.
Note : You can use any other serial terminal program if you want instead of the Arduino
serial monitor. The serial monitor that comes with Arduino IDE can open only one serial port
for communication. If you need to observe multiple ports (multiple Arduino boards
148 | P a g e
lOMoAR cPSD| 26885763
connected to the same computer/laptop), you need to use other programs like Putty,
RealTerm, TeraTerm, etc.
9. Now that we have selected the appropriate board, communication port, and the
programmer, we need to upload the Blink sketch on to the board.
We can either verify the sketch before the upload process or skip the verification process.
The IDE does the part of verifying the sketch before uploading as a part of the upload
process.
10. Since this is a built-in example sketch, we will not get any warnings or errors upon
verifying. If there are any warnings or errors, they are displayed by the IDE in the black
coloured area below the area for writing code. This area is shown in the image in the next
point, highlighted in red.
11. Now upload the sketch onto the board. When the upload process is done, you will get a
done uploading message. You should be able to see the LED on your Arduino board blinking
at 1 second intervals.
149 | P a g e
lOMoAR cPSD| 26885763
12. This process needs to be followed for all the sketches that are built-in or created by the
user.
Understanding how the Arduino IDE sets up its file directory system can spare you some
confusion when it comes to saving, organizing and opening your Arduino sketches (or
sketches you have downloaded from the internet).
The Arduino Sketchbook Folder And Changing The Default Save Location
The default location where Arduino sketches you write will be saved is called the
Sketchbook.
The Sketchbook is simply a folder on your computer like any other. It acts as a handy
repository for sketches and is also where add-on code libraries get saved.
You can see the sketches in the Sketchbook folder by going to File > Sketchbook.
The default name of the Sketchbook folder is “Arduino” and the default location of the
Sketchbook folder is in the “My Documents” folder (or just “Documents” for Mac users).
If your Sketchbook does not appear to be in this default location, you can see exactly where
it is by opening the Arduino IDE and going to Arduino > Preferences.
150 | P a g e
lOMoAR cPSD| 26885763
The default file path for your sketches is listed at the top of Arduino Preferences window.
Mine is:
/Users/michaelJames/Documents/Arduino
When I save a file in the Arduino IDE, this “Arduino” folder is the default location where the
sketch will be saved, unless I choose to change that location by selecting a different folder on
my computer’s directory.
If you want to change this default location, you click the Browse button next to the file
directory path and choose a different place. Pretty simple.
151 | P a g e
lOMoAR cPSD| 26885763
*/
There's another style for short, single-line comments. These start with
//
and continue to the end of the line. For example, in the line:
1int ledPin = 13; // LED connected to digital pin 13 the message "LED connected
to digital pin 13" is a comment.
Variables
A variable is a place for storing a piece of data. It has a name, a type, and a value. For
example, the line from the Blink sketch above declares a variable with the name ledPin, the
type int, and an initial value of 13. It's being used to indicate which Arduino pin the LED is
connected to. Every time the name ledPin appears in the code, its value will be retrieved. In
this case, the person writing the program could have chosen not to bother creating
the ledPin variable and instead have simply written 13 everywhere they needed to specify a
pin number. The advantage of using a variable is that it's easier to move the LED to a
different pin: you only need to edit the one line that assigns the initial value to the variable.
Often, however, the value of a variable will change while the sketch runs. For example,
you could store the value read from an input into a variable.
Functions
A function (otherwise known as a procedure or sub-routine) is a named piece of code that
can be used from elsewhere in a sketch. For example, here's the definition of the
setup()
152 | P a g e
lOMoAR cPSD| 26885763
{
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
The first line provides information about the function, like its name, "setup". The text
before and after the name specify its return type and parameters: these will be explained
later. The code between the { and } is called the body of the function: what the function
does.
You can call a function that's already been defined (either in your sketch or as part of
the Arduino language). For example, the line pinMode(ledPin, OUTPUT); calls
the pinMode() function, passing it two parameters: ledPin and OUTPUT. These parameters
are used by the
pinMode() function to decide which pin and mode to set.
The digitalWrite()
functions outputs a value on a pin. For example, the line:
digitalWrite(ledPin, HIGH);
set the ledPin (pin 13) to HIGH, or 5 volts. Writing a LOW to pin connects it to ground, or 0
volts.
The delay() causes the Arduino to wait for the specified number of milliseconds before
continuing on to the next line. There are 1000 milliseconds in a second, so the line:
delay(1000);
creates a delay of one second.
153 | P a g e
lOMoAR cPSD| 26885763
Let me say that one more time because it is really important to understand. Every Arduino
file must be inside a folder that has the same name as the file When I write a new sketch and
save it, the Arduino IDE automatically creates a new folder that has the exact same name as
the sketch itself. The Arduino file (which has the extension .ino) is placed inside this
enclosing folder, which is called a sketch folder.
If you go into the Sketchbook folder and change the name of the enclosing folder, it will
create some issues. The first issue is that when you go to File > Sketchbook, the sketch will
no longer show up! If you want to open this sketch you need to go to the .ino file in your
directory and open it from there.
If you open a .ino file that is not inside an enclosing sketch folder of the exact same name,
then you will get a pop-up from the Arduino IDE that says:
“The file “sketch_name.ino” needs to be inside a sketch folder named “sketch_name”. Create
this folder, move the file, and continue?”
154 | P a g e
lOMoAR cPSD| 26885763
If you choose Cancel, the sketch will not open. If you choose OK, then a folder gets created
(it will have the same name as the sketch) and the .ino file is placed inside it.
This sketch folder will be created in whatever directory the .ino file was that you tried to
open. For example, if you tried to open a .ino file that was in your My Downloads folder,
then the enclosing sketch folder also will be created inside the My Downloads folder.
Once you get a handle on some of these intricacies of the Arduino IDE file system, it can
really help to clear things up.
Arduino Shields
155 | P a g e
lOMoAR cPSD| 26885763
There is a polarity protection diode connecting between the positive of the barrel jack to the
VIN pin, rated at 1 Ampere.
The power source you use determines the power you have available for your circuit. For
instance, powering the circuit using the USB limits you to 500mA. Take into consideration
that this is also used for powering the MCU, its peripherals, the on-board regulators, and the
156 | P a g e
lOMoAR cPSD| 26885763
components connected to it. When powering your circuit through the barrel jack or VIN, the
maximum capacity available is determined by the 5 and 3.3 volts regulators on-board the
Arduino.
• 5v and 3v3
They provide regulated 5 and 3.3v to power external components according to manufacturer
specifications.
• GND
In the Arduino Uno pinout, you can find 5 GND pins, which are all interconnected.
The GND pins are used to close the electrical circuit and provide a common logic reference
level throughout your circuit. Always make sure that all GNDs (of the Arduino, peripherals
and components) are connected to one another and have a common ground.
157 | P a g e
lOMoAR cPSD| 26885763
device’s ADC, gets converted into digital data, which is transmitted to the receiving side
over the internet.
On the Arduino, When the digital pins are configured as output, they are set to 0 or 5 volts.
When the digital pins are configured as input, the voltage is supplied from an external
device. This voltage can vary between 0-5 volts which is converted into digital representation
(0 or 1). To determine this, there are 2 thresholds:
When connecting a component to a digital pin, make sure that the logic levels match. If the
voltage is in between the thresholds, the returning value will be undefined.
What is PWM?
In general, Pulse Width Modulation (PWM) is a modulation technique used to encode
a message into a pulsing signal. A PWM is comprised of two key
components: frequency and duty cycle. The PWM frequency dictates how long it takes to
complete a single cycle (period) and how quickly the signal fluctuates from high to low. The
duty cycle determines how long a signal stays high out of the total period. Duty cycle is
represented in percentage.
In Arduino, the PWM enabled pins produce a constant frequency of ~ 500Hz, while the duty
cycle changes according to the parameters set by the user. See the following illustration:
158 | P a g e
lOMoAR cPSD| 26885763
PWM signals are used for speed control of DC motors, dimming LEDs and more.
Communication Protocols
Serial (TTL) - Digital pins 0 and 1 are the serial pins of the Arduino Uno.
They are used by the onboard USB module.
159 | P a g e
lOMoAR cPSD| 26885763
USB. Arduino supports serial communication through digital pins with the SoftwareSerial
Library as well. This allows the user to connect multiple serial-enabled devices and leave the
main serial port available for the USB.
Software serial and hardware serial - Most microcontrollers have hardware designed to
communicate with other serial devices. Software serial ports use a pin-change interrupt
system to communicate. There is a built-in library for Software Serial communication.
Software serial is used by the processor to simulate extra serial ports. The only drawback
with software serial is that it requires more processing and cannot support the same high
speeds as hardware serial.
SPI - SS/SCK/MISO/MOSI pins are the dedicated pins for SPI communication. They can be
found on digital pins 10-13 of the Arduino Uno and on the ICSP headers.
What is SPI?
Serial Peripheral Interface (SPI) is a serial data protocol used by microcontrollers to
communicate with one or more external devices in a bus like connection. The SPI can also be
used to connect 2 microcontrollers. On the SPI bus, there is always one device that is denoted
as a Master device and all the rest as Slaves. In most cases, the microcontroller is the Master
device. The SS (Slave Select) pin determines which device the Master is currently
communicating with.
SPI enabled devices always have the following pins:
• MISO (Master In Slave Out) - A line for sending data to the Master device
• MOSI (Master Out Slave In) - The Master line for sending data to peripheral devices
• SCK (Serial Clock) - A clock signal generated by the Master device to synchronize
data transmission.
I2C - SCL/SDA pins are the dedicated pins for I2C communication. On the Arduino Uno
they are found on Analog pins A4 and A5.
What is I2C?
I2C is a communication protocol commonly referred to as the “I2C bus”. The I2C protocol
was designed to enable communication between components on a single circuit board. With
I2C there are 2 wires referred to as SCL and SDA.
• SCL is the clock line which is designed to synchronize data transfers.
• SDA is the line used to transmit data.
Each device on the I2C bus has a unique address, up to 255 devices can be connected on the
same bus.
160 | P a g e
lOMoAR cPSD| 26885763
Interrupt - INT0 and INT1. Arduino Uno has two external interrupt pins.
External Interrupt - An external interrupt is a system interrupt that occurs when outside
interference is present. Interference can come from the user or other hardware devices in the
network. Common uses for these interrupts in Arduino are reading the frequency a square
wave generated by encoders or waking up the processor upon an external event.
Arduino has two forms of interrupt:
• External
• Pin Change
There are two external interrupt pins on the ATmega168/328 called INT0 and INT1. both
INT0 and INT1 are mapped to pins 2 and 3. In contrast, Pin Change interrupts can be
activated on any of the pins.
161 | P a g e
lOMoAR cPSD| 26885763
The transistors in the output pin have non-negligible on resistance, so aren’t suitable for
driving large loads. When talking about this resistance in relation to an output pin, we call
it the output resistance of the pin—in other words, the resistance “seen” by a device
connected to the pin. Since this resistance might depend on the state of the pin (HIGH or
LOW), it actually has two output resistances. You’ll measure both in prelab 2b.
Input pins
An input pin reads the voltage on the pin as if it were a voltmeter, and returns either HIGH
(1) in software if the voltage is close to VDD , or LOW (0) if it is close to 0 V. An input pin
can be read using the digitalRead() function.
The value returned by digitalRead() is unpredictable (i.e., could be either HIGH or LOW)
when the input voltage is not close to either VDD or 0 V. The precise meaning of
“close” varies between microcontrollers, but for the Adafruit Metro Mini1 in our circuit,
the input pin voltage needs to be at least 0.6VDD to qualify as HIGH, and at most 0.3VDD
to qualify as LOW.
The pins on the Arduino board can be configured as either inputs or outputs. We will
explain the functioning of the pins in those modes. It is important to note that a majority of
Arduino analog pins, may be configured, and used, in exactly the same manner as digital
pins.
162 | P a g e
lOMoAR cPSD| 26885763
Arduino pins are by default configured as inputs, so they do not need to be explicitly
declared as inputs with pinMode() when you are using them as inputs. Pins configured this
way are said to be in a high-impedance state. Input pins make extremely small demands on
the circuit that they are sampling, equivalent to a series resistor of 100 megaohm in front of
the pin.
This means that it takes very little current to switch the input pin from one state to another.
This makes the pins useful for such tasks as implementing a capacitive touch sensor or
reading an LED as a photodiode.
Pins configured as pinMode(pin, INPUT) with nothing connected to them, or with wires
connected to them that are not connected to other circuits, report seemingly random changes
in pin state, picking up electrical noise from the environment, or capacitively coupling the
state of a nearby pin.
Pull-up Resistors
Pull-up resistors are often useful to steer an input pin to a known state if no input is present.
This can be done by adding a pull-up resistor (to +5V), or a pull-down resistor (resistor to
ground) on the input. A 10K resistor is a good value for a pull-up or pull-down resistor.
There are 20,000 pull-up resistors built into the Atmega chip that can be accessed from
software. These built-in pull-up resistors are accessed by setting the pinMode() as
INPUT_PULLUP. This effectively inverts the behavior of the INPUT mode, where HIGH
means the sensor is OFF and LOW means the sensor is ON. The value of this pull-up
depends on the microcontroller used. On most AVR-based boards, the value is guaranteed to
be between 20kΩ and 50kΩ. On the Arduino Due, it is between 50kΩ and 150kΩ. For the
exact value, consult the datasheet of the microcontroller on your board.
When connecting a sensor to a pin configured with INPUT_PULLUP, the other end should
be connected to the ground. In case of a simple switch, this causes the pin to read HIGH
when the switch is open and LOW when the switch is pressed. The pull-up resistors provide
enough current to light an LED dimly connected to a pin configured as an input. If LEDs in a
project seem to be working, but very dimly, this is likely what is going on.
Same registers (internal chip memory locations) that control whether a pin is HIGH or LOW
control the pull-up resistors. Consequently, a pin that is configured to have pull-up resistors
turned on when the pin is in INPUTmode, will have the pin configured as HIGH if the pin is
then switched to an OUTPUT mode with pinMode(). This works in the other direction as
163 | P a g e
lOMoAR cPSD| 26885763
well, and an output pin that is left in a HIGH state will have the pull-up resistor set if
switched to an input with pinMode().
Example
Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state. This
means that they can provide a substantial amount of current to other circuits. Atmega pins
can source (provide positive current) or sink (provide negative current) up to 40 mA
(milliamps) of current to other devices/circuits. This is enough current to brightly light up an
LED (do not forget the series resistor), or run many sensors but not enough current to run
relays, solenoids, or motors.
Attempting to run high current devices from the output pins, can damage or destroy the
output transistors in the pin, or damage the entire Atmega chip. Often, this results in a "dead"
pin in the microcontroller but the remaining chips still function adequately. For this reason, it
is a good idea to connect the OUTPUT pins to other devices through 470Ω or 1k resistors,
unless maximum current drawn from the pins is required for a particular application.
pinMode() Function
The pinMode() function is used to configure a specific pin to behave either as an input or an
output. It is possible to enable the internal pull-up resistors with the mode INPUT_PULLUP.
Additionally, the INPUT mode explicitly disables the internal pull-ups.
Void setup ()
{
pinMode (pin , mode);
}
• pin − the number of the pin whose mode you wish to set
• mode − INPUT, OUTPUT, or INPUT_PULLUP.
Example
164 | P a g e
lOMoAR cPSD| 26885763
void setup () {
pinMode(button , INPUT_PULLUP);
// set the digital pin as input with pull-up resistor
pinMode(button , OUTPUT); // set the digital pin as output
}
void setup () {
If (digitalRead(button ) == LOW) // if button pressed {
digitalWrite(LED,HIGH); // turn on led
delay(500); // delay for 500 ms
digitalWrite(LED,LOW); // turn off led
delay(500); // delay for 500 ms
}
}
digitalWrite() Function
The digitalWrite() function is used to write a HIGH or a LOW value to a digital pin. If the
pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the
corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW. If the
pin is configured as an INPUT, digitalWrite() will enable (HIGH) or disable (LOW) the
internal pullup on the input pin. It is recommended to set the pinMode() to INPUT_PULLUP
to enable the internal pull-up resistor.
If you do not set the pinMode() to OUTPUT, and connect an LED to a pin, when calling
digitalWrite(HIGH), the LED may appear dim. Without explicitly setting pinMode(),
digitalWrite() will have enabled the internal pull-up resistor, which acts like a large current-
limiting resistor.
Void loop()
{
digitalWrite (pin ,value);
}
• pin − the number of the pin whose mode you wish to set
• value − HIGH, or LOW.
Example
165 | P a g e
lOMoAR cPSD| 26885763
void setup ()
{
pinMode(LED, OUTPUT); // set the digital pin as output
}
void setup ()
{
digitalWrite(LED,HIGH); // turn on led
delay(500); // delay for 500 ms
digitalWrite(LED,LOW); // turn off led
delay(500); // delay for 500 ms
}
analogRead( ) function
Arduino is able to detect whether there is a voltage applied to one of its pins and report it
through the digitalRead() function. There is a difference between an on/off sensor (which
detects the presence of an object) and an analog sensor, whose value continuously changes.
In order to read this type of sensor, we need a different type of pin.
In the lower-right part of the Arduino board, you will see six pins marked “Analog In”.
These special pins not only tell whether there is a voltage applied to them, but also its value.
By using the analogRead() function, we can read the voltage applied to one of the pins.
This function returns a number between 0 and 1023, which represents voltages between 0
and 5 volts. For example, if there is a voltage of 2.5 V applied to pin number 0,
analogRead(0) returns 512.
analogRead(pin);
• pin − the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7
on the Mini and Nano, 0 to 15 on the Mega)
Example
166 | P a g e
lOMoAR cPSD| 26885763
void setup()
{
Serial.begin(9600); // setup serial
}
void loop()
{
val = analogRead(analogPin); // read the input pin
Serial.println(val); // debug value
}
Shield is defined as the hardware device that can be mounted over the board to increase the
capabilities of the projects. It also makes our work easy. For example, Ethernet shields are
used to connect the Arduino board to the Internet.
The pin position of the shields is similar to the Arduino boards. We can also connect the
modules and sensors to the shields with the help of the connection cable.
Arduino motor shields help us to control the motors with the Arduino board.
Types of Shields
The popular Arduino shields are listed below:
o Ethernet shield
o Xbee Shield
o Proto shield
o Relay shield
o Motor shield
o LCD shield
167 | P a g e
lOMoAR cPSD| 26885763
o Bluetooth shield
o Capacitive Touchpad Shield
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 We can communicate wirelessly with the Arduino board by using the Xbee Shield
with Zigbee.
o It reduces the hassle of the cable, which makes Xbee a wireless communication
model.
o The Xbee wireless module allows us to communicate outdoor upto 300 feet and
indoor upto 100 feet.
o The Xbee shield is shown below:
168 | P a g e
lOMoAR cPSD| 26885763
Proto shield
o Proto shields are designed for custom circuits.
o We can solder electronic circuits directly on the shield.
o The shield consists of two LED pads, two power lines, and SPI signal pads.
o 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
o 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 situation. It provides a
solution for controlling the devices carrying high current and voltage.
o The shield consists of four relays and four LED indicators.
169 | P a g e
lOMoAR cPSD| 26885763
o It also provides NO/NC interfaces and a shield form factor for the simple connection
to the Arduino board.
o The LED indicators depicts the ON/OFF condition of each relay.
o The relay used in the structure is of high quality.
o The NO (Normally Open), NC (Normally Closed), and COM pins are present on each
relay.
o The relay shield is shown below:
Motor shield
o The motor shield helps us to control the motor using the Arduino board.
o 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.
o 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 The operating voltage is from 5V to 12V.
170 | P a g e
lOMoAR cPSD| 26885763
o The applications of the motor shield are intelligent vehicles, micro-robots, etc.
LCD shield
o The keypad of LCD (Liquid Crystal Display) shield includes five buttons called as
up, down, left, right, and select.
o There are 6 push buttons present on the shield that can be used as a custom menu
control panel.
o It consists of the 1602 white characters, which are displayed on the blue backlight
LCD.
o The LED present on the board indicates the power ON.
o The five keys present on the board helps us to make the selection on menus and from
board to our project.
o
The LCD shield is shown below:
o The LCD shield is popularly designed for the classic boards such as Duemilanove,
UNO, etc.
Bluetooth shield
171 | P a g e
lOMoAR cPSD| 26885763
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.
o The communication distance of the Bluetooth shield is upto 10m at home without any
obstacle in between.
o The board can work with the logic level of 3.3V or 5V.
o We can establish a connection to the Arduino project by touching the shield.
172 | P a g e
lOMoAR cPSD| 26885763
The Internet of Things is a major contributing factor of the new Data Economy. The value of
an IoT system goes beyond the original intended use case, for instance in automation. This is
because further value lies in the intelligence that an IoT system creates. Sensors are the
source of IoT data. Furthermore, sensors and actuators in IoT can work together to enable
automation at industrial scale. Finally, analysis of the data that these sensors and actuators
produce can provide valuable business insights over time.
Sensors
A better term for a sensor is a transducer. A transducer is any physical device that converts
one form of energy into another. So, in the case of a sensor, the transducer converts some
physical phenomenon into an electrical impulse that determines the reading. A microphone is
a sensor that takes vibrational energy (sound waves), and converts it to electrical energy in a
useful way for other components in the system to correlate back to the original sound.
Actuators
Another type of transducer that you will encounter in many IoT systems is an actuator. In
simple terms, an actuator operates in the reverse direction of a sensor. It takes an electrical
173 | P a g e
lOMoAR cPSD| 26885763
input and turns it into physical action. For instance, an electric motor, a hydraulic system,
and a pneumatic system are all different types of actuators.
Controller
In a typical IoT system, a sensor may collect information and route to a control center. There,
previously defined logic dictates the decision. As a result, a corresponding command controls
an actuator in response to that sensed input. Thus, sensors and actuators in IoT work together
from opposite ends. Later, we will discuss where the control center resides in the greater IoT
system.
174 | P a g e
lOMoAR cPSD| 26885763
7. Power Considerations:
Ensure that your power supply can handle the power requirements of your sensors and
actuators. Some components may require an external power supply.
175 | P a g e
lOMoAR cPSD| 26885763
UNIT IV
• Bluetooth
• WiFi
• ZigBee
• GPS
• GSM modules
• Architecture
• Programming
• Interfacing
176 | P a g e
lOMoAR cPSD| 26885763
Publish-Subscribe Model(Pub-Sub)
177 | P a g e
lOMoAR cPSD| 26885763
In this model, you will find three main entities:- Publisher, Broker and Consumer Let us see
the roles of each of these 3 entities. Publishers, send the data to the topics that are managed
by the broker. They are the source of data. The Man in the Middle, the Broker, has the
responsibility to accept the data sent by the publisher and deliver that data to the
consumers.What is the task of the Consumers? Consumers will subscribe to the broker-
managed topics. Once the data is published on a topic, the broker sends this message to all
consumers who have subscribed to the specific topic. It works a bit like YouTube. When you
subscribe to a channel and tap the Bell icon, you'll get notifications if the YouTube channel
posts a video.
Push-Pull Model
178 | P a g e
lOMoAR cPSD| 26885763
rate at which the producers push data and the rate at which the consumer pull data. So they
work as a buffer and flow control mechanisms whenever there is any mismatch in the push-
pull rates.
179 | P a g e
lOMoAR cPSD| 26885763
Representational state transfer (REST) is a set of architectural principles by which you can
design Web services the Web APIs that focus on the system's resources and how resource
states are addressed and transferred.
Client-server
Let me explain it to you by giving a suitable example. The client should not be concerned
with the storage of data which is a concern of the server, similarly, the server should not be
concerned about the user interface, which is the concern of the client. Separation makes it
possible for the client and server to be developed and updated independently.
180 | P a g e
lOMoAR cPSD| 26885763
Stateless
The status of the session remains entirely on the client.
Cache-able
This property defines whether the response to any request can be cached or not. If a response
can be cached, then a client cache is granted the right to reuse that response data for
subsequent matching requests.
Layered system
A layered system defines the boundaries of the components within each specific layer. For
example, A client is unable to tell whether it is connected to the end server or an intermediate
node. As simple as that!
Uniform interface
This specifies that the technique of communication between a client and a server must be
uniform throughout the communication period.
Code on Demand
Servers may provide executable code or scripts for execution by clients in their context.
Websocket based APIs
Websocket APIs enable bi-directional and duplex communication between customers and
servers.
Unlike REST, There is no need to set up a connection every now and then to send messages
between a client and a server.
It works on the principle of the exclusive pair model. Can you recall it? Yes. Once a
connection is set up, there is a constant exchange of messages between the client and the
181 | P a g e
lOMoAR cPSD| 26885763
server. All we need is to establish a dedicated connection to start the process. the
communication goes on unless the connection is terminated.
It is a stateful type.
Due to onetime dedicated connection setup, there is less overhead, lower traffic and less
latency and high throughput.
4.2.1. Bluetooth
An important short-range IoT communications Protocols / Technology. Bluetooth, which has
become very important in computing and many consumer product markets. It is expected to
be key for wearable products in particular, again connecting to the IoT albeit probably via a
smartphone in many cases.
The latest version of ZigBee is the recently launched 3.0, which is essentially the unification
of the various ZigBee wireless standards into a single standard.
182 | P a g e
lOMoAR cPSD| 26885763
4.2.3. Z-Wave
Z-Wave is a low-power RF communications IoT technology that primarily design for home
automation for products such as lamp controllers and sensors among many other devices.
A Z-Wave uses a simpler protocol than some others, which can enable faster and simpler
development, but the only maker of chips is Sigma Designs compared to multiple sources for
other wireless technologies such as ZigBee and others.
WiFi connectivity is one of the most popular IoT communication protocol, often an obvious
choice for many developers, especially given the availability of WiFi within the home
environment within LANs.
183 | P a g e
lOMoAR cPSD| 26885763
There is a wide existing infrastructure as well as offering fast data transfer and the ability to
handle high quantities of data.
Currently, the most common WiFi standard used in homes and many businesses is 802.11n,
which offers range of hundreds of megabit per second, which is fine for file transfers but may
be too power-consuming for many IoT applications.
4.2.4. Cellular
Any IoT application that requires operation over longer distances can take advantage of
GSM/3G/4G cellular communication capabilities. While cellular is clearly capable of
sending high quantities of data, especially for 4G, the cost and also power consumption will
be too high for many applications.
But it can be ideal for sensor-based low-bandwidth-data projects that will send very low
amounts of data over the Internet.
184 | P a g e
lOMoAR cPSD| 26885763
4.3. Bluetooth
To understand the architecture of Bluetooth first lets understand what actually Bluetooth is.
Bluetooth is a radio-wave technology that is mainly designed to enable wireless
communications over short distances. The frequency of these waves ranges between 2.400
and 2.485 GHz, which can extend a maximum of 164 feet between two devices. Every
185 | P a g e
lOMoAR cPSD| 26885763
Bluetooth device has a Transmitter and a Receiver. The power of the device transmitter
governs the range over which a Bluetooth device can operate in other words transmitter
decides the range of communication.
These days Bluetooth is the common technology present in most of the products. It is used in
many fields such as the health sector, sports and fitness, electronics, home automation, and
security, etc.
->Wireless communication between a smartphone and a smart lock for unlocking doors.
–> For low bandwidth applications where USB higher bandwidth is not required and cable-
free connection desired.
–> For example, Smart watches, Smart Lights.
How does it work?
186 | P a g e
lOMoAR cPSD| 26885763
Maximum 7 active slaves can be present in multiple piconets, in other words, only 8
maximum devices including the master can communicate at any one time in a piconet.
4.3.1.2. Scatternet
Its a Combination of multiple piconets.
Here Master of one piconet can be a slave in another piconet. This node can receive a
message from a master in one piconet and deliver the message to its slave into the other
piconet.
187 | P a g e
lOMoAR cPSD| 26885763
Therefore, this type of node is referred to as a bridge node. Above all, a station cannot be
master in two piconets.Read More
188 | P a g e
lOMoAR cPSD| 26885763
The below diagram shows a complete Bluetooth protocol stack. It shows the relationship
between the protocols that use the services of other protocols when there is a payload to be
transferred in the air. Anyhow, the protocols have many other relationships between the other
protocols – for example, some protocols (L2CAP, TCS Binary) use the LMP to control the
link manager.
The complete protocol stack architecture of Bluetooth is made up of both Bluetooth specific
protocols like object exchange protocols (OBEX) and user datagram protocol (UDP).
The main principle is to minimize the reuse of current protocols for different purposes at
higher layers as if re-inventing circle once again. The protocol re-use is helpful for the legacy
applications to work with the Bluetooth technology to measure the smooth operations and
interoperability of applications. Hence, many applications are being developed to take
immediate advantage of the software and hardware.
189 | P a g e
lOMoAR cPSD| 26885763
Logical Link Control It is also known as the heart of the Bluetooth protocol stack. It
and Adaptation allows the communication between the upper and lower layers of the
Protocol Bluetooth protocol stack.
Baseband Link layer In short, it performs the connection establishment within a piconet.
WAP It is short for Wireless Access Protocol. It is used for internet access.
Application layer In short , it enables the user to interact with the application.
190 | P a g e
lOMoAR cPSD| 26885763
Bluetooth Security
Firstly, the security of any wireless technology is very important. With hackers gaining
access to an ever-increasing number of systems, as a result,Bluetooth security is increasingly
important.
Bluetooth security must also address more specific Bluetooth related attacks that target
known vulnerabilities in Bluetooth implementations and specifications. In other words, these
may include attacks against improperly secured Bluetooth implementations which can
provide attackers with unauthorized access.
Many users may not believe there is an issue with Bluetooth security, but hackers may be
able to gain access to information from phone lists to more sensitive information that others
may hold on Bluetooth enabled phones and other devices.
191 | P a g e
lOMoAR cPSD| 26885763
• Bluesnarfing: It is more serious than bluejacking because it can reveal private information
on a smartphone and is capable of happening even when invisible/non-discoverable mode is
enabled.
• Bluebugging: In short, it’s capable of accessing all the information such as photos, apps,
contacts, etc. It’s more dangerous than bluejacking and bluesnarfing.
In Conclusion, Some prevention tips for Bluetooth hacks are to set invisible mode.
Therefore, makes it more difficult for hackers to gain access to your data. Lastly, stay awake
from the open Wi-Fi networks in busy or untrusted locations, so that you can minimize the
risk of falling victim to hackers.
4.4. Wi-Fi
A ubiquitous Internet of Things (IoT) depends upon wireless connectivity, but there are
many options for wireless and not every device is IP addressable – a requisite feature for IoT.
What’s more, RF design is inherently difficult. Few companies are equipped with the
appropriate skills to implement RF and antenna design, and even when done, keeping that
design up to date with the latest standards and getting it through FCC compliance is time
consuming.
Figure: The wide range of IoT applications that use Wi-Fi modules shows the flexibility and
scalability of the interface, as well as its ubiquity. (Source: Tektronix.)
192 | P a g e
lOMoAR cPSD| 26885763
For designers, there is a very solid and proven option for wireless connectivity and the IoT.
That option is Wi-Fi and the use of modules. This feature will explain why, offer some
design solutions, discuss soon-to-arrive upgrades to IEEE 802.11 protocols, and show how to
bridge ZigBee to Wi-Fi for native IP addressability.
There are many wireless interface options, Bluetooth Low Energy (BLE), ZigBee, Z-Wave,
Wi-Fi and RFID, each with their own unique balance of power, range, data rates, mesh
networking, interference immunity, and ease of use. However, some interfaces are not yet
native-IP enabled, so cannot be addressed directly or exchange data with other devices and
servers over the Internet. These then require a separate gateway, adding expense and
complexity to the final solution.
This is where Wi-Fi stands out: it is based on the IEEE 802.11 standards with native IP
addressability, is ubiquitous, well understood, and can scale well in terms of data rates to
optimize for power consumption. According to the Wi-Fi Alliance, there are more than 6.8
billion installed Wi-Fi-capable devices, so the odds are pretty high that there is a local Wi-Fi
access point available . Note too that 802.11 standards are also IPv6 compliant, so there’s
almost no limit to the number of unique addresses.
While Wi-Fi is widespread and well understood, it is still a wireless interface, with all the
vagaries of design that RF entails. Understanding next steps is critical.
How does this task get done within typical time to market parameters given that RF design
expertise is not something readily available to every electronics company? An increasingly
common way to add Wi-Fi capability is to use a pre-packaged module. This approach greatly
simplifies the process. Modules are supplied tested, calibrated and pre-certified to the
required standards by the module vendor, and therefore can provide companies with a fast,
easy route to market with what is, essentially, a plug-and-play solution, reducing the need for
193 | P a g e
lOMoAR cPSD| 26885763
software development. What is more, manufacturers who design and build the Wi-Fi
modules can be your RF consultants during the design integration stage.
The Wi-Fi module generally contains two main parts: a Wi-Fi chip and an application host
processor. The Wi-Fi subsystem includes an 802.11 radio physical layer (PHY), baseband,
media access control (MAC), and perhaps a crypto engine for fast, secure Internet
connection. The application host processor has internal or external flash, ROM, and RAM.
The module generally also comes with I/Os for timers, serial communication interfaces,
analog comparators, analog-to-digital converter (ADC), digital-to-analog converter (DAC),
crystal oscillators, and a debug interface.
The power management subsystem includes integrated DC-DC converters supporting a wide
range of supply voltages. It enables low-power consumption modes, such as hibernate with
real-time clock (RTC) mode. A module may offer an integrated antenna or provide an RF
connector for an external antenna. The software package included with a Wi-Fi module
usually includes a device driver, an integrated 802.11 security layer, and a management and
monitoring utility.
In designing a Wi-Fi IoT solution, the starting point is an understanding that IEEE 802.11
represents a family of standards that until just recently operated only in the 2.4 GHz (IEEE
802.11b/g/n) and 5 GHz (IEEE 802.11a/n/ac) unlicensed bands. There are three key factors
to consider when evaluating these protocols: data rate, range, and power requirements. When
you compare the different Wi-Fi protocols, 802.11b/g has the advantage in compatibility
with installed devices and power requirements while 802.11n and 802.11ac have the
advantage of higher data throughput for multimedia applications such as video streaming
(see Table).
Table: A summary of different Wi-Fi protocols and data rates shows the progression of IEEE
802.11 from its early days of 2 Mbps to 1.3 Gbps today. (Source: Intel Corp.)
194 | P a g e
lOMoAR cPSD| 26885763
When designing for IoT applications, however, a higher data rate protocol is not always
preferable. Even though 802.11ac can crank it up to a maximum of 1.3 Gbps, most embedded
applications (e.g., machine to machine [M2M] data and control devices) are power
constrained and can get by with a much lower data rate.
One more good reason to choose Wi-Fi is that within the next year or so technology upgrades
will make it much more capable. For example, the Wi-Fi Alliance recently announced the
Wi-Fi HaLow (pronounced "halo") designation for products incorporating IEEE 802.11ah
technology. HaLow extends Wi-Fi into the 900 MHz band and offers improved range –
nearly twice that of today’s Wi-Fi – with scalable data rates from 150 Kbps to 2.1 Mbps;
IEEE 802.11ah also promises to provide low power consumption features and its use cases
are primarily for wireless sensor networks, a classic IoT application.
In February, at the 2016 International Solid-State Circuits Conference (ISSCC) the Holst
Centre of the Netherlands, in collaboration with Belgium’s IMEC Research Institute, showed
a HaLow transmitter running Wi-Fi over sub-GHz bands. The team cited a maximum power
consumption of 7.1 mW when delivering 0 dBm output power and operating from a 1 V
supply. This represents a 10x power reduction compared to state-of-the-art 802.11 OFDM
transceivers.
Also under development is IEEE 802.11ai, which will provide a fast initial link setup
(achieving a secure link setup in less than 100 ms) and IEEE 802.11aq, being developed to
provide a cellular-like automatic network-discovery experience.
Microchip, for example, supplies an IoT development kit (DM990001) using a module
driven by a 32-bit controller. It employs two Microchip components,
the MRF24WG0MA/B pre-certified Wi-Fi module, which supports both 802.11b and
802.11g, and the PIC32MX695F512H microcontroller with 128 Kbytes of RAM and 512
Kbits of flash. The PIC MCU features an 80 MHz, 105-DMIPS 32-bit core, a USB 2.0 On-
The-Go (OTG) peripheral with integrated PHY, a 10/100 Ethernet MAC, and four dedicated
direct memory access (DMA) channels for USB OTG and Ethernet.
The starter kit is powered by Amazon Web Services (AWS), a managed cloud platform that
lets connected devices securely interact with cloud applications. With AWS IoT applications
195 | P a g e
lOMoAR cPSD| 26885763
can keep track of and communicate with all networked devices, all the time, even when they
aren’t connected.
Amazon has put together Quickstart reference deployments for its AWS IoT, which is
designed to show off some of the capabilities of the platform. AWS IoT can be especially
helpful if you plan to use Amazon as your hosting provider. It supports HTTP, WebSockets
for web browsers and web servers, and MQ Telemetry Transport (MQTT), a lightweight
communication protocol for small sensors and mobile devices specifically designed to
tolerate intermittent connections, minimize the code footprint on devices, and reduce network
bandwidth requirements.
The CC3100MOD Wi-Fi Network Processor subsystem incorporates an 802.11 b/g/n radio,
baseband, and MAC and has a 256-bit encryption engine for secure Internet connection. It
196 | P a g e
lOMoAR cPSD| 26885763
also contains a dedicated ARM MCU that completely off-loads the host MCU. The power
management subsystem includes an integrated DC-DC converter with support for a wide
range of supply voltages. It enables low-power consumption modes such as hibernate with
RTC mode, which requires only about 7 μA of current.
On the software side the module includes embedded TCP/IP and TLS/SSL security stacks,
HTTP server, and multiple Internet protocols. The device driver keeps the host memory
footprint requirement to less than 7 Kbytes for code and 700 bytes of RAM for data for a
TCP client application. The CC3100MOD IoT module solution is also FCC, IC, CE, and Wi-
Fi certified.
Block diagram of the ST SPWF01S serial-to-Wi-Fi b/g/n module. With low power
consumption and a small form factor, it can be used for both fixed and mobile wireless
applications.
The SPWF01S comes with CE, FCC and IC certification and meets industrial temperature-
range requirements.
While we have focused on Wi-Fi, the ZigBee wireless standard is a popular choice for a wide
range of applications that require low power, medium range, and flexible networking that is
197 | P a g e
lOMoAR cPSD| 26885763
relatively easy to install, configure and maintain. ZigBee, however, lacks a crucial
requirement for IoT applications: native IP connectivity. Digi International’s XBee® Wi-Fi
modules bridge this gap. To get you started, the company’s XBee Wi-Fi Cloud kit (xka2B-
wft-0) includes an XBee Wi-Fi (S6B) module, XBee USB development board with
breadboard, a components package (resistors, relay, buttons, LEDs), access to Digi’s cloud-
based application and all necessary antennas, power supplies, and cables. Digi’s XBee Wi-Fi
modules share a common footprint with other XBee modules, which allows different XBee
technologies to be drop-in replacements for each other.
IoT applications depend upon wireless connectivity, but there are numerous wireless protocol
options. RF design also is inherently difficult and few companies are equipped with the
appropriate skills to implement RF and antenna design. Even if the expertise is available,
keeping the design up to date with the latest standards and getting it through FCC compliance
is time consuming. This Wi-Fi modules and their associated kits and reference designs can
dramatically simplify the implementation challenges facing designers of new IoT devices.
4.5. Zigbee
When you are designing, planning and prototyping a wireless application, the protocol you
choose is a key component, with considerations for security, flexibility and the ability to
deploy to multiple regions.
Zigbee is a wireless technology developed as an open global standard to address the unique
needs of low-cost, low-power wireless IoT networks. The Zigbee standard operates on the
IEEE 802.15.4 physical radio specification and operates in unlicensed bands including 2.4
GHz, 900 MHz and 868 MHz.
The 802.15.4 specification upon which the Zigbee stack operates gained ratification by
the Institute of Electrical and Electronics Engineers (IEEE) in 2003. The specification is a
packet-based radio protocol intended for low-cost, battery-operated devices. The protocol
allows devices to communicate in a variety of network topologies and can have battery life
lasting several years.
The Zigbee 3.0 protocol was created and ratified by member companies
of the Zigbee Alliance. Over 300 leading semiconductor manufacturers, technology firms,
OEMs and service companies comprise the Zigbee Alliance membership. The Zigbee
protocol was designed to provide an easy-to-use wireless data solution characterized by
secure, reliable wireless network architectures.
198 | P a g e
lOMoAR cPSD| 26885763
The Zigbee 3.0 protocol is designed to communicate data through noisy RF environments
that are common in commercial and industrial applications. Version 3.0 builds on the
existing Zigbee standard but unifies the market-specific application profiles to allow all
devices to be wirelessly connected in the same network, irrespective of their market
designation and function.
Additionally, a Zigbee 3.0 certification scheme ensures the interoperability of products from
different manufacturers. Connecting Zigbee 3.0 networks to the IP domain opens up
monitoring and control from devices such as smartphones and tablets on a LAN or WAN,
including the Internet, and brings the true Internet of Things to fruition.
199 | P a g e
lOMoAR cPSD| 26885763
connectivity standard operates on the IEEE 802.15.4 physical board radio specification and
operates in unlicensed radio bands including 2.4 GHz, 900 MHz and 868 MHz.
The 802.15.4 wireless specification upon which the Zigbee stack operates gained board
ratification by the Institute of Electrical and Electronics Engineers (IEEE) in 2003. The
specification is a packet-based radio board protocol intended for low-cost, battery-operated
devices and products. The protocol allows devices to communicate data in a variety of
network topologies and can have battery life lasting several years.
The Zigbee 3.0 Protocol
The Zigbee protocol has been created and ratified by member companies of the Zigbee Board
Alliance.Over 300 market leading semiconductor manufacturers, technology firms, OEMs
and service companies comprise the Zigbee Alliance membership board. The Zigbee
protocol was designed to provide an easy-to-use wireless data solution characterized by
secure, reliable wireless network architectures.
The Zigbee 3.0 protocol is designed to communicate data through noisy RF environments
that are common in commercial and industrial market applications. Version 3.0 builds on the
existing Zigbee connectivity standard but unifies the market-specific application profiles to
allow all devices to be wirelessly connected in the same network, irrespective of their market
designation and function. Furthermore, a Zigbee 3.0 certification scheme ensures the
interoperability of products from different device manufacturers. Connecting Zigbee 3.0
networks to the IP domain opens up wireless monitoring and control from radio devices such
as smartphones and tablets on a LAN or WAN, including the Internet, and brings the true
Internet of Things to fruition.
Zigbee protocol features include:
• Support for multiple network topologies such as point-to-point,
point-to-multipoint and mesh networks
• Low duty cycle – provides long battery life
• Low latency
• Direct Sequence Spread Spectrum (DSSS)
• Up to 65,000 nodes per network
• 128-bit AES encryption for secure data connections
• Collision avoidance, retries and acknowledgements
The Zigbee 3.0 software stack incorporates a ‘base device’ that provides consistent behavior
for commissioning nodes and devices into a network. A common set of commissioning
methods is provided, including Touchlink, a method of proximity commissioning.
200 | P a g e
lOMoAR cPSD| 26885763
201 | P a g e
lOMoAR cPSD| 26885763
A key component of the Zigbee protocol is the ability to support mesh networking. In a mesh
network, nodes are interconnected with other nodes so that multiple pathways connect each
node. Connections between nodes are dynamically updated and optimized through
sophisticated, built-in mesh routing table.
Mesh networks are decentralized in nature; each node is capable of self-discovery on the
network. Also, as nodes leave the network, the mesh topology allows the nodes to
reconfigure routing paths based on the new network structure. The characteristics of mesh
topology and ad-hoc routing provide greater stability in changing wave conditions or failure
at single nodes.
4.6. GPS
GPS uses satellites to monitor the movement of anything equipped with such a GPS
tracking device, including automobiles, humans, and even pets. It operates in any weather
condition and offers precise location updates in real-time. As one of the earliest ways to
track and disseminate digital information from the real environment, GPS has significantly
impacted IoT technology. The Internet of Things (IoT) may gather and measure enormous
amounts of data on anything from individual health to public transportation; GPS tracking is
required to provide location information for such objects.
A more reliable and easily accessible data set can be built using GPS and the Internet
of Things. In the same way that GPS pinpoints the precise location of a vehicle, the Internet
of Things is able to monitor moving items and collect data on their movements in real time.
202 | P a g e
lOMoAR cPSD| 26885763
GPS satellites complete two accurate orbits around the planet every day. An individual
satellite's signal and orbiting parameters can be decoded and used to pinpoint the satellite's
location via a GPS receiver. This data, together with triangulation, is used by GPS receivers
to pinpoint the precise location of its owners.
Cut back on the money spent on managing employees. By equipping workers with GPS
trackers, employers can gain insight into the "what? who? where?" of their operations and,
using that data, create more effective attendance and safety management systems. Can cut
administrative expenses
Some Devices that are part of the Internet of Things and use a global positioning
system
203 | P a g e
lOMoAR cPSD| 26885763
LORAWAN G62: Using publicly or private LoRaWAN (Long Range Wide Area Network)
networks, the G62 LoRaWAN can keep tabs on any service, no matter how extreme the
weather becomes. It is compact, lightweight, and built to withstand the elements.
LORAWAN, OR SHELLFISH: The Oyster is a rugged GPS tracking system that can
withstand the elements and be made with the super-long battery life of LoRaWAN networks
in mind for tracking exposed, unpowered assets in mind.
204 | P a g e
lOMoAR cPSD| 26885763
The NEO-6M GPS module is also compatible with other microcontroller boards..
Pin Wiring
The NEO-6M GPS module has four pins: VCC, RX, TX, and GND. The module
communicates with the Arduino via serial communication using the TX and RX pins, so the
wiring couldn’t be simpler:
VCC 5V
GND GND
205 | P a g e
lOMoAR cPSD| 26885763
Parts Required
Wire the NEO-6M GPS module to your Arduino by following the schematic below.
void setup(){
Serial.begin(9600);
ss.begin(9600);
}
void loop(){
while (ss.available() > 0){
// get the byte data from the GPS
byte gpsData = ss.read();
Serial.write(gpsData);
}
}
206 | P a g e
lOMoAR cPSD| 26885763
Wireless MODEMs
Wireless MODEMs are the MODEM devices that generate, transmit or decode data from a
cellular network, for establishing communication between the cellular network and the
computer. These are manufactured for specific cellular network (GSM/UMTS/CDMA) or
207 | P a g e
lOMoAR cPSD| 26885763
GSM/GPRS MODEM
GSM/GPRS MODEM is a class of wireless MODEM devices that are designed for
communication of a computer with the GSM and GPRS network. It requires a SIM
(Subscriber Identity Module) card just like mobile phones to activate communication with
the network. Also they have IMEI (International Mobile Equipment Identity) number similar
to mobile phones for their identification. A GSM/GPRS MODEM can perform the following
operations:
The MODEM needs AT commands, for interacting with processor or controller, which are
communicated through serial communication. These commands are sent by the
controller/processor. The MODEM sends back a result after it receives a command. Different
AT commands supported by the MODEM can be sent by the processor/controller/computer
to interact with the GSM and GPRS cellular network.
GSM/GPRS Module
208 | P a g e
lOMoAR cPSD| 26885763
Block Diagram Showing Diffrent Functions Of Cell Phone And SIM In Mobile Station
Mobile Termination is interfaced with the GSM mobile network and is controlled by a
baseband processor. It handles access to SIM, speech encoding and decoding, signaling and
other network related tasks. The Terminal Equipment is an application processor that deals
with handling operations related to keypad, screen, phone memory and other hardware and
software services embedded into the handset. The Terminal Adapter establishes
communication between the Terminal Equipment and the Mobile Termination using AT
commands. The communication with the network in a GSM/GPRS mobile is carried out by
the baseband processor.
209 | P a g e
lOMoAR cPSD| 26885763
And, it also provides an edge toward the public switched telephone network so that the phone
calls can be connected from the network of the mobile to a phone to a landline. Interfaces to
other mobile switching center server are provided to allow mobile calls to be made to
mobiles over dissimilar networks.
Even once the mobile is switched on, but not active then it again registers to make sure that
the HLR network is responsive to its most recent location. There is one HLR for each
210 | P a g e
lOMoAR cPSD| 26885763
network, even though it may be dispersed across a variety of sub-centers for operational
causes.
The Short Message Service Gateway Mobile Switching Centre (SMS-GMSC) is used for
short messages which are being transmitted to an ME. The Short Message Service Inter-
Working Mobile Switching Centre (SMS-IWMSC) is used for short messages created
through a mobile network. The main role of SMS-GMSC is related to GMSC, but the SMS-
IWMSC offers a permanent access end to the SMS Centre.
211 | P a g e
lOMoAR cPSD| 26885763
These units were the major ones that are used in the network of GSM technology. They were
normally co-located, however frequently the overall middle network was transmitted around
the country wherever the network was situated. In case of malfunction, it will give some
flexibility.
The network subsystem provides the basic network connection to the mobile stations. The
basic part of the Network Subsystem is the Mobile Service Switching Centre which provides
access to different networks like ISDN, PSTN, etc. It also consists of the Home Location
Register and the Visitor Location Register which provides the call routing and roaming
capabilities of GSM.
It also contains the Equipment Identity Register which maintains an account of all the mobile
equipment wherein each mobile is identified by its own IMEI number. IMEI stands for
International Mobile Equipment Identity.
The BSS or Base Station Subsystem section of the second generation GSM network
architecture is basically connected with the mobiles over the network. This subsystem
includes two elements which are discussed below.
212 | P a g e
lOMoAR cPSD| 26885763
Mobile Station
It is the mobile phone which consists of the transceiver, the display, and the processor and is
controlled by a SIM card operating over the network.
The hardware includes the major elements of the mobile phone like the case, display,
battery, & the electronics utilized to produce the signal & process the data receiver to be
broadcasted.
The mobile station includes a number called the IMEI. This can be set up on the mobile
phone while manufacturing & it cannot be modified.
It is accessed by the network during registration to check whether the equipment has been
reported as stolen.
The SIM (Subscriber Identity Module) card includes the data which gives the user
identity toward the network. And also, it includes different information like a number called
the IMSI (International Mobile Subscriber Identity). When this IMSI is used in the SIM card,
the mobile user could simply change mobiles by moving the SIM from one mobile to
another.
So mobile changing is easy without changing the same mobile number means that people
would frequently improve, thus making a further income stream for the providers of network
& serving to enhance the total financial victory of GSM.
213 | P a g e
lOMoAR cPSD| 26885763
preservation tasks are moved to the base transceiver stations so that the ownership cost of the
system can be reduced.
GSM Modem
A GSM modem is a device that can be either a mobile phone or a modem device that
can be used to make a computer or any other processor communicate over a network. A
GSM modem requires a SIM card to be operated and operates over a network range
subscribed by the network operator. It can be connected to a computer through serial, USB,
or Bluetooth connection.
A GSM modem can also be a standard GSM mobile phone with the appropriate cable
and software driver to connect to a serial port or USB port on your computer. GSM modem
is usually preferable to a GSM mobile phone. The GSM modem has a wide range of
applications in transaction terminals, supply chain management, security applications,
weather stations, and GPRS mode remote data logging.
214 | P a g e
lOMoAR cPSD| 26885763
The command so sent by the user is based on an intimation received by him through the
GSM modem ‘ALERT’ a programmed message only if the input is driven low. The complete
operation is displayed over a 16×2 LCD display.
215 | P a g e
lOMoAR cPSD| 26885763
computer, but it may or may not support AT commands from the computer or an external
processor/controller.
The GSM/GPRS module, on the other hand, always needs a computer or external
processor/controller to receive AT commands from. GSM/GPRS module itself does not
provide any interface between the user and the network, but the computer to which module is
connected is the interface between user and network.
An advantage that GSM/GPRS modules offer is that they support concatenated SMS which
may not be supported in some GSM mobile handsets. Also some mobile handsets can’t
receive MMS when connected to a computer.
Scope
we will be understanding Operating systems that can be installed on a Raspberry Pi.
• We'll learn about What an operating system in general is.
• We'll go through a Variety of Operating Systems that a Raspberry Pi can run.
Introduction
As read above, Raspberry Pi is a very low-cost computer that comes along with the
advantage of portability. However, being in such a small form factor, it gets bounded by the
type of hardware to use in making it; hence, it will be significantly tough to run regular
operating systems on it.
Due to this, specific operating systems were designed to power a Raspberry Pi; some of them
were entirely new, while some originated from existing popular operating systems. Most of
the Raspberry Pi OS is Linux based, but it also has windows 10-based Raspberry Pi
OS (Windows 10 IoT core) built explicitly for low-powered devices like this.
216 | P a g e
lOMoAR cPSD| 26885763
Meaning an operating system is a software program that helps us to use and to connect with
the computer hardware. For example, if we want to use our mouse or keyboard, only with the
help of an OS we can do that; if we want to install some program on our computer, we would
be needing an OS; if we want to create a file, we need an OS; we want to delete a file, we
would again be needing an OS, i.e., without an operating system we cannot use the computer
hardware, we would be needing some underlying software, i.e., some operating system, using
which we would do so.
217 | P a g e
lOMoAR cPSD| 26885763
The above image is a picture of a Raspberry Pi; we can see that there are various ports
available in it on which different devices can be mounted and used.
It was first launched in 2012, and from then onwards, various variations of it have been
launched. The original Raspberry Pi had a single-core 700mhz CPU and a 256MB of RAM,
but it has evolved a lot since then; today, we have a quad-core Raspberry Pi with a clock
speed of around 1.5Ghz and up to 4GB of RAM. Surprisingly the cost of Raspberry Pi has
always been less than 100 USD. In fact, the Raspberry Pi Zero (an even low-cost version of
regular Raspberry Pi) costs as less as 5 USD. A full-fledged general-purpose CPU under 5$,
that's what the organization's mission is "Aiming to provide people easier and low-cost
access to the computers."
Raspberry Pi is used by people all around the world in learning how to program, build
hardware projects, do home automation, and implement Kubernetes clusters, and it is even
getting used in some industrial applications. Raspberry Pi is a very economical computer that
runs Linux Operating System.
Now, let's talk about which specific distribution of Linux Raspberry Pi uses. Raspberry Pi
officially recommends the use of the Raspbian Operating System. It is a Debian-based OS,
explicitly made for Raspberry Pi and hence its name Raspbian.
Explore free courses by our top instructorsView All
TARUN LUTHRA
Java Course - Mastering the Fundamentals
56k+ enrolled
218 | P a g e
lOMoAR cPSD| 26885763
RAHUL JANGHU
Python Certification Course: Master the essentials
42k+ enrolled
PRATEEK NARANG
C++ Course: Learn the Essentials
29k+ enrolled
35,262+ learners have attended these Courses.
Raspbian
Raspbian or Raspberry Pi OS is a Linux-based operating system built specifically for
Raspberry Pi. It is packed with all the necessary tools and features that are required for day-
to-day use. It will possibly run on every kind of Raspberry Pi board with a few exceptions,
like the Raspberry Pi's pico edition, because of its far smaller form factor and computing
power.
NOOBS
New Out Of the Box Software, or simply NOOBS is an operating system installer for
Raspberry Pi, delivered primarily on an SD card, which contains a variety of operating
systems, out of which we can choose which one we want to install on our Raspberry Pi. It is
made for people who are absolutely new to the Raspberry Pi and do not want to deal with the
complex setting up process of burning an OS image on an SD card. NOOBS is provided
along with every new Raspberry Pi at the time of its purchase.
With NOOBS, the user only needs to connect their Raspberry Pi to a display screen and a
keyboard and then power it up; the NOOBs will boot. There we can select which operating
system we want to install, and NOOBS will install the respective OS on the same SD card
within a few minutes.
219 | P a g e
lOMoAR cPSD| 26885763
Minibian
While Raspbian OS is very lightweight as far as we talk about operating systems, but if we
want something even more straightforward, then we can go for Minibian OS. It is a minimal
version of Raspbian for Raspberry Pi machines. The now-going version of minibian is based
on the recent Raspbian build and will run on all the versions of Raspberry Pi. Minibian
differs from Raspbian in a number of ways, but the main difference is it is built more for
electronics people instead of those who are interested in making a full-fledged computer.
Minibian includes the core system and some fundamental utilities like web servers, some
electronics applications, etc. Notably, it does not include a Graphical interface for
interaction, which makes it an excellent choice for embedded projects. The result then is, we
have a capable and working operating system in less than 500MB which merely uses 30MB
of RAM.
Raspbian Lite
It is also a lightweight operating system for Raspberry Pi with a minimal set of packages. It
is advised only for experienced users who are able to establish ssh connections and remote
management using the command line, as it does not includes the GUI interface. It is more
like a command line-based operating system where we would be needing to type commands
to control our Raspberry Pi computer. One advantage of this is that it can run on a very low
amount of CPU and RAM. It should be noted that Raspbiain lite OS can also be converted
220 | P a g e
lOMoAR cPSD| 26885763
into a complete desktop environment with a GUI interface by installing the necessary
packages.
RISC OS
RISC OS is an open-source OS initially developed in Cambridge in the 1980s and was the
first operating system for ARM processors. It is neither related to Linux, Windows, or any
other operating system; hence, diving into it will ignore our previous operating system
experiences. Understanding the RISC OS will be a completely different thing, and it will take
time for us to get used to it.
Ubuntu Mate
Ubuntu Mate is a free and open-source operating system of raspberry pi that specifies low-
performance devices as its design requirements, meaning it works seamlessly on low-power
or old appliances. It is a flavor of Ubuntu that uses the Mate desktop environment. It
prioritizes pre-packaging the apt package manager into its software deployment and talking
about the communication to remote workstations; ubuntu MATE is dependable. To run it on
a Raspberry Pi device, a 4GB sd card is all that is required. It should also be noted that
ubuntu mate OS is consistently maintained and updated by its developers. It can be
downloaded from the official website of Ubuntu MATE.
Gentoo Linux
Gentoo Linux is an open-source Linux-based lightweight operating system of the raspberry
pi. Its built-in portage package manager makes the package installation straightforward and
easy using emerge instead of apt installer. Moreover, it offers unique adaptability, which
makes it an ideal Linux distribution for these low-powered devices. A 4GB SD Card will be
enough to fulfill the device requirements of Gentoo OS on Raspberry Pi.
SARPI
Slackware ARM, or SARPI, is a well-known operating system in the Raspberry Pi
community. It is often regarded as one of the substantial operating systems to run on the
Raspberry Pi. This is because it has a very simple-to-implement software architecture. The
boot time of SARPI OS is really less, making it live in less than 30 seconds of time.
221 | P a g e
lOMoAR cPSD| 26885763
FreeBSD
FreeBSD is an open-source Unix-like operating system derived from the Berkeley Software
Distribution or BSD, which was based on the research of Unix (early versions of the Unix
operating system). It works seamlessly with powerful hardware. Its software design makes it
a significantly great OS to interact with servers, desktop PCs, IoT devices, cloud computing,
etc. The FreeBSD OS can run on as less as a Raspberry Pi with 512MB of RAM; it can also
be a perfect choice for one's Raspberry Pi system.
Lakka
A free, open-source, and lightweight operating system that can turn any PC into a full-
fledged gaming console without the keyboard and mouse. It is basically used to set up
emulators on systems like Raspberry Pi.
OpenELEC
Open Embedded Linux Entertainment Center or OpenELEC. It is a minimal-sized OS, often
referred to as Just Enough Operating System or JeOS. If one is aware of the Kodi Media
Center, which is a tool for managing media files. The primary purpose of this OS is to
transform the running system into Kodi.
OSMC
OSMC is a free and open-source operating system of raspberry pi that stands for Open
Source Media Center. It is simple and easy to work with the program that can independently
supply Kodi Operating System functions like media file format management. Its user-
friendly interface is simple and sophisticated, and its built-in image library contributes to its
extensive customization possibilities. Therefore, it is an excellent choice if we majorly want
to handle media materials on the Raspberry Pi system.
RaspBSD
RaspBSD is a special kind of FreeBSD operating system of raspberry pi and similar systems.
It is an open-source OS software that contains the FreeBSD 11 image. The live image of
RaspBSD features FreeBSD with the pre-installed Openbox window manager and the LXDE
desktop environment. RaspBSD is based on FreeBSD's current tree.
Linutop
Linutop is a Raspbian OS-based Linux operating system of the raspberry pi. It's software
security makes it the ideal choice for web kiosks and digital signage players. Moreover, it
obligates its features and performance specifications to business users who wish for
Raspberry Pi's digital signage and internet stall solutions.
Kali Linux
222 | P a g e
lOMoAR cPSD| 26885763
Kali is a Debian-based operating system particularly made for penetration testing. It comes
with both the 32bit and 64bit architecture and is also one of the most feature-rich OS we have
talked about so far. It has all the necessary tools needed for penetration testing installed by
default. In addition, Kali's community is very effective and helpful. With Kali Linux, a
Raspberry Pi device can become a toolset for penetration inside one's pocket.
Domoticz
Domoticz is a free and open-source home automation system that allows users to design and
monitor various devices like switches, sensors, and meters for temperature, power, etc.
Domoticz's main user interface is an expandable and scalable HTML5 frontend. Some of its
outstanding features are its interactiveness with any browser, extensive logging, support for
external devices, and auto-learning for sensors and switches.
OpenSUSE
The openSUSE project is a global initiative based on the RPM-based Linux distribution,
which promotes the adoption of Linux OS everywhere by developing desktop and server
operating systems. OpenSUSE operating system for Raspberry Pi is a part of the openSUSE
project. The initiative's primary goal is to educate people about Linux. The openSUSE OS is
developed, distributed, and maintained by an open-source community.
RetroPie
RetroPie is an emulator which can be used to play some low-end games on one's Raspberry
Pi. It is a Debian-based open-source software library. It is elementary to set up and has broad
community support. RetroPie uses the Emulation Station frontend RetroArch etc., which
makes it possible to play old-school console games, nostalgic arcade games, and classic pc
games. To add more to it, RetroPie sits on the top of the Raspberry Pi Lite Operating System,
which omits the PIXEL (Pi improved XWindows Environment Lightweight) environment.
And along with that, it can also be installed on top of a fully working Raspberry Pi OS.
RetroPie is a popular emulation platform for playing retro games on the Raspberry Pi.
Ubuntu Core
223 | P a g e
lOMoAR cPSD| 26885763
Ubuntu core is essentially designed to meet the needs of IoT devices. It is a minimal version
of Ubuntu which requires less storage and memory to function. As Ubuntu is one of the most
popular Linux distributions, hence its community has plenty of support and resources for
users who are interested in ubuntu core. It is simple to set up and can be installed using the
ubuntu snappy core installer.
Batocera.Linux
Batocera is a widespread open-source Linux distribution built primarily for retro gaming.
While it could run on some standard computer systems, but is designed explicitly for
microcomputers like Raspberry Pi. People who want to transform their Raspberry Pi
computer into a gaming console are recommended to download Batocera.Linux
BMC64
BMC64 is a free and open-source system that is a bare metal version of VICE's C64
emulator. BMC64 proves to be an appropriate operating system for devices like Raspberry
Pi. The reasons are it has the GIPO pins to connect simple keyboards and joysticks, it offers
PCB scanning, real 50Hz/60Hz scrolling, low audio and video latency, an optimal startup
time, etc., helpful features.
Notes:-
• Raspberry Pi is a low-cost, economical pocket-sized computer, the size of an ATM
Card.
• It was developed by Raspberry Pi Foundation in 2012with the aim of providing
people easy access to computing and computer education.
• Due to its small form factor, it is bounded by certain hardware limitations, and hence
running regular operating systems on it will be comparatively effortful.
• Therefore, specific operating systems were designed to power devices like Raspberry
Pi.
• Most of the operating systems for Raspberry Pi are Linux-based, but certain are not.
For example - Windows 10 IoT core (windows 10-based Raspberry Pi Operating
System), RISC OS (a completely different OS model, which is neither Linux nor
windows), etc.
• Raspberry Pi devices are mainly used as portable computers used for building
hardware projects, IoT applications, home automation, etc.
• Along with all these, we can also use a Raspberry Pi to play games, listen to music,
do regular programming, etc.
• Raspberry Pi could be a great tool if one wants the power of an on-the-go computer
along with the advantage of great portability.
224 | P a g e
lOMoAR cPSD| 26885763
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).
The original device had a single-core Processor speed of device ranges from 700 MHz to 1.2
GHz and a memory range from 256 MB to 1 GB RAM.
To store the operating system and program memory Secure Digital (SD) cards are used.
Raspbian OS which is a Linux operating system is recommended OS by Raspberry Pi
Foundation. Some other third party operating systems like RISC OS Pi. Diet Pi, Kali, Linux
can also be run on Raspberry Pi.
Used:
It also provides a set of general purpose input/output pins allowing you to control electronic
components for physical computing and explore the Internet of Things (IOT).
Raspberry pi Diagram:
225 | P a g e
lOMoAR cPSD| 26885763
Raspberry Pi model –
There have been many generations of raspberry Pi from Pi 1 to Pi 4. There is generally a
model A and model B. Model A is a less expensive variant and it trends to have reduced
RAM and dual cores such as USB and Ethernet.
226 | P a g e
lOMoAR cPSD| 26885763
Specs of the Computer: – The computer has a quad-core ARM processor that doesn’t
support the same instruction as an X86 desktop CPU. It has 1GB of RAM, One HDMI port,
four USB ports, one Ethernet connection, Micro SD slot for storage, one combined 3.5mm
audio/video port, and a Bluetooth connection. It has got a series of input and output pins that
are used for making projects like – home security cameras, Encrypted Door lock, etc.
227 | P a g e
lOMoAR cPSD| 26885763
With all the features and capabilities that are packed into this small board, there’s no
shortage of projects and use cases for the Raspberry Pi.
If you can think of a project that would benefit from having a credit card–sized computer
attached to it, then someone has probably used a Raspberry Pi to do it. The Raspberry Pi is a
fantastic way to bring your Python project ideas to life.
Raspberry Pi Board Overview
Below is the board layout of the Raspberry Pi 4. While this layout is slightly different from
previous models of the Raspberry Pi, most of the connections are the same. The setup
described in the next section should be the same for both a Raspberry Pi 3 and a Raspberry Pi
4:
228 | P a g e
lOMoAR cPSD| 26885763
• General-purpose input–output pins: These pins are used to connect the Raspberry
Pi to electronic components.
• Ethernet port: This port connects the Raspberry Pi to a wired network. The
Raspberry Pi also has Wi-Fi and Bluetooth built in for wireless connections.
• Two USB 3.0 and two USB 2.0 ports: These USB ports are used to connect
peripherals like a keyboard or mouse. The two black ports are USB 2.0 and the two
blue ports are USB 3.0.
• AV jack: This AV jack allows you to connect speakers or headphones to the
Raspberry Pi.
• Camera Module port: This port is used to connect the official Raspberry Pi Camera
Module, which enables the Raspberry Pi to capture images.
• HDMI ports: These HDMI ports connect the Raspberry Pi to external monitors. The
Raspberry Pi 4 features two micro HDMI ports, allowing it to drive two separate
monitors at the same time.
• USB power port: This USB port powers the Raspberry Pi. The Raspberry Pi 4 has
a USB Type-C port, while older versions of the Pi have a micro-USB port.
• External display port: This port is used to connect the official seven-inch Raspberry
Pi touch display for touch-based input on the Raspberry Pi.
• microSD card slot (underside of the board): This card slot is for the microSD card
that contains the Raspberry Pi operating system and files.
People often wonder what the difference is between a Raspberry Pi and an Arduino. The
Arduino is another device that is widely used in physical computing. While there is some
overlap in the capabilities of the Arduino and the Raspberry Pi, there are some distinct
differences.
For running Python, the Raspberry Pi is often the better choice, as you get a full-fledged
Python installation out of the box without any configuration.
229 | P a g e
lOMoAR cPSD| 26885763
Warriors of programming language wars often cite their own language's "hello world"
against that of another, saying theirs is shorter or more concise or more explicit or
something. Having a nice simple readable "hello world" program makes for a good intro for
beginners learning your language, library, framework, or tool.
I thought it would be cool to create a list of as many different "hello world" programs as
possible that can be run on the Raspberry Pi using its Raspbian operating system, but without
installing any additional software than what comes bundled when you download it from the
Raspberry Pi website. I've created a GitHub repository of these programs, and I've explained
10 of them for you here.
1. Scratch
2. Click Looks.
230 | P a g e
lOMoAR cPSD| 26885763
2. Python
Python is a powerful and professional language that's also great for beginners— and it's lots
of fun to learn. Because one of Python's main objectives was to be readable and stick to
simple English, its "hello world" program is as simple as possible.
print("Hello world")
opensource.com
3. Ruby/Sonic Pi
Ruby is another powerful language that's friendly for beginners. Sonic Pi, the live coding
music synth, is built on top of Ruby, so what users actually type is a form of Ruby.
231 | P a g e
lOMoAR cPSD| 26885763
3. Press Run.
Alternatively, to using the Sonic Pi application for this example, you can write Ruby code in
a text editor and run it in the terminal:
ruby hello.rb
4. JavaScript
232 | P a g e
lOMoAR cPSD| 26885763
This is a bit of a cheat as I just make use of client-side JavaScript within the web browser
using the Web Inspector console, but it still counts!
console.log("Hello world")
You can also install NodeJS on the Raspberry Pi, and write server-side JavaScript, but that's
not available in the standard Raspbian image.
5. Bash
Bash (Bourne Again Shell) is the default Unix shell command language in most Linux
distributions, including Raspbian. You can enter Bash commands directly into a terminal
window, or script them into a file and execute the file like a programming script.
233 | P a g e
lOMoAR cPSD| 26885763
Note you'd usually see a "hashbang" at the top of the script (#!/bin/bash), but because I'm
calling this script directly using the bash command, it's not necessary (and I'm trying to keep
all these examples as short as possible).
You'd also usually make the file executable with chmod +x, but again, this is not necessary
as I'm executing with bash.
6. Java
5. System.out.println("Hello world");
6. }
7. }
8.
9. Save the file as Hello.java in the home directory.
10. Open Terminal from the main menu.
11. Run the following commands:
234 | P a g e
lOMoAR cPSD| 26885763
java Hello
I could almost remember the "hello world" for Java off the top of my head, but not quite. I
always forget where the String[] args bit goes, but it's obvious when you think about it...
7. C
4. int main() {
5. printf("Hello world\n");
./hello
235 | P a g e
lOMoAR cPSD| 26885763
Note that in the previous examples, only one command was required to run the code
(e.g., python3 hello.py or ruby hello.rb) because these languages are interpreted rather than
compiled. (Actually Python is compiled at runtime but that's a minor detail.) C code is
compiled into byte code and the byte code is executed.
8. C++
C's younger bother, C++ (that's C incremented by one...) is another fundamental low-level
language, with more advanced language features included, such as classes. It's popular in a
range of uses, including game development, and chunks of your operating system will be
written in C++ too.
./hellocpp
236 | P a g e
lOMoAR cPSD| 26885763
Readers familiar with C/C++ will notice I have not included the main function return values
in my examples. This is intentional as to remove boilerplate, which is not strictly necessary.
9. Perl
Perl gets a lot of stick for being hard to read, but nothing much gets in the way of
understanding its "hello world" program. So far, so good!
perl hello.pl
Again, I learned Perl at university, but unlike Java, I have managed to successfully avoid
using it.
237 | P a g e
lOMoAR cPSD| 26885763
So that's nine different programming languages covered, but let's finish with a bit more
Python. The popular computer game Minecraft is available for Raspberry Pi, and comes
bundled with Raspbian. A Python library allows you to communicate with your Minecraft
world, so open Minecraft and a Python editor side-by-side for some fun hacking your virtual
world with code.
7.
8. mc = Minecraft.create()
9.
mc.postToChat("Hello world")
238 | P a g e
lOMoAR cPSD| 26885763
Finally, let's look at the Sense HAT Emulator. This tool provides a graphical representation
of the Sense HAT.
The sense_emu Python library is identical to the sense_hat library except that its commands
get executed in the emulator rather than on a physical piece of hardware. Because the Sense
HAT includes an 8x8 LED display, we can use its show_message function to write "hello
world".
3.
4. sense = SenseHat()
5.
sense.show_message("Hello world")
Example:
Pi Camera Module Interface with Raspberry Pi using Python
239 | P a g e
lOMoAR cPSD| 26885763
• Resolution – 5 MP
• HD Video recording – 1080p @30fps, 720p @60fps, 960p @45fps and so on.
• It Can capture wide, still (motionless) images of a resolution 2592x1944 pixels
• CSI Interface enabled.
240 | P a g e
lOMoAR cPSD| 26885763
Now, we can use Pi Camera for capturing images and videos using Raspberry Pi.
Before using Pi Camera, we need to enable camera for its working.
241 | P a g e
lOMoAR cPSD| 26885763
For enabling the camera in Raspberry Pi, open the raspberry pi configuration using the
following command,
sudo raspi-config
then select Interfacing options in which select the camera option to enable its functionality.
reboot Raspberry Pi.
Now we can access the camera on Raspberry Pi.
Now we can capture images and videos using Pi Camera on Raspberry Pi.
Example
Capture images and save it to the specified directory.
We can capture images using Python. Here, we will write a Python program to capture
images using Pi Camera on Raspberry Pi.
Here, we have used picamera package(library) which provides different classes for
Raspberry Pi. Out of which we are mainly interested in PiCamera class which is for camera
module.
Pi Camera Python Program for Image Capture
Camera
import picamera
from time import sleep
#create object for PiCamera class
camera = picamera.PiCamera()
#set resolution
camera.resolution = (1024, 768)
camera.brightness = 60
camera.start_preview()
#add text on image
camera.annotate_text = 'Hi Pi User'
sleep(5)
#store image
camera.capture('image1.jpeg')
242 | P a g e
lOMoAR cPSD| 26885763
camera.stop_preview()
Functions Used
To use picamera python based library we have to include it in our program as given below
import picamera
This picamera library has PiCamera class for the camera module. So, we have to create an
object for PiCamera class.
PiCamera Class
To use Pi Camera in Python on Raspberry Pi, we can use PiCamera class which has different
APIs for camera functionality. We need to create object for PiCamera class.
E.g.
Camera = picamera.PiCamera()
The above PiCamera class has different member variables and functions which we can access
by simply inserting a dot (.) in between object name and member name.
E.g.
Camera.resolution = (1080, 648)
capture()
It is used to capture images using Pi Camera.
E.g.
Camera.capture(“/home/pi/image.jpeg”)
The capture() function has different parameters which we can pass for different operations
like resize, format, use_video_port, etc.
E.g.
Camera.capture(“/home/pi/image.jpeg”, resize=(720, 480))
resolution= (width,height)
It sets the resolution of the camera at which image captures, video records, and previews will
display. The resolution can be specified as (width, height) tuple, as a string
formatted WIDTHxHEIGHT, or as a string containing commonly recognized display
resolution names e.g. “HD”, “VGA”, “1080p”, etc.
E.g.
243 | P a g e
lOMoAR cPSD| 26885763
stop_preview()
It is used to close the preview overlay.
E.g.
Camera.stop_preview()
Note: There are various APIs of PiCamera class. So, to know more API in detail you can
refer
PiCamera APIs.
Pi Camera Python Program for Video Recording
import picamera
from time import sleep
camera = picamera.PiCamera()
camera.resolution = (640, 480)
print()
#start recording using pi camera
camera.start_recording("/home/pi/demo.h264")
244 | P a g e
lOMoAR cPSD| 26885763
Functions used
We have to create an object for PiCamera class. Here, we have create objects as camera.
start_recording()
It is used to start video recording and store it.
E.g.
Camera.start_recording(‘demo.h264’)
It records video named demo of h264 format.
wait_recording(timeout)
Wait on the video encoder for specified timeout seconds.
E.g.
Camera.wait_recording(60)
stop_recording()
It is used to stop video recording.
E.g.
Camera.stop_recording()
Play Recorded Video
To open a video, we can use omxplayer by using the following command,
omxplayer video_name
245 | P a g e
lOMoAR cPSD| 26885763
Interface a Raspberry Pi with an Arduino so the two boards can communicate with one
another.
Sometimes you may need to connect an Arduino to a Raspberry Pi. For example, if you have
sensors, motors, and actuators, you can connect these to the Arduino and make the Arduino
send values to and from the Raspberry Pi. This way, we can separate the computing intensive
tasks (done by the Raspberry Pi) and controlling tasks (done by the Arduino).
we will connect an Arduino to a Raspberry Pi and have the Arduino send “Hello from
Arduino” to the Raspberry Pi, and the Raspberry Pi will blink an LED upon receiving the
command from the Arduino.
For communication, we will use simple serial communication over USB cable.
So, let’s get started!
246 | P a g e
lOMoAR cPSD| 26885763
Write the following code in the new window and save it. (Save to your desktop so you don't
lose it.)
import serial
import RPi.GPIO as GPIO
import time
GPIO.output(pin,GPIO.HIGH)
time.sleep(1)
GPIO.output(pin,GPIO.LOW)
time.sleep(1)
return
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
while True:
read_ser=ser.readline()
print(read_ser)
if(read_ser=="Hello From Arduino!"):
blink(11)
Now open Arduino IDE and upload the following code to your Arduino.
247 | P a g e
lOMoAR cPSD| 26885763
248 | P a g e
lOMoAR cPSD| 26885763
Next, you'll need to restart your Raspberry Pi. Open the Terminal and execute these
commands:
Then find a line with /dev/ttyACM0 or something like /dev/ttyACM1 etc. (check for an
ACM with any number 0,1,2 etc.)
249 | P a g e
lOMoAR cPSD| 26885763
250 | P a g e
lOMoAR cPSD| 26885763
Some of the GPIO pins are multiplexed with alternate functions like I2C, SPI, UART etc.
We can use any of the GPIO pins for our application.
Pin Numbering
We should define GPIO pin which we want to use as an output or input. But Raspberry Pi
has two ways of defining pin number which are as follows:
• GPIO Numbering
• Physical Numbering
In GPIO Numbering, pin number refers to number on Broadcom SoC (System on Chip).
So, we should always consider the pin mapping for using GPIO pin.
While in Physical Numbering, pin number refers to the pin of 40-pin P1 header on
Raspberry Pi Board. The above physical numbering is simple as we can count pin number on
P1 header and assign it as GPIO.
But, still we should consider the pin configuration diagram shown above to know which are
GPIO pins and which are VCC and GND.
Control LED with Push Button using Raspberry Pi
251 | P a g e
lOMoAR cPSD| 26885763
Example
Now, let’s control LED using a switch connected to the Raspberry Pi. Here, we are using
Python and C (WiringPi) for LED ON-OFF control.
252 | P a g e
lOMoAR cPSD| 26885763
• GPIO as Output
GPIO.setup(channel, GPIO.OUT)
• GPIO as Input
GPIO.setup(channel, GPIO.IN)
253 | P a g e
lOMoAR cPSD| 26885763
GPIO.output(channel, state)
This function is used to set the output state of GPIO pin.
channel – GPIO pin number as per numbering system.
state – Output state i.e. HIGH or LOW of GPIO pin
e.g.
GPIO.output(7, GPIO.HIGH)
GPIO.input(channel)
This function is used to read the value of GPIO pin.
e.g.
GPIO.input(9)
254 | P a g e
lOMoAR cPSD| 26885763
It’s these pins that hold the true power of the Pi. They can control homes, machines, new
inventions, and even robots, so why is it so many people don’t know what they really are?
GPIO stands for ‘General Purpose Input/Output’, and it’s these pins that let the Raspberry Pi
do its magic. This is because the pins have no specific function, and can be set to a dedicated
purpose, such as controlling a signal.
255 | P a g e
lOMoAR cPSD| 26885763
A GPIO pin set to output can provide either 3.3 volts, known as a HIGH signal, or 0 volts,
known as a LOW signal. When set to input, it can read these same voltages.
It’s important to remember that GPIO pins (and the 3.3-volt power pins) are meant to control
and communicate with other components.
You can get about 51mA from all 3.3 volt pins combined, but you’ll want to take care when
connecting; if your circuit tries to pull too much current through these 3.3 volt pins, you can
fry the whole board.
The 5-volt power pins, on the other hand, give you all the power available from the power
supply, minus the bit used by the Raspberry Pi itself.
When you first start using these GPIO pins, it’s wise to use a breadboard. This makes it easy
to build circuits without solder and to modify them.
If you’ve never used a breadboard before, familiarize yourself with the basics here:
A GPIO extension board also helps immensely. This connects the GPIO header via a ribbon
and places the pins directly on the breadboard, in a clearly labeled manner.
It requires some real estate though: 20 rows each side of the breadboard. On a small board,
that’s nearly the whole thing! A breadboard with 40 rows or so leftover gives plenty of space
for beginner projects.
Every GPIO pin can be set to send and receive HIGH and LOW signals. Some have special
uses too.
Hardware PWM
GPIO pins output either 3.3 or 0 volts: a HIGH or LOW signal. Pulse width modulation, or
PWM, is a way of simulating the range of voltages in between by flickering the pin on and
off rapidly.
This isn’t a true analog signal, but it’s fine for something like dimming an LED. It will
flicker faster than you can see and simply appear dimmer.
256 | P a g e
lOMoAR cPSD| 26885763
You can also use a low pass filter to smooth a PWM into an analog signal. This can be used
for analogue audio, if you aren’t fussy about quality. It’s fine for a doorbell or toy.
You can generate a PWM signal from any GPIO pin using software, but the operating system
juggles this with other tasks, so this signal can jitter.
Hardware PWM is available on GPIO pins 18 and 19. Hardware PWM and the headphone
jack use the same circuits, so shouldn’t be used simultaneously.
If you take a look below at the diagram (known as a Raspberry Pi ‘Pinout’) you’ll see that
some pins are I2C, SPI, and UART serial. These are serial bus protocols that can be used to
send and receive data from other components.
You can combine these with a digital-analogue converter, or DAC, to output an analogue
signal. This can be preferable to PWM for high quality audio, or to control many
components.
Often you will want your Raspberry Pi GPIO pin to read the position of a button or a switch.
That’s easy to do by wiring it so that it closes a circuit attached to the control voltage to read
HIGH, or to ground to read LOW.
257 | P a g e
lOMoAR cPSD| 26885763
The problem is that when this circuit is open and nothing else is attached to the pin, it might
return any value. This is known as “floating,” and it’s extremely unhelpful.
You can prevent floating with “pull up” or “pull down” resistors.
A pull up resistor is wired to your control voltage; when nothing else is attached, the pin will
read HIGH. A pull down resistor is wired to ground; the pin will read LOW. Use whichever
provides the opposite value to your switch or button.
You don’t need to wire these resistors into your circuit. They’re inside the Raspberry Pi
already and you can control them from software.
Among the easiest ways to control GPIO pins is by using the GPIO Zero library in Python. If
you’ve written any Python before, you’ll pick this up easy.
If this is your first time using Python, If you don’t, the commands below will still work;
you’ll just be less able to follow along. The web version of ‘Automate the Boring Stuff With
Python’ is excellent and costs nothing.
GPIO Zero is installed by default on Raspbian Desktop images. If you are using Raspbian
Lite or a different operating system, you may need to install it.
Let’s have a go at turning on an LED! A job this simple doesn’t really require a computer,
but we’ll involve the Raspberry Pi in the GPIO pins.
A Raspberry Pi with
power supply and an SD
card with
Raspbian installed
258 | P a g e
lOMoAR cPSD| 26885763
A breadboard
A GPIO extension
board (optional, but
recommended)
An LED
259 | P a g e
lOMoAR cPSD| 26885763
Now add your button to the middle of the breadboard. Connect one pin of the button to a
Raspberry Pi GPIO pin. I’m using 13, because it’s my lucky number.
Then, connect the diagonally opposite pin of the button to the negative power rail. When you
push this button down, the circuit closes.
Finally, we need to tell the Pi to pay attention to this pin, so let’s open the Python interpreter.
At the command prompt, type:
python3
Now at the interpreter, type:
button = Button(13)
This Button class takes care of assigning the pull up resistor. Now let’s test that it works by
typing the following lines:
while True:
if button.is_pressed:
print(‘Sweet, the button works!’)
break
Python is fussy about indentation, so be sure to copy the spaces too. Then press Enter again
to run the loop.
This loop will run until someone presses the button, so press it. It should produce a message
saying the button works. This means you’ve successfully built a simple circuit that sends a
message to your Raspberry Pi. If this doesn’t work, check that everything is connected
properly and try again.
260 | P a g e
lOMoAR cPSD| 26885763
short leg of the LED, and the other end to the negative power rail. Resistors can go in either
way around.
Now let’s go tell the Raspberry Pi what’s going on. Type: Image: Pi & Breadboard
led.on()
led.off()
Controlling the LED With the Button
Now that everything’s connected and you’ve checked they work, type:
button.when_pressed = led.on
Now press the button. The LED should switch on and stay on. Now type:
button.when_released = led.off
Press the button again; the LED should switch off when the button is released.
With the development of smart things, sensors and telecommunication, IoT (Internet of
Things) technology has greatly developed and become more and more standardized. But
fragmented device-side communication connection problems often impede the project
implementation process.
There are four best practices to connect different types of devices to the cloud:
• Directly integrate IoT SDK (Software Development Kit) for resource-rich devices
• Rely on a communication module for resource-constrained devices
261 | P a g e
lOMoAR cPSD| 26885763
IoT Device SDK is used to help us quickly connect hardware devices to the IoT platform.
We can download the IoT Device SDK from the corresponding cloud platform, e.g. AWS
IoT Device SDK.
1. The HAL (hardware abstraction layer) abstracts the support function interface of different
OS (operating systems) to the SDK. This enables the SDK to be ported to different hardware
environments, different OS, and even bare chip environments.
2. The core layer completes the function encapsulation of MQTT/CoAP communication based
on the HAL layer interface, including MQTT connection establishment, message sending and
receiving; CoAP connection establishment, message sending and receiving; shadow device
operation; OTA firmware status query, download and upgrade.
262 | P a g e
lOMoAR cPSD| 26885763
3. Interface layer, providing API and callback function definitions, isolating the core layer and
the application.
4. Provide sample programs so that developers can quickly learn how to use the SDK.
When developing applications on a device, we can always choose higher-level SDKs such as
Android IoT SDK on an Android device. That’s because the hardware environment porting
work has already been done by the SDK itself.
However, when developing applications for an MCU (Micro Controller Unit) which has
Linux or RTOS (Real Time Operating System), we should choose Embedded C SDK and
port the code to a specific hardware environment.
With the knowledge of IoT SDK, we can discuss how to connect an IoT device to the cloud.
With the development of high-performance hardware, many smart devices have complete OS
such as Linux, Android etc. These devices also have a Wi-Fi or cellular network.
At the operating system level, network communication problems have already been resolved.
We only need to develop applications which integrate the IoT SDK of the cloud platform and
the communication link with the cloud will have been established.
Examples of smart devices include smart phones, tablets, smart wearables, smart POS,
computers, industrial gateways and development boards like the Raspberry Pi and ESP32.
263 | P a g e
lOMoAR cPSD| 26885763
In the IoT scenario, a large number of devices are resource-constrained, with RTOS, or even
without an operating system, using MCU + communication modules to establish their link to
the cloud.
There are many suppliers of cellular modules (NB-IoT/2G/3G/4G) on the market. The AT
commands of each company are different, which makes developing device-side applications
very difficult.
When we need to connect MCU to an IoT Platform, we should always carefully select the
cellular modules and check whether they are suitable for a specific IoT platform.
The industrial gateway has the functions of collecting data from field devices through
serial port or network port. Data collection, protocol analysis, data standardization and
uploading to the IoT platform through edge computing functions. Which is more flexible,
powerful and customizable than DTU, but it is more expensive and needs more resources to
maintain.
Examples of sensors / devices which can be connected to DTU or industrial gateway include
sensors, industrial equipment PLCs (Programmable Logic Controller), Bluetooth bracelets
264 | P a g e
lOMoAR cPSD| 26885763
For some devices, they already have the ability to connect to the internet, but the protocols
vary according to device manufacturers. We don’t want the IoT platform layer to handle the
parsing of these protocols directly;an intermediate layer should satisfy the protocol
conversion work to make the data meet the unified format of the IoT platform.
This intermediate layer is the cloud gateway. The cloud gateway is at the front of the
platform. It receives data from the device side, completes message parsing, and then sends a
message to the IoT platform with IoT device SDK.
Examples of devices that connect to the internet through private protocol include vehicle
GPS.
Some device vendors already provide a mature system which manages the devices and
provides API. In this case, we can have another form of cloud gateway: Cloud to cloud
connection. Making full use of the existing system will make the overall system more stable
and give clear rights and responsibilities.
Using a mature system will bring us higher development efficiency, but it’ll also introduce
another midware, which will increase communication time.
265 | P a g e