Cs3691-Iot Notes Material - 5uint Cover
Cs3691-Iot Notes Material - 5uint Cover
3024
COURSEOBJECTIVES:
Tolearntheinternalarchitectureandprogramming ofan embeddedprocessor.
TointroduceinterfacingI/Odevicestotheprocessor.
Tointroducetheevolutionofthe Internetof Things(IoT).
Tobuildasmalllow-
costembeddedandIoTsystemusingArduino/RaspberryPi/openplatform.
Toapplytheconceptof Internet ofThingsinrealworld scenario.
UNITI8-BITEMBEDDEDPROCESSOR
8- Bit Microcontroller – Architecture – Instruction Set and Programming –
ProgrammingParallelPorts– Timers and Serial Port – InterruptHandling.
UNITIIEMBEDDEDCPROGRAMMING
Memory And I/O Devices Interfacing – Programming Embedded Systems in C – Need
ForRTOS –Multiple Tasks and Processes – Context Switching – Priority Based
SchedulingPolicies.
UNITIIIIOTANDARDUINOPROGRAMMING
IntroductiontotheConceptof IoTDevices – IoTDevicesVersus
Computers – IoT Configurations – Basic Components – Introduction to Arduino – Types
ofArduino–ArduinoToolchain–ArduinoProgrammingStructure–Sketches–Pins–Input/Output
FromPins Using Sketches – Introduction to Arduino Shields – Integration ofSensorsand
ActuatorswithArduino.
UNITIVIOTCOMMUNICATIONANDOPENPLATFORMS
IoT Communication Models and APIs – IoT Communication Protocols – Bluetooth – WiFi –
ZigBee–GPS–GSMmodules–OpenPlatform(likeRaspberryPi)–Architecture–Programming –
Interfacing – Accessing GPIO Pins – Sending and Receiving Signals UsingGPIOPins –
Connecting to the Cloud.
UNITVAPPLICATIONSDEVELOPMENT
CompleteDesignofEmbeddedSystems–DevelopmentofIoTApplications–HomeAutomation–
Smart Agriculture– SmartCities – Smart Healthcare.
1|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
UNITI
8-BITEMBEDDEDPROCESSOR
8-BitMicrocontroller
Architecture
ProgrammingParallelPorts
Timersand SerialPort
InterruptHandling.
2|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
1.1. 8051Microcontroller
8051 microcontroller is an 8-bit microcontroller created in 1981 by Intel Corporation. It
hasan8-bit processor that simply means that it operates on 8-bit data at a time. It is among
themostpopularand commonly used microcontroller.
As it is an 8-bit microcontroller thus has 8-bit data bus, 16-bit address bus. Along with that,
itholds4 KB ROMwith128 bytes RAM.
1.1.1. WhataMicrocontrolleris?
Amicrocontrollerisanintegratedchipdesignedunder Very Large Scale
Integrationtechniquethatconsistsofaprocessorwithotherperipheralunitslikememory,I/Oport,ti
mer, decoder, ADC etc. A microcontroller is basically designed in such a way that all
theworkingperipherals areembedded in asinglechipwith theprocessor.
Any programmable device holds a processor, memory, I/O ports and timer within it. But
amicrocontroller contains all these components embedded in a single chip. This single-
chipmanagesthe overall operation ofthe device.
A microprocessor simply contains a CPU that processes the operations with the help of
otherperipheral units. Microprocessors are used where huge space is present to inbuilt a
largemotherboardlikein PCs.
1.2. Architectureof8051Microcontroller
Thefigurebelowrepresentsthearchitecturalblockdiagramof 8051microcontroller:
As we can see that several units are present in the above architecture. And every unit
isembedded to execute the desired operation. Let us now discuss the operation of each
unitpresentin the architecture.
1.2.1. Central processing unit (CPU): 8051 uses the 8-bit processor. This unit carries
outthe operation on 8-bit data. A processor is the heart of microcontroller. As the execution
oftheprogram stored inthememory isperformed bythe processor.
The unit performs arithmetic and logical operations on 8-bit data as it has ALU, with
internalregistersand program counters.
Several logical operations are performed by the ALU according to the program stored in
thememory.
The processor of 8051 microcontrollers possesses a special feature by which it can
processsingle bit or 8-bit data. This simply means that it has the ability to access each single
bit dataeitherto clear, set or moveetc. forany logical computation.
3|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Architectureof8051Microcontroller
1.2.2. Memory:Basically8051microcontrollerconsistsofon-
chipprogrammemoryi.e.,ROMand on-chip datamemory i.e.,RAM.
Letusfirstunderstand
ROM
8051microcontrollerhas4KBROMwith0000Hto0FFFHastheaddressablespace.Itis
completely a program or code memory that means used by the programmer to store
theprogramsthat areto be executed by themicrocontroller.
The operations that are executed by the device in which the microcontroller is present
arestored in the ROM of the memory at the time of fabrication. Hence cannot be changed
ormodified.
RAM
8051holdsa128bytesRAM.Basically,RAMisusedtostoredataoroperandsforonlyasmalltime
duration.Itcanbealteredanytimeaccordingtotheneedoftheuser.Itisalsoknown as the data
memoryas it stores the datatemporarily.
Out of the 128-byte RAM, first, 32 bytes is held by the working registers. Basically,
theseare 4 banks which separately has 8 registers. These registers are accessed either by
itsname or address. It is to be noted here that at a particular time only a single register
bankcanbeused.
4|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
As in 8051, the data and program memory i.e., RAM and ROM hold a definite
memoryspace.However,forsomeapplicationsthereexisttheneedforexternalmemorytoenhan
ce the memory space, thus external RAM, ROM/EPROM is used by the
8051microcontrollers.
1.2.3. Input/Outputport:8051consistsof4parallelportsof8biteachtherebyproviding
32input-outputpins.Allthe4portsfunctionbidirectionali.e.,eitherinputoroutputaccordingto
thesoftwarecontrol.
1.2.4. Timer and Control Unit: Timers are used to create a time gap or delay between
2events. 8051 microcontroller consists of 2 timers of 16 bit each by which the system
canproducetwo delayssimultaneouslyin order togenerate theappropriatedelay.
1.2.5. 8051FlagBitsandPSWRegister
The program status word (PSW) register is an 8-bit register, also known as flag register. It
isof8-bit widebutonly 6-bit of itis used. Thetwounused bits areuser-definedflags.
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
meantfor pointing to data. It is used by the 8051 to access external memory using the
addressindicatedby DPTR.
5|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
DescriptionofthePins:
Pin 1 to Pin 8 (Port 1) – Pin 1 to Pin 8 are assigned to Port 1 for simple I/O
operations.They can be configured as input or output pins depending on the logic control
i.e. if logiczero (0) is applied to the I/O port it will act as an output pin and if logic one
(1) is appliedthe pin will act as an input pin. These pins are also referred to as P1.0 to
P1.7 (where P1indicates that it is a pin in port 1 and the number after ‘.’ tells the pin
number i.e. 0indicates first pin of the port. So, P1.0 means first pin of port 1, P1.1 means
second pin oftheport 1 and so on). Thesepins arebidirectionalpins.
Pin 9 (RST) – Reset pin. It is an active-high, input pin. Therefore if the RST pin is
highfor a minimum of 2 machine cycles, the microcontroller will reset i.e. it will close
andterminate all activities. It is often referred as “power-on-reset” pin because it is used
toresetthemicrocontroller to it’s initialvalueswhen poweris on (high).
Pin 10 to Pin 17 (Port 3) – Pin 10 to pin 17 are port 3 pins which are also referred to
asP3.0 to P3.7. These pins are similar to port 1 and can be used as universal input or
outputpins. These pins are bidirectional pins. These pins also have some additional
functionswhichare as follows:
P3.0 (RXD) : 10th pin is RXD (serial data receive pin) which is for serial input.
Throughthisinput signalmicrocontroller receivesdatafor serialcommunication.
P3.1 (TXD) : 11th pin is TXD (serial data transmit pin) which is serial output
pin.Throughthisoutputsignalmicrocontroller transmitsdataforserialcommunication.
6|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
P3.2andP3.3(INT0′,INT1′):12thand13thpinsareforExternalHardwareInterrupt0 and
Interrupt 1 respectively. When this interrupt is activated(i.e. when it is low), 8051gets
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
externalinput.They can beconnected with 16 bit timer/counter.
P3.6 (WR’) : 16th pin is for external memory write i.e. writing data to the
externalmemory.
P3.7(RD’): 17thpinisforexternalmemoryreadi.e.readingdatafromexternalmemory.
Pin 18 and Pin 19 (XTAL2 And XTAL1) – These pins are connected to an
externaloscillator which is generally a quartz crystal oscillator. They are used to provide
anexternalclock frequencyof 4MHzto 30MHz.
Pin 20 (GND) – This pin is connected to the ground. It has to be provided with 0V
powersupply.Henceit is connected to thenegativeterminal of thepower supply.
Pin 21 to Pin 28 (Port 2) – Pin 21 to pin 28 are port 2 pins also referred to as P2.0
toP2.7. When additional external memory is interfaced with the 8051 microcontroller,
pinsofport 2 actas higher-order address bytes.Thesepins arebidirectional.
Pin29(PSEN)–PSENstandsforProgramStoreEnable.Itisoutput,active-lowpin.This is used
to read external memory. In 8031 based system where external ROM holdstheprogram
code, this pin is connected to theOEpin of theROM.
Pin 30 (ALE/ PROG) – ALE stands for Address Latch Enable. It is input, active-
highpin. This pin is used to distinguish between memory chips when multiple memory
chipsare used. It is also used to de-multiplex the multiplexed address and data signals
availableat port 0.Duringflashprogramming i.e. Programming of EPROM, this pin
actsasprogrampulseinput (PROG).
Pin 31 (EA/ VPP) – EA stands for External Access input. It is used to
enable/disableexternal memory interfacing. In 8051, EA is connected to Vcc as it comes
with on-chipROM to store programs. For other family members such as 8031 and 8032 in
which thereisno on-chip ROM, theEApin is connected to theGND.
Pin 32 to Pin 39 (Port 0) – Pin 32 to pin 39 are port 0 pins also referred to as P0.0
toP0.7. They are bidirectional input/output pins. They don’t have any internal pull-
ups.Hence, 10 K? pull-up registers are used as external pull-ups. Port 0 is also designated
asAD0-AD7because8051multiplexes address and data throughport 0 tosavepins.
Pin 40(VCC)–Thispin providespowersupply voltagei.e. +5Voltsto the circuit.
7|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
displays, and communication modules. The pin diagram provides the information
aboutthelocation ofthesepins, theirfunctionalities,and theirelectrical characteristics.
2. Programmingthemicrocontroller:
The8051microcontrollercanbeprogrammedusingvariousprogramminglanguagessuchasAss
embly,C,andBASIC.Thepindiagram provides the information about the pins that are used
for programming themicrocontroller,suchas the PSENpin and theALE pin.
3. Debugging and testing: The pin diagram provides access to the internal signals of
themicrocontroller, such as the address and data buses, which can be used for debugging
andtestingthemicrocontroller.Specialhardwaretoolssuchaslogicanalyzersandoscilloscopes
can be connected to the pins to monitor the signals and diagnose any issuesin thesystem.
4. Expansion and customization: The pin diagram provides the flexibility to expand
andcustomize the functionality of the microcontroller by connecting external devices
andperipherals. For example, additional memory can be added by connecting external
RAMorROM chips to the address and databuses.
1.2.8. Characteristicsof8051Microcontroller
1. An8-bitprocessor.
2. Datamemory orRAMof128 bytes.
3. ProgrammemoryorROMof 4KB.
4. 2timersof16bit each.
5. 8-bitdatabus.
6. 16-bitaddressbus.
7. Offersbitaddressableformat.
8. Specialfunctionregistersandserialport.
9. 32 input/output lines.
1.3. 8051ProgramminginAssemblyLanguage
The assembly language is a low-level programming language used to write program code
interms of mnemonics. Even though there are many high-level languages that are currently
indemand, assembly programming language is popularly used in many applications. It can
beusedfordirecthardwaremanipulations.Itisalsousedtowritethe
8051programmingcodeefficientlywithlessnumberofclockcyclesbyconsuminglessmemorycom
paredtotheother high-level languages.
1.3.1. 8051ProgramminginAssemblyLanguage
The assembly language is a fully hardware related programming language. The
embeddeddesigners must have sufficient knowledge on hardware of particular processor or
controllersbefore writing the program. The assembly language is developed by mnemonics;
therefore,userscannot understand it easily to modify the program.
8|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
8051ProgramminginAssemblyLanguage
Microcontrollersorprocessorscanunderstandonlybinarylanguageintheformof‘0sor1s’;Anassem
blerconvertstheassemblylanguagetobinarylanguage,andthenstoresitinthemicrocontrollermemo
ry to perform the specifictask.
1.3.2. 8051MicrocontrollerArchitecture
The 8051 microcontroller is the CISC based Harvard architecture, and it has peripherals
like32 I/O, timers/counters, serial communication and memories. The microcontroller
requires
aprogramtoperformtheoperationsthatrequireamemoryforsavingandtoreadthefunctions.The805
1 microcontroller consists of RAMandROMmemoriestostoreinstructions.
9|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
8051MicrocontrollerArchitecuture
A Register is the main part in the processors and microcontrollers which is contained in
thememory that provides a faster way of collecting and storing the data. The 8051
assemblylanguage programming is based on the memory registers. If we want to manipulate
data to aprocessor or controller by performing subtraction, addition, etc., we cannot do that
directly inthe memory, but it needs registers to process and to store the data. Microcontrollers
containseveral types of registers that can be classified according to their instructions or
content thatoperatein them.
1.3.3. 8051MicrocontrollerProgramsinAssemblyLanguage
Theassemblylanguageismadeupofelementswhichallareusedtowritetheprograminsequentialma
nner.Followthe givenrulestowriteprogramminginassemblylanguage.
1.3.3.1. RulesofAssemblyLanguage
Theassemblycodemustbewritteninuppercase letters
Thelabelsmustbefollowedbyacolon(label:)
Allsymbols andlabels mustbegin with aletter
Allcomments aretyped in lower case
Thelast lineoftheprogram must betheEND directive
10|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
The assembly language mnemonics are in the form of op-code, such as MOV, ADD,
JMP,andso on, which areused to perform theoperations.
Op-code:Theop-codeisasingleinstructionthatcanbeexecutedbytheCPU.Heretheop-codeis a
MOVinstruction.
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
theoperand.
Syntax:MUL a,b;
1.3.4. TheElementsofanAssemblyLanguageProgramming:
AssemblerDirectives
InstructionSet
AddressingModes
1.3.4.1. AssemblerDirectives:
The assembling directives give the directions to the CPU. The 8051 microcontroller
consistsof various kinds of assembly directives to give the direction to the control unit. The
mostusefuldirectivesare8051 programming, such as:
ORG
DB
EQU
END
ORG(origin): This directive indicates the start of the program. This is used to set the
registeraddress during assembly. For example; ORG 0000h tells the compiler all subsequent
codestartingat address 0000h.
Syntax:ORG 0000h
11|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
(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”
bytheDB directly with doublequotes.
Syntax:ORG
0000hMOVa,
#00h
————-
————-
DB”EDGEFX”
EQU(equivalent):Theequivalentdirectiveisusedtoequate addressofthevariable.
Syntax:
regequ,09h
—————–
—————–
MOVreg,#2h
ImmediateAddressingMode
12|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
The above instruction and its execution. The opcode 74H is saved at 0202 address. The
data6AHissavedat0203addressintheprogrammemory.Afterreadingtheopcode74H,thedata at
the next program memory address is transferred to accumulator A (E0H is the addressof
accumulator). Since the instruction is of 2-bytes and is executed in one cycle, the
programcounterwill beincremented by 2 andwill point to 0204 of theprogrammemory.
Note − The '#' symbol before 6AH indicates that the operand is a data (8 bit). In the
absenceof'#', the hexadecimal numberwould betakenasan address.
DirectAddressingMode
This is another way of addressing an operand. Here, the address of the data (source data)
isgivenasan operand. Let’stakean example.
MOVA, 04H
Theregisterbank#0(4thregister)hastheaddress04H.WhentheMOVinstructionisexecuted, the
data stored in register 04H is moved to the accumulator. As the register 04Hholdsthe data
1FH, 1FHis moved to theaccumulator.
13|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Note − We have not used '#' in direct addressing mode, unlike immediate mode. If we
hadused'#',the datavalue 04Hwould havebeen transferredto theaccumulator insteadof 1FH.
Now,takealookatthefollowingillustration. Itshowshowtheinstructiongetsexecuted.
As shown in the above illustration, this is a 2-byte instruction which requires 1 cycle
tocomplete. The PC will be incremented by 2 and will point to 0204. The opcode for
theinstruction MOV A, address is E5H. When the instruction at 0202 is executed (E5H),
theaccumulatorismadeactiveandreadytoreceivedata.ThenthePCgoestothenextaddressas 0203
and looks up the address of the location of 04H where the source data (to betransferred to
accumulator) is located. At 04H, the control finds the data 1F and transfers it
totheaccumulatorand hencethe execution is completed.
RegisterDirectAddressingMode
In this addressing mode, we use the register name directly (as source operand). Let us try
tounderstandwith thehelpof an example.
MOVA, R4
Atatime,theregisterscantakevaluesfromR0toR7.Thereare32suchregisters.Inorderto use 32
registers with just 8 variables to address registers, register banks are used. There
are4registerbanksnamedfrom0to3.Eachbankcomprisesof8registersnamedfromR0toR7.
14|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
At a time, a single register bank can be selected. Selection of a register bank is made
possiblethrough a Special Function Register (SFR) named Processor Status Word (PSW).
PSW isan 8-bit SFR where each bit can be programmed as required. Bits are designated from
PSW.0toPSW.7. PSW.3 and PSW.4 areused to selectregister banks.
Now,takealookatthefollowingillustrationto getaclear understandingofhowitworks.
Opcode EC is used for MOV A, R4. The opcode is stored at the address 0202 and when it
isexecuted, the control goes directly to R4 of the respected register bank (that is selected
inPSW). If register bank#0 isselected, then the data fromR4 of register bank #0 willbemoved
to the accumulator. Here 2F is stored at 04H. 04H represents the address of R4
ofregisterbank #0.
Data (2F) movement is highlighted in bold. 2F is getting transferred to the accumulator
fromdata memory location 0C H and is shown as dotted line. 0CH is the address location
ofRegister 4 (R4) of register bank #1. The instruction above is 1 byte and requires 1 cycle
forcomplete execution. What it means is, you can save program memory by using register
directaddressingmode.
RegisterIndirectAddressingMode
In this addressing mode, the address of the data is stored in the register as
operand.MOVA, @R0
15|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
HerethevalueinsideR0isconsideredasanaddress,whichholdsthedatatobetransferredto the
accumulator. Example: If R0 has the value 20H, and data 2FH is stored at the
address20H,thenthevalue2FHwillgettransferredtotheaccumulatorafterexecutingthisinstruction
.Seethe following illustration.
So the opcode for MOV A, @R0 is E6H. Assuming that the register bank #0 is selected,
theR0ofregisterbank#0holdsthedata20H.Programcontrolmovesto20Hwhereitlocatesthe data
2FH and it transfers 2FH to the accumulator. This is a 1-byte instruction and
theprogramcounter increments by 1 and movesto 0203 of theprogram memory.
Note − Only R0 and R1are allowed toform aregister indirect addressing instruction.Inother
words, the programmer can create an instruction either using @R0 or @R1. All
registerbanksare allowed.
IndexedAddressingMode
16|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
We will take two examples to understand the concept of indexed addressing mode. Take
alookat the following instructions −
MOVCA,@A+DPTR
and
MOVCA,@A+PC
where DPTR is the data pointer and PC is the program counter (both are 16-bit
registers).Considerthefirst example.
MOVCA,@A+DPTR
The source operand is @A+DPTR. It contains the source data from this location. Here we
areadding the contents of DPTR with the current content of the accumulator. This addition
willgiveanewaddresswhichistheaddressofthesourcedata.Thedatapointedbythisaddressisthen
transferred to theaccumulator.
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-
bitadditionisperformedand01FEH+02Hresultsin0200H.Dataatthelocation0200Hwillget
transferred to the accumulator. The previous value inside the accumulator (02H) will
bereplacedwiththenewdatafrom0200H.Thenewdataintheaccumulatorishighlightedinthe
illustration.
17|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
This is a 1-byte instruction with 2 cycles needed for execution and the execution
timerequired for this instruction is high compared to previous instructions (which were all 1
cycleeach).
The other example MOVC A, @A+PC works the same way as the above example.Insteadof
adding DPTR with the accumulator, here thedata inside the program counter (PC)
isaddedwith theaccumulator to obtain thetarget address.
1.3.4.3. InstructionSet
Loopingin the8051
Repeating a sequence of instructions a certain number of times is called a loop. The loop
isone of most widely used actions that any microprocessor performs. In the 8051, the
loopaction is performed by the instruction “DJNZ reg, label”. In this instruction, the register
isdecremented; if it is not zero, it jumps to the target address referred to by the label. Prior
tothe start of the loop the register is loaded with the counter for the number of
repetitions.Notice that in this instruction both the register decrement and the decision to jump
arecombinedinto asingleinstruction.
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,itjumpstothetargetaddressassociatedwiththelabel“AGAIN”.Thisloopingactioncontinues
until R2 becomes zero. After R2 becomes zero, it falls through the loop andexecutes 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 alsobeaRAM
location
18|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Loopinsidea loop
As shown in Example the maximum count is 256. What happens if we want to repeat
anaction more times than 256? To do that, we use a loop inside a loop, which is called a
nestedloop.In anested loop, weusetwo registers to holdthecount.
Example
Writeaprogramto(a)loadtheaccumulatorwiththevalue55H,and(b)complementtheACC 700
times.
Solution:
Since700islargerthan255(themaximumcapacityofanyregister),weusetworegisterstoholdthecou
nt. Thefollowing codeshows how touseR2 and R3 forthe count.
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.
Thisinstruction forces the CPU to load R2 with the count 70 and the inner loop starts again.
Thisprocesswill continue until R3becomes zeroand the outerloop is finished.
Otherconditionaljumps
Conditionaljumpsforthe8051aresummarizedinTable3-1.Moredetailsofeachinstruction are
provided in Appendix A. In Table 3-1, notice that some of the instructions,such as JZ (jump
if A = zero) and JC (jump if carry), jump only if a certain condition is
met.Nextweexaminesomeconditional jumpinstructions with examples.
JZ(jump if A= 0)
19|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
In this program,. if either RO or Rl is zero, it jumps to the label OVER. Notice that the
JZinstruction can be used only for register A. It can only check to see whether the
accumulatoris zero, and it does not apply to any other register. More importantly, you don’t
have toperform an arithmetic instruction such as decrement to use the JNZ instruction. See
Example3-4.
Example
20|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
There are also JB (jump if bit is high) and JNB (jump if bit is low) instructions. These
arediscussedin Chapters 4 and 8when bit manipulation instructions arediscussed.
Allconditionaljumpsareshortjumps
It must be noted that all conditional jumps are short jumps, meaning that the address of
thetarget must be within -128 to +127 bytes of the contents of the program counter (PC).
Thisveryimportant concept is discussed at theend ofthis section.
Unconditionaljumpinstructions
The unconditional jump is a jump in which control is transferred unconditionally to the
targetlocation. In the 8051 there are two unconditional jumps: LJMP (long jump) and SJMP
(shortjump).Each is discussedbelow.
SJMP(shortjump)
In this 2-byte instruction, the first byte is the opcode and the second byte is the
relativeaddress of the target location. The relative address range of 00 – FFH is divided into
forwardand backward jumps; that is, within -128 to +127 bytes of memory relative to the
address ofthe current PC (program counter). If the jump is forward, the target address can be
within aspace of 127 bytes from the current PC. If the target address is backward, the target
addresscanbewithin -128 bytes from thecurrent PC. Thisis explained in detail next.
Calculatingtheshortjumpaddress
Inaddition to the SJMP instruction, all conditional jumps such as JNC,JZ, and DJNZarealso
short jumps due to the fact that they are all two-byte instructions. Inthese instructionsthe first
byte is the opcode and the second byte is the relative address. The target address
isrelativetothevalueoftheprogramcounter.Tocalculatethetargetaddress,thesecondbyteisadded
to thePC of theinstruction immediately belowthe jump.
ShiftingOperators
21|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
The shift operators are used for sending and receiving the data efficiently.
The8051microcontrollerconsist fourshift operators:
RR —>RotateRight
RRC—>RotateRightthroughcarry
RL—>RotateLeft
RLC—>RotateLeftthroughcarry
RotateRight(RR):
In this shifting operation, the MSB becomes LSB and all bits shift towards right side bit-by-
bit,serially.
Syntax:
MOV A,
#25hRR A
RotateLeft(RL):
In this shifting operation, the MSB becomes LSB and all bits shift towards Left side bit-by-
bit,serially.
Syntax:
MOV A,
#25hRL A
RRCRotateRightthroughCarry:
In this shifting operation, the LSB moves to carry and the carry becomes MSB, and all
thebitsareshift towards right sidebit by bit position.
Syntax:MOV
A, #27hRRC
A
22|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
RLCRotateLeftthroughCarry:
In this shifting operation, the MSB moves to carry and the carry becomes LSB and all
thebitsshift towards left side in abit-by-bit position.
Syntax:
MOV A,
#27hRLC A
BasicEmbeddedC Programs:
The microcontroller programming differs for each type of operating system. There are
manyoperating systems such as Linux, Windows, RTOS and so on. However, RTOS has
severaladvantages for embedded system development.Some of the Assembly levels
programmingexamplesaregiven below.
LEDprogramswith8051Microcontrller
1.WAPto togglethePORT1LEDs
ORG0000H
TOGLE:MOVP1, #01 //move 00000001 to the p1
register//CALLDELAY //execute thedelay//
MOVA, P1 //move p1 value to the
accumulator//CPLA //complement A value //
MOVP1, A //move 11111110 to the port1
register//CALLDELAY //execute thedelay//
SJMP TOGLE
DELAY:MOVR5, #10H //load register R5 with
10//TWO: MOVR6, #200 //load register R6
with 200//ONE: MOVR7, #200 //load
register R7 with 200//DJNZR7, $ //decrement R7
tillit is zero//
DJNZR6, ONE //decrement R7 till it is
zero//DJNZR5,TWO //decrement R7
till it is zero//RET //go back to the main
program //END
1.4. ProgrammingParallelport
1.4.1. 8051Microcontrollerportprogramming
23|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
There are four ports P0, P1, P2andP3 eachuse8 pins,makingthem 8-bitports. All the portsuponRESET
are configured as output, ready to be used as output ports. To use any of these ports asaninputport,
itmustbe programmed.
1.4.2. Pinconfigurationof8051/8031microcontroller.
Pinconfigurationof8951
Port 0: Port 0 occupies a total of 8 pins (pins 32-39) .It can be used for input or output. To use
thepins of port 0 as both input and output ports, each pin must be connected externally to a 10K
ohmpull-up resistor. This is due to the fact that P0 is an open drain, unlike P1, P2, and P3.Open
drainis aterm used for MOS chips in the same way that open collector is used for TTL chips. With
externalpull-up resistors connected upon reset, port 0 is configured as an output port. For example,
thefollowingcode will continuouslysendoutto port 0 thealternatingvalues 55HandAAH
MOV
A,#55HBACK:MO
V P0,AACALL
DELAYCPLA
SJMP BACK
24|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Port 0 as Input : With resistors connected to port 0, in order to make it an input, the port must
beprogrammed by writing 1 to all the bits. In the following code, port 0 is configured first as an
inputportby writing 1’stoit, and thendatais receivedfromtheportandsenttoP1.
8051I/OPorts
MOVA,#0FFH ;A=FFhex
MOVP0,A ; make P0 an input
portBACK:MOVA,P0
;getdatafromP0MOVP1,A ;senditto port1
SJMP BACK
Dual role of port 0: Port 0 is also designated as AD0-AD7, allowing it to be used for both
addressand 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 ordata. When ALE = 0, it provides data D0-D7, but when ALE =1 it has address and data
with the helpof a 74LS373latch.
Port 1: Port 1 occupies a total of 8 pins (pins 1 through 8). It can be used as input or output.
Incontrast to port 0, this port does not need any pull-up resistors since it already has pull-up
resistorsinternally. Upon reset, Port 1 is configured as an output port. For example, the following code
willcontinuouslysendoutto port1thealternatingvalues55h&AAh
MOVA,#55H ;A=55hex
BACK: MOVP1,A ;send it to Port
1ACALLDELAY ;calldelayroutine
CPLA ;makeA=0
SJMP BACK
Port 1 as input: To make port1 an input port, it must programmed as such by writing 1 to all its
bits.In the following code port1 is configured first as an input port by writing 1’s to it, then data
isreceivedfromthe portandsavedin R7 ,R6&R5.
MOVA,#0FFH;A=FF HEX
MOVP1,A ;make P1 an input port by writing all 1’s to
itMOVA,P1 ;getdata fromP1
25|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
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,Port2isconfiguredasanoutputport.Forexample,thefollowingcodewillsendoutcontinuouslytoport2t
healternatingvalues 55handAAH. Thatisallthebits of port2togglecontinuously.
MOVA,#55H ;A=55hex
BACK:MOVP2,A ;send it to Port
2ACALLDELAY ;call delay
routineCPLA ;makeA=0
SJMPBACK
Port 2 as input : To make port 2 an input, it must programme as such by writing 1 to all its bits.
Inthefollowing code,port2 isconfiguredfirstasan inputportby writing 1’sto it. Thendata
isreceivedfromthatportandis sentto P1continuously.
MOVA,#0FFH ;A=FFhex
MOVP2,A ;make P2 an input port by writing all 1’s to
itBACK: MOVA,P2 ;getdatafromP2
MOVP1,A ;senditto Port1
SJMP BACK ;keepdoingthat
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
forthe 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, itneeds a path for the 16 bits of the address. While P0 provides the lower 8 bits via A0-A7, it
is the jobof P2 to provide bits A8-A15 of the address. In other words, when 8031 is connected to
externalmemory,P2 is used fortheupper8 bitsof the 16bit address, anditcannotbe usedfor I/O.
Port3:Port3occupiesatotalof8pins,pins10through17.Itcanbeusedasinputoroutput.P3doesnotneedanypu
ll-upresistors,thesameasP1andP2didnot.Althoughport3isconfiguredasan output port upon reset. Port 3
has the additional function of providing some extremely importantsignalssuchasinterrupts.
Thisinformationappliesboth 8051 and8031chips.
26|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
MOVP1,#55H ;P1=01010101
AGAIN: XLR P1,#0FFH;EX-OR P1 with 1111
1111ACALLDELAY
SJMPAGAIN
The first step is to load the two numbers into two different ports. For example, we
canload the first number into port P1 and the second number into port P2. We can use the
MOVinstructionto load the numbers into theports.
Oncethenumbersareloadedintotheports,wecanusetheADDinstructiontoaddthetwonumb
ers.TheADDinstructionaddsthecontentsoftheaccumulatorandthespecified operand and stores
the result in the accumulator. Since the two numbers are alreadyloaded into the ports, we can
simply use the ADD instruction with the accumulator and theappropriateport.
After the addition is complete, we can retrieve the result from the accumulator
andstoreitinanotherportormemorylocationforfurtherprocessingordisplay.8051microcontroller
is a microcontroller designed by Intel in 1981. It is an 8-bit microcontrollerwith 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 asaddressable as perthe
requirement.
IssuesinAddition oftwo8-bitnumbers8051MicrocontrollerUsingPorts:
There are severalissuesthat can arise when performingadditionof two 8-
bitnumbersin8051microcontroller using ports:
1. Overflow: If the result of the addition exceeds 8 bits, the carry flag (CY) in the
programstatus word (PSW) will be set. If this flag is not checked before storing the result,
theresultmay beincorrect.
2. Input validation: Before performing the addition, it is important to validate the input
toensure that the numbers are within the range of 0 to 255. If the input is not validated,
theresultmay beincorrect.
3. Port initialization: The ports used for input and output must be properly initialized
beforeuse.Iftheportsarenotproperlyinitialized, thedatamaynot betransferredcorrectly.
4. Endianness: The order in which the bytes of the numbers are stored in memory can
affectthe result of the addition. It is important to ensure that the bytes are stored in the
correctorderbeforeperforming theaddition.
5. Interrupts:If interruptsare enabled during the addition operation, the result may
beaffected. It is important to disable interrupts during critical operations to ensure
thecorrectresult.
27|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
6. Timing:Thetimingoftheadditionoperationcanaffecttheresult.Itisimportanttoensurethatthen
ecessarydelaysareaddedbetweeninstructionstoensurecorrectoperation.
7. Code optimization: The code used to perform the addition should be optimized to
ensurethat it uses the least number of instructions and takes the least amount of time. This
isimportant to avoid potential timing issues and to ensure that the microcontroller
canperformother tasks whilethe additionis being performed.
Problem:Towriteanassemblylanguageprogramtoaddtwo8bitnumbersin8051microcontrollerus
ing ports.
Example:
Blockdiagram:
Algorithm:
InitializePortsP0and P1asinputports.
InitializePortsP2and P3asoutputports.
InitializetheR1register.
28|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
MovethecontentsfromPort0toBregister.
MovethecontentsfromPort1toAregister.
Addcontentsin AandB.
Ifcarryispresentincrement R1.
Movecontentsin R1 to Port 2.
Movethesum in step 6 to Port 3.
Program:
ORG00H //Indicatesstartingaddress
Explanation:
ORG00His thestartingaddress oftheprogram.
Givingthevaluesas#0FFHand#00Hinitializestheportsasinputandoutputportsrespectively.
R1registeris initializedto0 soasto storeany carryproducedduring thesum.
MOVB,P0 movesthevalue presentin P0totheBregister.
MOVA, P1moves thevalue presentin P1 toAccumulator.
ADDABaddsthevaluespresentinAccumulatorandBregisterandstorestheresultinAccumulat
or.
JNCL2referstojumptolabelL2ifnocarryispresentbyautomaticallycheckingwhetherthecarry
bit is set ornot.
Ifthecarrybitis settoincrementregisterR1.
MOVP2,R1,andMOVP3,AreferstomovingthecarrybittoP2andresultinAccumulatorto P3.
29|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
1.5. 8051Timers
1.5.1. Introductionto8051Timers
8051microcontrollershavetwotimersandcounterswhichworkontheclockfrequency.
Timer/countercan be used for time delay generation, counting external events,etc.
8051Clock
Every Timer needs a clock to work, and8051 provides it from an external crystal which isthe
main clock source for Timer. The internal circuitry in the 8051 microcontrollers providesa
clock source to the timers which is 1/12th of the frequency of crystal attached to
themicrocontroller,alsocalled Machinecycle frequency.
8051Timer Clock
Forexample,supposewehaveacrystalfrequencyof11.0592MHzthenthemicrocontrollerwillprovi
de 1/12th i.e.
Timer clock frequency=(Xtal Osc.frequency)/12=(11.0592 MHz)/12= 921.6
KHzperiodT=1/(921.6 kHz)=1.085 μS
1.5.2. 8051Timer
8051hastwotimersTimer0(T0)andTimer1(T1),bothare16-bitwide.Since8051has8-bit
architecture, each of these is accessed by two separate 8-bit registers as shown in
thefigurebelow. Theseregisters areused to load timer count.
8051 has a Timer Mode Register and Timer Control Register for selecting a mode of
operation and controlling purpose.
Let'sseetheseregisters,
1.5.2.1. TMODregister
TMODisan8-bitregisterusedto settimermodeoftimer0andtimer1.
30|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
1.5.2.2. TCONRegister
TCONisan8-bitcontrolregisterandcontainsatimerandinterruptflags.
Bit7-TF1:Timer1OverflowFlag
1=Timer1overflowoccurred(i.e.Timer1goes toitsmaxandrolloverbacktozero).
0=Timer1 overflownotoccurred.
Itisclearedthroughsoftware.IntheTimer1overflowinterruptserviceroutine,thisbitwillgetcleared
automatically while exiting fromISR.
Bit5–TF0:Timer0OverflowFlag
1=Timer0overflowoccurred(i.e.Timer0goestoitsmax androlloverbacktozero).
31|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
0=Timer0 overflownotoccurred.
Itisclearedthroughsoftware.IntheTimer0overflowinterruptserviceroutine,thisbitwillgetcleared
automatically while exitingfromISR.
Bit2-
IT1:ExternalInterrupt1TriggerTypeSelectBit1=In
terruptoccursonfallingedgeatINT1pin.0=Interrupt
occuronalowlevelatthe INT1pin.
Let'sseethe timersmodes
1.5.3. 8051TimerModes
TimershavetheiroperationmodeswhichareselectedintheTMODregisterusingM0&M1bitcombi
nations.
Mode0(13-bittimermode)
TheMode0operationisthe8-bittimerorcounterwitha5-bitpre-scaler.Soitisa13-bittimer/counter.
It uses 5 bitsof TL0 orTL1 andallof the8-bits ofTH0 orTH1.
Inthisexample
theTimer1isselected,inthiscase,every32(25)eventforcounteroperationsor32machinecyclesforti
meroperation,theTH1registerwillbeincrementedby1.When
32|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
the TH1overflows from FFH to 00H, then the TF1 of TCON register will be high, and
itstops the timer/counter. So for an example, we can say that if the TH1 is holding F0H, and
itisin timermode, then TF1will behigh after10H *32 =512machinecycles.
MOVTMOD,
#00HMOVTH1,
#0F0HMOVIE,
#88HSETB TR1
In the above program, the Timer1 is configured as timer mode 0. In this case Gate = 0.
Thenthe TH1 will be loaded with F0H, then enable the Timer1 interrupt. At last set the TR1
ofTCONregister,and startthe timer.
Mode1(16-bittimermode)
The Mode 1 operation is the 16-bit timer or counter. In the following diagram, we are
usingMode1forTimer0.
In this case every event for counter operations or machine cycles for timer operation,
theTH0– TL0 register-pair will be incremented by 1. When the register pair overflows
fromFFFFHto0000H,thentheTF0ofTCONregisterwillbehigh,anditstopsthetimer/counter. So
for an example, we can say that if the TH0 – TL0 register pair is holdingFFF0H, and it is in
timer mode, then TF0 will be high after 10H = 16 machine cycles. Whenthe clock frequency
is 12MHz, then the following instructions generate an interrupt 16 µsafterTimer0 starts
running.
MOVTMOD,
#01HMOVTL0,
#0F0HMOVTH0,
#0FFHMOVIE,
#82HSETB TR0
In the above program, the Timer0 is configured as timer mode 1. In this case Gate = 0.
Thenthe TL0 will be loaded with F0H and TH0 is loaded with FFH, then enable the
Timer0interrupt.At last set theTR0of TCONregister,and startthetimer.
Mode2(8-bitauto-reloadtimermode)
33|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
The Mode 2 operation is the 8-bit auto reload timer or counter. In the following diagram,
weareusingMode2 for Timer1.
In this case every event for counter operations or machine cycles for timer operation,
theTL1register 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 ofTH1and starts the operation again.
So for an example, we can say that if the TH1 and TL1 register both are holding F0H and
itis in timer mode, then TF1 will be high after 10H= 16 machine cycles. When the
clockfrequency is 12MHz this happens after 16 µs, then the following instructions generate
aninterruptonce every 16µs after Timer1 starts running.
MOVTMOD,
#20HMOVTL1,
#0F0HMOVTH1,
#0F0HMOVIE,
#88HSETBTR1
In the above program, the Timer1 is configured as timer mode 2. In this case Gate = 0.
Thenthe TL1 and TH1 are loaded with F0H. then enable the Timer1 interrupt. At last set the
TR1ofTCONregister,and start thetimer.
Mode3ofTimer/Counter
Mode 3 is different for Timer0 and Timer1. When the Timer0 is working in mode 3, the
TL0will be used as an 8-bit timer/counter. It will be controlled by the standard Timer0
controlbits, T0 and INT0 inputs. The TH0 is used as an 8-bit timer but not the counter. This
iscontrolledbyTimer1ControlbitTR1.WhentheTH0overflowsfromFFHto00H,thenTF1is set to
1.In the following diagram, we can Timer0 in Mode3.
34|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
When the Timer1 is working in Mode 3, it simply holds the count but does not run.
WhenTimer0 is in mode 3, the Timer1 is configured in one of the mode 0, 1 and 2. In this
case, theTimer1 cannotinterruptthe microcontroller. When the TF1 is used by TH0 timer,
theTimer1is used as BaudRate Generator.
Themeaningof gatebitin Timer0 andTimer1 formode3 isas follows
It controls the running of 8-bit timer/counter TL0 as like Mode 0, 1, or 2. The running
ofTH0 is controlled by TR1 bit only. So the gate bit in this mode for Timer0 has no
specificrole.
The mode 3 is present for applications requiring an extra 8-bit timer/counter. In Mode 3
ofTimer0, the 8051 has three timers. One 8-bit timer by TH0, another8-bit timer/counter
byTL0,and one16-bit timer/counterby Timer1.
If the Timer0 is in mode3, and Timer1 is working on either 0, 1 or 2, then the gun control
oftheTimer1isactivatedwhenthegatebitislowor INT1 ishigh.Theruncontrolisdeactivated when
the gate is high andINT1 is low.
1.6. SerialPortin8051
There is a serial port in 8051 as mentioned in the pin diagram of 8051. 8051 has capability
toperformparallel as well as serial communication.
Parallelcommunicationin8051:
8051 can do 8-bit parallel communication as it has 8-bit ALU. For parallel
communication,any of the ports ( P0 /P1 /P2 /P3 ) isused asa transmission channelbetween
transmitterandreceiver.
Serialcommunication in8051:
Forserialcommunicationtherearetwoseparate pinsknownas serialportof8051.
35|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
TxD:
This pin basically acts as a transmitter ( sending data ), but in some other modes it doesn’t
dothe 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
ofdata that is to be transmitted to SBUF and fromthere bit by bit is transferred ,firstly
LSBand then at last MSB of the byte stored in SBUF. Once the total byte is transmitted,
aninterrupt is sent to the processor by making some flag 1, so that the processor can send
moredatafor transmission as soon as the interrupt is received.
After every bit is transmitted, it requires delay for next bit transmission. So SBUF
needstriggeringwhich is provided by
Timer T1 ( here T1 only needs to trigger, T1 does not require its overflow flag ,
mode3 in timers ). Here we can vary the delay, so data transmission delay can be
varied (frequencycan bevaried ). It has avariable baudrate.
There is an internal clock in 8051 ( fosc / 12 = 1Mhz ) , where delay cannot be
varied,thishasfixedtrigger delay.Sofrequencycannotbevaried.It hasafixedbaud rate.
WheneverSBUFtransferred8bitofdata,T iflagbecomes1.WheneverprocessorsgotoISR( in other
interrupts the flag is auto cleared whenever processor goes to ISR ) , in this theTiflag is not
auto cleared.
RxD:
This pin is basically for data reception . It received data bit by bit ( as the transmitter
sendsLSB 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 (
errorscaused due to transmission). Once there is no error in the received information R i flag is
setand an interrupt is sent to the processor. Processor goes to ISR ( here also R i is not
clearedautomatically).
36|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
1.6.1. Modesinserialcommunication:
Mode1(8-bitUARTcommunication):
UART stands for universal asynchronous receiver-transmitter. It means receiver
andtransmitter are asynchronous which mean they don’t have a common clock. Normally 8
bitsaretransmitted through the channel,but in this mode10bits aretransmitted.
Herestartandstopbitsaresystemgenerated.
Significanceofstartandstop bit:
Foreg:Thereisatransmitterandreceiver.FirstC8H(11001000)dataistransmittedandthen for
10min there is no transmission and after that again 8EH ( 1000 1110 )is transmitted.Ifthereis
notransmission, last bit transmittedwould beremained inthechannel
Receiverassumesbluedata(whentherewasnocommunication )alsoasdata.
37|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
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
bitsand 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
thenext8 bits and so on ).
Stopbitisalsousedforerrorchecking.WheneverSM2=1,Itchecksforerror,IftheRB8=1(whichmea
nsstop=1received,sothedataisreceivedcorrectly)andifRB8=0(transmitter generated stop as 1,
but received as 0 ) so there is an error. If there is an error inreceiveddata, no interrupt is sent
to theprocessor.
The9thbitisaprogrammablebitanditisgiventhroughTB8.Here9thbitis1anditisusedforerrorcheck
ing and stop bit fortriggering the data high (so start bit gets 0 and so on ).
Why the 9th bit , when the already stop bit
exists?Standardvalue of9th bitis 1and
canbemade0.
38|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
WheneverSM2=1(receiveracceptsonlyerrorlessdata)andif9thbitis1,thenonlyerrorlessdata is
acceptedorelse discarded. Discarding datais a purpose.
Mode3(9-bitUARTcommunication):
Thismodeiscompletely similarto mode2,in mode2 fortriggering timerisused
Whereasinthismodeinternal clock isused fortriggering.Ithas afixed baudrate.
Mode0 :
Totally there were four modes in serial port of 8051, but for better understanding mode 0
isexplained after three modes. In this mode data is transferred and received only through
theRxDchannel. TxD is used forclocks. Thisis synchronous modeof communication.
Suchasystemisalsoknownashalfduplexmode.Ithas fixedbaudrate.
SCONregister:
SM0andSM1:
Theseareused toselect themode.
1.7. 8-BitInterrupts
39|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
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-
writtenfirmware routine called the Interrupt Service Routine (ISR). The ISR processes the
interruptevent,then resumes normal program flow.
Enableinterruptsfromselectedperipherals
Each peripheral on the MCU has an individual enable bit. A peripheral's individual
interruptenable bitmustbe set,inadditiontoGIE/PEIE,before the
peripheralcangenerateaninterrupt.TheindividualinterruptenablebitsarelocatedinINTCON,PIE1
,PIE2,andPIE3.
Peripheralassertsaninterruptrequest
When a peripheral reaches a state where program intervention is needed, the peripheral
setsan Interrupt Request Flag (xxIF). These interrupt flags are set regardless of the status of
theGIE, PEIE, and individual interrupt enable bits. The interrupt flags are located in
INTCON,PIR1,PIR2, and PIR3.
Theinterruptrequestflagsarelatchedhighwhensetandmustbeclearedbytheuser-writtenISR.
Interruptoccurs
Whenaninterruptrequestflagissetandtheinterruptisproperlyenabled,theinterruptprocessbegins:
1. GlobalInterruptsaredisabledby clearingGIEto0.
2. Thecurrentprogram contextissaved totheshadowregisters.
3. ThevalueoftheProgramCounterisstored onthereturnstack.
4. Programcontrolistransferredtotheinterruptvectorataddress04h.
ISRruns
TheISRisafunctionwrittenbytheuserandplacedataddress04h.TheISRdoesthefollowing:
1. Checkstheinterrupt-enabledperipherals forthesourceof theinterruptrequest.
2. Performsthenecessaryperipheraltasks.
3. Clearstheappropriateinterruptrequest flag.
4. ExecutestheReturn FromInterruptinstruction(RETFIE)asthefinal ISR instruction.
ControlisreturnedtotheMain program
WhenRETFIEisexecuted:
1. GlobalInterruptsareenabled(GIE=1).
40|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
GIE - GlobalInterruptEnablePeripheralI
PEIE- nterruptEnable
TMR0IE- Timer0 Interrupt
INTE- EnableExternalInterruptEnableI
IOCIE- nterruptonChangeEnable
TMR0IF- Timer0 Interrupt
INTF- flagExternalInterruptflagI
IOCIF- nterruptonChangeflag
INTCON contains global and peripheral interrupt enable flags as well as the
individualinterrupt request flags and interrupt enable flags for three of the PIC16F1xxxx
interrupts.InterruptEnable Registers
PIE1register
TMR1GIE- Timer1GateInterruptEnable
ADIE- Analog-to-DigitalConverter(ADC)InterruptEnable
RCIE- Universal Synchronous Asynchronous Receiver Tranmsitter (USART)
ReceiveInterruptEnable
TXIE- USARTTransmitInterruptEnable
SSPIE - Synchronous Serial Port (MSSP) Interrupt
CCP1IE- EnableCCP1Interrupt Enable
TMR2IE- Timer2 Interrupt
TMR1IE-
EnableTimer1Interrupt
Enable
PIE2register
41|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
----Unimplementedread as 0
CCP5IE- CCP5 Interrupt
CCP4IE- EnableCCP4 Interrupt
CCP3IE- EnableCCP3Interrupt
TMR6IE Enable
- Timer6 Interrupt
---- EnableUnimplemented, readas
0
TMR4IE-
Timer4InterruptEnable
----Unimplemented,read as 0
PIE1,PIE2,and PIE3 containtheindividualinterruptenableflagsforthe MCU's
peripherals.
InterruptRequestRegisters
PIR1register
FlagPIR3register
43|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
The INTEDG flag in OPTION_REG is used to set a rising or falling edge on the INT pin
asthetriggerfor anINTE interrupt.
Enabling
InterruptsCoreInte
rrupts
Three interrupt sources (Timer0, External Interrupt, and Interrupt on Change) have
interruptenablebits locatedinINTCON. Theseinterruptsarereferredtoascoreinterrupts.
44|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
UNITII
EMBEDDED C PROGRAMMING
ProgrammingEmbeddedSystemsin C
NeedFor RTOS
MultipleTasksand Processes
ContextSwitching
PriorityBased SchedulingPolicies
45|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
2.1. MemoryandI/OInterfacing
Several memory chips and I/O devices are connected to a microprocessor.The
followingfigureshowsaschematicdiagramtointerfacememorychipsandI/Odevicestoamicroproc
essor.
2.1.1. MemoryInterfacing
When we are executing any instruction, the address of memory location or an I/O device
issentoutbythemicroprocessor.ThecorrespondingmemorychiporI/Odeviceisselectedbyadecodi
ng circuit.
Memoryrequiressomesignalstoreadfromandwritetoregistersandmicroprocessortransmitssome
signals forreading orwriting data.
The interfacing process includes matching the memory requirements with the
microprocessorsignals.Therefore,theinterfacingcircuitshouldbedesignedinsuchawaythatitmatc
hesthememory signal requirements with the microprocessor's signals.
2.1.2. I/Ointerfacing
As we know, keyboard and displays are used as communication channel with outside
world.Therefore, it is necessary that we interface keyboard and displays with the
microprocessor.This is called I/O interfacing. For this type of interfacing, we use latches and
buffers forinterfacingthekeyboardsand displays withthe microprocessor.
But the main drawback of this interfacing is that the microprocessor can perform only
onefunction.
8051MicrocontrollerMemoryOrganization
46|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
In the 8051 Microcontroller, we have seen the 8051 Microcontroller Introduction and
Basics,PinDiagram,PinDescriptionandtheArchitectureoverview.wewillcontinueexploring805
1Microcontrollerbyunderstandingthe8051MicrocontrollerMemoryOrganization,ProgramMe
mory (ROM), DataMemory (RAM),External Memory.
Differencesbetweenmicroprocessorandmicrocontroller
Themaindifferencecanbestatedason-chipmemoryi.e.,aMicrocontrollerhasbothProgram
Memory(ROM) and Data Memory(RAM) on the same chip (IC), whereas
aMicroprocessorhas to beexternally interfacing withthememory modules.
Hence,itisclearthatthememoryisanimportantpartofthe8051MicrocontrollerArchitecture(forthat
matter,anyMicrocontroller).So,itisimportantforustounderstandthe 8051 Microcontroller
Memory Organization i.e., how memory is organized, how
theprocessoraccesseseachmemoryandhowtointerfaceexternalmemorywith8051Microcontrolle
r.
Beforegoingintothedetailsofthe8051MicrocontrollerMemoryOrganization,wewillfirstseealittl
ebitabouttheComputerArchitectureandthenproceedwithmemoryorganizationof8051
Microcontroller.
1.2.3. TypesofComputerArchitecture
Basically,Microprocessors or Microcontrollers are classifiedbasedonthe
twotypesofComputerArchitecture:VonNeumann ArchitectureandHarvardArchitecture.
VonNeumannArchitecture
Von Neumann Architecture or Princeton Architecture is a Computer Architecture, where
theProgrami.e.,theInstructionsandtheDataarestoredinasinglememory.SincetheInstruction
Memory and the Data Memory are the same, the Processor or CPU cannot accessboth
Instructions and Data at the same time as they use a single bus.This type of architecturehas
severe limitations to the performance of the system as it creates a bottleneck
whileaccessingthe memory.
47|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
HarvardArchitecture
Harvard Architecture, in contrast to Von Neumann Architecture, uses separate memory
forInstruction(Program)andData.SincetheInstructionMemoryandDataMemoryareseparate in a
Harvard Architecture, their signal paths i.e., buses are also different and hence,theCPU can
access bothInstructions and Dataatthesame time.
AlmostallMicrocontrollers,including8051MicrocontrollerimplementHarvardArchitecture.
1.2.4. 8051MicrocontrollerMemoryOrganization
The8051MicrocontrollerMemoryisseparatedinProgramMemory(ROM)andDataMemory
(RAM). The Program Memory of the 8051 Microcontroller is used for storing theprogram to
be executed i.e., instructions. The Data Memory on the other hand, is used
forstoringtemporary variable data and intermediateresults.
8051 Microcontroller has both Internal ROM and Internal RAM. If the internal memory
isinadequate,youcan addexternal memory using suitablecircuits.
1.2.4.1. ProgramMemory(ROM)of8051Microcontroller
Somevariantsof8051likethe8031and8032seriesdoesn’thaveanyinternalROM(Program
Memory) and must be interfaced with external Program Memory with instructionsloadedin it.
48|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Almost all modern 8051 Microcontrollers, like 8052 Series, have 8KB of Internal
ProgramMemory(ROM)intheformofFlashMemory(ROM)andprovidetheoptionofreprogramm
ingthememory.
In case of 4KB of Internal ROM, the address space is 0000H to 0FFFH. If the address
spacei.e., the program addresses exceed this value, then the CPU will automatically fetch the
codefromtheexternal Program Memory.
For this, the External Access Pin (EA Pin) must be pulled HIGH i.e., when the EA Pin
ishigh, the CPU first fetches instructions from the Internal Program Memory in the
addressrangeof0000Hto0FFFFHandifthememoryaddressesexceedthelimit,thentheinstructions
arefetched fromthe externalROM intheaddressrangeof1000Hto FFFFH.
There is another way to fetch the instructions: ignore the Internal ROM and fetch all
theinstructionsonlyfromtheExternalProgramMemory(ExternalROM).Forthisscenario,the
49|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
EA Pin must be connected to GND. In this case, the memory addresses of the external
ROMwillbefrom 0000H to FFFFH.
1.2.4.2. DataMemory(RAM)of8051Microcontroller
TheDataMemoryorRAMofthe8051Microcontrollerstorestemporarydataandintermediateresult
sthataregeneratedandusedduringthenormaloperationofthemicrocontroller.OriginalIntel’s
8051Microcontrollerhad 128Bofinternal RAM.
50|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
In the first 128B of RAM (from 00H to 7FH), the first 32B i.e., memory from addresses
00Hto 1FH consists of 32 Working Registers that are organized as four banks with 8
Registers ineachBank.
The 4 banks are named as Bank0, Bank1, Bank2 and Bank3. Each Bank consists of
8registers named as R0 – R7. Each Register can be addressed in two ways: either by name
orby address.To address the register by name, first the corresponding Bank must be selected.
Inorder to select the bank, we have to use the RS0 and RS1 bits of the Program Status
Word(PSW)Register (RS0 and RS1are3rd and 4th bitsin the PSWRegister).
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 entirebytecan beaddressed as20H to 2FH.
1.2.5. InterfacingExternalMemorywith8051Microcontroller
It is always good to have an option to expand the capabilities of a Microcontroller, whether
itis in terms of Memory or IO or anything else. Such expansion will be useful to avoid
designthrottling. We have seen that a typical 8051 Microcontroller has 4KB of ROM and
128B ofRAM(most modern8051 Microcontroller variantshave8K ROMand 256Bof RAM).
The designer of an 8051 Microcontroller based system is not limited to the internal RAM
andROM present in the 8051 Microcontroller. There is a provision of connecting both
externalRAMand ROM i.e., DataMemory and Program.
The reason for interfacing external Program Memory or ROM is that complex
programswrittenin high– level languagesoften tendto belarger and occupy more memory.
Another important reason is that chips like 8031 or 8032, which doesn’t have any
internalROM,haveto be interfaced with external ROM.
A maximum of 64KB of Program Memory (ROM) and Data Memory (RAM) each can
beinterfacewith the8051Microcontroller.
The following image shows the block diagram of interfacing 64KB of External RAM
and64KBof External ROMwith the8051 Microcontroller.
51|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Animportantpointtorememberwheninterfacingexternalmemorywith8051Microcontroller is
that Port 0 (P0) cannot be used as an IO Port as it will be used
formultiplexedaddressanddatabus(A0–A7andD0–D7).Notalways,butPort2maybeusedas
higher byteof theaddress bus.
2.2. EmbeddedCProgrammingwithKeilLanguage
EmbeddedCismostpopularprogramminglanguageinsoftwarefieldfordevelopingelectronic
gadgets. Each processor used in electronic system is associated with embeddedsoftware.
o Easytounderstand
o HighReliability
o Portability
o Scalability
Let'sseetheblockdiagram representationofembeddedsystemprogramming:
52|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
2.2.1. EmbeddedSystemProgramming:
BasicDeclaration
Let'sseetheblockdiagramofEmbeddedCProgramming development:
Function is a collection of statements that is used for performing aspecific task and
acollection of one or more functions is called a programming language. Every language
isconsistingofbasicelementsandgrammaticalrules.TheClanguageprogrammingisdesignedforfu
nctionwithvariables,characterset,datatypes,keywords,expressionandsoonareusedforwriting aC
program.
#include<microcontrollername.h>
53|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
BasicEmbeddedC ProgrammingSteps
Let'sseetheblockdiagramrepresentationofEmbeddedCProgrammingSteps:
Themicrocontrollerprogrammingisdifferentforeachtypeofoperatingsystem.Eventhough there
are many operating system are exist such as Windows, Linux, RTOS, etc butRTOShas
severaladvantagefor embedded systemdevelopment.
2.2.2. BasicsofEmbeddedCProgram
EmbeddedCisoneofthemostpopularandmostcommonlyusedProgrammingLanguagesinthedeve
lopmentofEmbeddedSystems.So,wewillseesomeoftheBasicsofEmbeddedCProgram and
theProgramming Structureof Embedded C.
2.2.2.1. WhatisanEmbeddedSystem?
An Embedded System is a combination of Hardware and Software. My desktop
computeralso has hardware and software. Does that mean a desktop computer is also an
EmbeddedSystem? NO. A desktop computer is considered a general purpose system as it can
do manydifferent tasks that too simultaneously. Some common tasks are playing videos,
working onofficesuites, editing images (orvideos), browsingtheweb, etc.
An example for embedded system, which we use daily, is a Wireless Router. In order to
getwireless internet connectivity on our mobile phones and laptops, we often use routers.
Thetask of a wireless router is to take the signal from a cable and transmit it wirelessly. And
takewirelessdatafrom thedevice(likeamobile) and send it through thecable.
We use washing machines almost daily but wouldn’t get the idea that it is an
embeddedsystemconsisting of aProcessor (and otherhardwareaswell) and software.
54|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
It takes some inputs from the user like wash cycle, type of clothes, extra soaking and
rinsing,spinrpm,etc.,performsthenecessaryactionsaspertheinstructionsandfinisheswashingand
drying the clothes. If no new instructions are given for the next wash, then the
washingmachinesrepeats thesameset of tasks as theprevious wash.
Embedded Systems can not only be stand-alone devices like Washing Machines but also be
apart of a much larger system. An example for this is a Car. A modern day Car has
severalindividual embedded systems that perform their specific tasks with the aim of making
asmoothand safejourney.
Some of the embedded systems in a Car are Anti-lock Braking System (ABS),
TemperatureMonitoring System, Automatic Climate Control, Tire Pressure Monitoring
System, EngineOilLevel Monitor, etc.
2.2.3. ProgrammingEmbeddedSystems
As mentioned earlier, Embedded Systems consists of both Hardware and Software. If
weconsider a simple Embedded System, the main Hardware Module is the Processor.
TheProcessor is the heart of the Embedded System and it can be anything like a
Microprocessor,Microcontroller, DSP, CPLD (Complex Programmable Logic Device) or an
FPGA (FieldProgrammableGated Array).
All these devices have one thing in common: they are programmable i.e., we can write
aprogram (which is the software part of the Embedded System) to define how the
deviceactuallyworks.
EmbeddedSoftwareorProgramallowHardwaretomonitorexternalevents(Inputs/Sensors)andco
ntrolexternaldevices(Outputs)accordingly.Duringthisprocess,theprogram for an Embedded
System may have todirectly manipulate the internal architectureof the Embedded Hardware
(usually the processor) such as Timers, Serial CommunicationsInterface,Interrupt Handling,
and I/O Ports etc.
55|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Fromtheabovestatement,itisclearthattheSoftwarepartofanEmbeddedSystemisequally
important as the Hardware part. There is no point in having advanced
HardwareComponentswith 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),VisualBasic, JAVA Script (Applicationlevel Programming Languages), etc.
In the process of making a better embedded system, the programming of the system plays
avitalroleand hence,the selection oftheProgramming Languageisvery important.
Size:
ThememorythattheprogramoccupiesisveryimportantasEmbeddedProcessorslikeMicro
controllershaveaverylimitedamountofROM(ProgramMemory).
Speed: The programs must be very fast i.e., they must run as fast as possible.
Thehardwareshould not be slowed down dueto aslow running software.
Portability:Thesameprogramcan becompiledfordifferentprocessors.
EaseofImplementation
EaseofMaintenance
Readability
Earlier Embedded Systems were developed mainly using Assembly Language. Even
thoughAssembly Language is closest to the actual machine code instructions andproduces
smallsize hex files, the lack of portability and high amount of resources (time and man
power)spenton developing thecode, madetheAssembly Languagedifficultto work with.
There are other high-level programming languages that offered the above mentioned
featuresbutnonewereclosetoCProgrammingLanguage.SomeofthebenefitsofusingEmbeddedCa
s the main Programming Language:
SignificantlyeasytowritecodeinC
ConsumeslesstimewhencomparedtoAssembly
Maintenanceof code(modifications andupdates)isvery simple
Makeuseof libraryfunctionsto reducethecomplexityofthemaincode
Youcaneasilyportthecodetootherarchitecture withverylittle modifications
56|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
2.2.6. ComponentsofEmbeddedSystem
AnEmbeddedSystemconsistsoffourmaincomponents.TheyaretheProcessor(Microprocessor or
Microcontroller), Memory (RAM and ROM), Peripherals(Input andOutput)and
Software(main program).
Processor: The heart of an Embedded System is the Processor. Based on the functionality
ofthe system, the processor can be anything like a General Purpose Processor, a single
purposeprocessor, an Application SpecificProcessor, a microcontrolleroranFPGA.
Memory: Memory is another important part of an embedded system. It is divided in to
RAMand ROM. Memory in an Embedded System (ROM to be specific) stores the main
programandRAM stores the program variables and temporarydata.
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
peripheralsinclude Input/ OutputPorts, CommunicationInterfaces, Timersand Counters,etc.
57|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Software: All the hardware work according to the software (main program) written.
Softwarepart of an Embedded System includes initialization of the system, controlling inputs
andoutputs,error handling etc.
NOTE: ManyEmbeddedSystems,usuallysmalltomediumscaledsystems,generallyconsists of a
Microcontroller as the main processor. With the help of a Microcontroller,
theprocessor,memory and fewperipherals will be integratedin to a singledevice.
2.2.7. IntroductiontoEmbeddedCProgrammingLanguage
BeforegoingintothedetailsofEmbeddedCProgrammingLanguageandbasicsofEmbeddedC
Program, wewillfirst talk about theC Programming Language.
TheCProgrammingLanguagebecamesopopularthatitisusedinawiderangeofapplicationsranging
from Embedded Systems to SuperComputers.
EmbeddedCProgrammingLanguage,whichiswidelyusedinthedevelopmentofEmbedded
Systems, is an extension of C Program Language. The Embedded C ProgrammingLanguage
uses the same syntax and semantics of the C Programming Language like
mainfunction,declarationofdatatypes,defining variables,loops, functions,statements, etc.
TheextensioninEmbeddedCfromstandardCProgrammingLanguageincludeI/OHardwareAddre
ssing,fixedpoint arithmetic operations,accessingaddressspaces, etc.
2.2.7.1. DifferencebetweenCandEmbeddedC
There is actually not much difference between C and Embedded C apart from few
extensionsandtheoperatingenvironment.BothCandEmbeddedCprogrammingareISOStandardst
hathavealmost same syntax, datatypes, functions, etc.
EmbeddedCisbasicallyanextensiontotheStandardCProgrammingLanguagewithadditionalfeatu
reslikeAddressingI/O,multiplememoryaddressingandfixed-pointarithmetic,etc.
58|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
small
large
Thefollowingtable listsoutall thekeywordsassociated withtheCx51 CCompiler.
_at_ alien bdata
bit code compact
data far idata
interrupt large pdata
_priority_ reentrant sbit
sfr sfr16 small
_task_ using xdata
DataTypesin EmbeddedC
Data Types in C Programming Language (or any programming language for that matter)
helpusdeclaringvariablesintheprogram.TherearemanydatatypesinCProgrammingLanguage
like signed int, unsigned int, signed char, unsigned char, float, double, etc. Inadditionto
thesetherefew moredata types in Embedded C.
The following are the extra data types in Embedded C associated with the Keil’s
Cx51Compiler.
bit
sbit
sfr
sfr16
Thefollowing tableshows someofthedata types inCx51Compileralong withtheir ranges.
DataType Bits(Bytes) Range
bit 1 0or 1(bitaddressable part ofRAM)
signedint 16(2) -32768to +32767
unsignedint 16(2) 0 to 65535
signedchar 8 (1) -128to +127
unsigned 8 (1) 0 to 255
float 32(4) ±1.175494E-38to±3.402823E+38
double 32(4) ±1.175494E-38to±3.402823E+38
sbit 1 0or 1(bitaddressable part ofRAM)
sfr 8 (1) RAMAddresses(80htoFFh)
sfr16 16(2) 0 to 65535
59|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
2.2.7.3. DifferentComponentsofanEmbeddedCProgram
Comments: Comments are readable text that are written to help us (the reader)
understandthe code easily. They are ignored by the compiler and do not take up any memory
in the finalcode(aftercompilation).
There are two ways you can write comments: one is the single line comments denoted by
//andthe other is multilinecomments denoted by /*….*/.
Global Variables: Global Variables, as the name suggests, are Global to the program
i.e.,theycan beaccessedanywherein theprogram.
Main Function: Every C or Embedded C Program has one main function, from where
theexecutionofthe programbegins.
BasicEmbeddedCProgram
60|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Till now, we have seen a few Basics of Embedded C Program like difference between C
andEmbeddedC,basicstructureortemplateofanEmbeddedCProgramanddifferentcomponentsof
theEmbedded C Program.
ExampleofEmbeddedC Program
The following image shows the circuit diagram for the example circuit. It contains an
8051basedMicrocontroller(AT89S52)alongwithits basiccomponents
(likeRESETCircuit,OscillatorCircuit, etc.)and components forblinking LEDs (LEDs and
Resistors).
In order to write the Embedded C Program for the above circuit, we will use the Keil
CCompiler.This compiler isapart ofthe Keil µVisionIDE. Theprogramis shown below.
#include<reg51.h>// Preprocessor
Directivevoid delay (int); // Delay Function
Declarationvoidmain(void)// Main Function
{
P1=0x00;
/*Making PORT1pins LOW.All theLEDsare OFF.
*(P1 isPORT1, asdefined inreg51.h)*/
while(1)// infiniteloop
{
61|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
2.2.7.4. LEDBlinkingusing8051Microcontroller
LED is a semiconductor device used in many electronic devices, mostly used for
indicationpurposes. It is used widely as indicator during test for checking the validity of
results atdifferentstages.
It is very cheap and easily available in variety of shape, color and size. The LEDs are
alsousedin designingofmessagedisplayboardsand traffic control signal lightsetc.
ConsidertheProteusSoftwarebasedsimulationofLEDblinkingusing8051Microcontrolleris
shown below:-
62|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
InaboveProteusbasedsimulationtheLEDsareinterfacedtothePORT0ofthe8051microcontroller.
Let'sseetheEmbeddedCProgramforgeneratingtheLEDoutputsequenceasshownbelow:
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;
b=P0;
for(l-
0;l<3000;l++);for(k
=0;k<8;k++)
{
b=b<<1;
P0=b;
}
}
63|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
ConsidertheEmbeddedCProgramforgeneratingtheLEDoutputsequenceasshownbelowis:
-
00000001
00000011
00000111.....
.... Andso on up to 11111111.
#include<reg51.h>
voidmain()
{
unsignedinti;unsi
gned 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;P
0=b;
}
}
}
DisplayingNumberon 7-SegmentDisplayusing 8051Microcontroller
Electronic display used for displaying alphanumeric character is known as 7-Segment
displayitis used in many systems fordisplaying theinformation.
64|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Consider theprogramfordisplayingthenumberfrom'0toF'on7-segmentdisplayis:-
10s#include<reg51
.h>sbit a=P3^0;
sbit x=
P3^1;sbit y=
P3^2;sbit z=
P3^3;void
main()
{
unsignedcharm[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++);
}
}
}
Considerthe programfordisplayingnumbers from '00 to 10'on a 7segmentdisplay is:-
#include<reg51.h>
sbit x=P3^0;
sbit y=
P3^1;void
display1();void
display2();void
delay();
65|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
void main()
{
unsignedcharm[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();displa
y2();
}
}
void display1()
{
x=1;
y=0;
P2=m[ds1];
delay();x=1
;
y=0;P2=m[
ds1];delay(
);
}
voiddisplay2()
{
ds1++;
if(ds1>=10)
{
ds1=0;ds2+
+;if(ds2>=1
0)
{
ds1=ds2=0;
}
}
}
voiddelay()
{
unsignedintk;
for(k=0;k<30000;k++);
}
2.3. RTOS(Real-TimeOperatingSystemsforEmbeddedDevelopers)
66|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
The key difference between an operating system such as Windows and an RTOS often
foundin embedded systems is the response time to external events. An ordinary OS provides
a non-deterministicresponsetoeventswithnoguaranteewithrespecttowhentheywillbeprocessed,
albeit while trying to stay responsive. The user perceiving the OS to be responsiveis more
important than handling underlying tasks. On the other hand, an RTOS' goal is
fastandmoredeterministicreaction.
DevelopersusedtoOS’ssuchasWindowsorLinuxwillbequitefamiliarwiththecharacteristics of
an embedded RTOS. They are designed to run in systems with limitedmemory,and to operate
indefinitely without theneed to bereset.
Because an RTOS is designed to respond to events quickly and perform under heavy loads,
itcanbeslower at big tasks when compared to anotherOS.
2.3.2. RTOSscheduling
An RTOS is valued for how quickly it can respond and in that, the advanced
schedulingalgorithmis the key component.
The time-criticality of embedded systems vary from soft-real time washing machine
controlsystemsthroughhard-
realtimeaircraftsafetysystems.Insituationslikethelatter,thefundamental demand to meet real-
time requirements can only be made if the OS scheduler’sbehaviorcan beaccurately
predicted.
Many operating systems give the impression of executing multiple programs at once, but
thismulti-tasking is something of an illusion. A single processor core can only run a single
threadof execution at any one time. An operating system’s scheduler decides which program,
orthread,torunwhen.Byrapidlyswitchingbetweenthreads,itprovidestheillusionofsimultaneous
multitasking.
67|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
UsinganRTOSmeansyoucanrunmultipletasksconcurrently,bringinginthebasicconnectivity,
privacy, security, and so on as and when you need them. An RTOS allows youtocreatean
optimized solution forthe specificrequirements of yourproject.
2.3.4. IntroducingtheZephyrRTOS
There are numerous RTOS solutions out there. Many developers in the Nordic world
arefocused on low power embedded systems. If that’s you, we’d suggest you check out
Zephyr,whichis well-suitedforconnectivity solutionsinwhichultra-low power isarequirement.
The modular Zephyr RTOS supports multiple architectures, so developers are able to
easilytailorasolution to meet their needs.
2.3.5. Real-timeoperatingsystem(RTOS):Components,Types,Examples
Real-time operating system (RTOS) is an operating system intended to serve
realtimeapplicationthatprocessdataasitcomesin,mostlywithoutbufferdelay.ThefullformofRTO
S is Real timeoperating system.
2.3.5. WhyuseanRTOS?
HereareimportantreasonsforusingRTOS:
It offers priority-based scheduling, which allows you to separate analytical
processingfromnon-critical processing.
TheRealtimeOSprovidesAPIfunctionsthatallowcleanerandsmallerapplicationcode.
Abstractingtimingdependenciesandthetask-
baseddesignresultsinfewerinterdependenciesbetween modules.
RTOSoffersmodulartask-baseddevelopment,whichallowsmodulartask-basedtesting.
68|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
The task-based API encourages modular development as a task, will typically have
aclearly defined role. It allows designers/teams to work independently on their parts
oftheproject.
An RTOS is event-driven with no time wastage on processing time for the
eventwhichis not occur
2.3.6. TermsusedinRTOS
Here, areessentialtermsusedinRTOS:
Task– Asetofrelatedtasksthatarejointlyabletoprovidesomesystemfunctionality.
Job– A jobisasmallpieceof workthatcanbe assignedtoaprocessor, andthatmayormay
not require resources.
Releasetimeof a job–It’satimeofajob atwhichjob becomesready for execution.
Executiontimeofajob: Itistime takenbyjob tofinishitsexecution.
Deadlineofajob:It’stimebywhich ajobshouldfinishitsexecution.
Processors:Theyarealsoknownasactiveresources.Theyareimportantfortheexecutionofa
job.
Maximum Itisthe allowableresponsetime ofajob iscalledits relativedeadline.
Responsetimeofajob:
Itisalengthoftimefromthereleasetimeofajobwhentheinstantfinishes.
Absolutedeadline: Thisistherelativedeadline,whichalsoincludes itsreleasetime.
2.3.7. ComponentsofRTOS
SymmetricMultiprocessing(SMP):Itisanumberofmultipledifferenttasksthatcanbehandledby
theRTOS so that parallelprocessing can bedone.
69|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
FunctionLibrary:ItisanimportantelementofRTOSthatactsasaninterfacethathelpsyou to
connect kernel and application code. This application allows you to send the
requeststotheKernelusing afunction libraryso thattheapplicationcan givethedesiredresults.
Fast dispatch latency: It is an interval between the termination of the task that can
beidentified by the OS and the actual time taken by the thread, which is in the ready queue,
thathasstarted processing.
User-defined data objects and classes: RTOS system makes use of programming
languageslikeC or C++, whichshould be organizedaccordingto their operation.
FactorsforselectinganRTOS
Here, are essentialfactorsthatyouneedtoconsiderforselectingRTOS:
Performance:Performanceisthemostimportantfactorrequiredtobeconsideredwhilesele
cting foraRTOS.
Middleware:ifthereisnomiddlewaresupportinRealtimeoperatingsystem,thentheissue
oftime-taken integration ofprocesses occurs.
Error-free:RTOSsystemsareerror-free.Therefore,thereisnochanceofgettinganerror
while performing thetask.
Embeddedsystemusage:ProgramsofRTOSareofsmallsize.SowewidelyuseRTOSfore
mbedded systems.
MaximumConsumption:wecanachievemaximumConsumptionwiththehelpofRTOS.
Taskshifting:Shiftingtimeofthetasks isvery less.
Unique features: A good RTS should be capable, and it has some extra features
likehow it operates to execute a command, efficient protection of the memory of
thesystem,etc.
24/7performance:RTOSisideal forthoseapplicationswhich requiretorun24/7.
70|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
General-PurposeOperatingSystem
Real-TimeOperatingSystem(RTOS)
(GPOS)
Itused fordesktopPC andlaptop. Itisonlyappliedtotheembeddedapplication.
Time-basedschedulingusedlikeround-robin
Process-basedScheduling.
scheduling.
Interruptlatencyisnotconsideredas Interruptlagisminimal,whichismeasuredina few
importantasinRTOS. microseconds.
Nopriorityinversionmechanismis Thepriorityinversionmechanism iscurrent.Soit
presentinthesystem. cannot modify by the system.
Kernel’soperationmayormaynotbe
Kernel’soperationcanbepreempted.
preempted.
Priorityinversionremainunnoticed Nopredictabilityguarantees
Thereal-timeoperating systemscanbeof3types–
RTOS
1. HardReal-Timeoperating system:
Theseoperatingsystemsguaranteethatcriticaltasksbecompletedwithinarangeoftime.
For example, a robot is hired to weld a car body. If the robot welds too early or too
late,the car cannot be sold, so it is a hard real-time system that requires complete car
weldingby robot hardly on the time., scientific experiments, medical imaging systems,
industrialcontrolsystems, weaponsystems,robots, air trafficcontrolsystems, etc.
2. Softreal-timeoperating system:
Thisoperatingsystem providessomerelaxation inthe timelimit.
For example – Multimedia systems, digital audio systems etc. Explicit, programmer-
definedandcontrolledprocessesareencounteredinreal-timesystems.Aseparateprocess is
changed with handling a single external event. The process is activated uponoccurrenceof
therelatedevent signalled byan interrupt.
71|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Multitaskingoperationisaccomplishedbyschedulingprocessesforexecutionindependently
of each other. Each process is assigned a certain level of priority thatcorresponds to the
relative importance of the event that it services. The processor isallocated to the highest
priority processes. This type of schedule, called, priority-basedpreemptivescheduling is
used by real-time systems.
3. FirmReal-timeOperating System:
RTOS of this type have to follow deadlines as well. In spite of its small impact, missing
adeadline can have unintended consequences, including a reduction in the quality of
theproduct.Example: Multimediaapplications.
2. Task Shifting
Time assigned for shifting tasks in these systems is very less. For example, in
oldersystems,ittakesabout10 microseconds.Shiftingonetaskto
anotherandinthelatestsystems,it takes 3 microseconds.
3. FocusOnApplication –
Focusonrunningapplicationsandlessimportancetoapplicationsthatareinthequeue.
4. Real-TimeOperatingSystemInEmbeddedSystem–
Since the size of programs is small, RTOS can also be embedded systems like
intransportand others.
5. ErrorFree–
Thesetypesofsystemsareerror-free.
6. MemoryAllocation–
Memoryallocationisbestmanaged inthesetypes ofsystems.
1. LimitedTasks–
Very few tasks run simultaneously, and their concentration is very less on
fewapplicationsto avoid errors.
72|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
2. UseHeavySystemResources–
Sometimesthesystem resourcesarenotsogood andthey areexpensiveaswell.
3. ComplexAlgorithms–
Thealgorithmsarevery complex anddifficult for the designerto writeon.
4. DeviceDriver AndInterruptsignals –
Itneedsspecificdevicedriversandinterruptssignalstorespondearliesttointerrupts.
5. ThreadPriority–
Itis notgood toset thread priorityas thesesystems areveryless proneto switching tasks.
6. MinimumSwitching–RTOSperformsminimaltaskswitching.
2.4. MultipleTasksAndMultipleProcesses
2.4.1. TasksandProcesses
Many(ifnotmost)embeddedcomputingsystemsdomorethanonethingthatis,theenvironment can
cause mode changes that in turn cause the embedded system to behave quitedifferently.For
example,when designing atelephoneanswering machine,
We can define recording a phone call and operating the user’s control panel as distinct
tasks,becausetheyperformlogicallydistinctoperationsandtheymustbeperformedatverydifferentr
ates.Thesedifferent tasks arepartofthesystem’sfunctionality,butthatapplication-
levelorganizationoffunctionalityisoftenreflectedinthestructureoftheprogramas well.
73|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
The program’s need toreceive andsend data at differentratesfor example, the programmay
emit 2 bits for the first byte and then 7 bits for the second byte will obviously find
itselfreflected in the structure of the code. It is easy to create irregular, ungainly code to solve
thisproblem; a more elegant solution is to create a queue of output bits, with those bits
beingremovedfrom the queueand sent tothe serial portin 8-bitsets.
But beyond the need to create a clean data structure that simplifies the control structure of
thecode, we must also ensure that we process the inputs and outputs at the proper rates.
Forexample, if we spend too much time in packaging and emitting output characters, we
maydropan input character. Solving timing problems isamorechallenging problem.
The text compression box provides a simple example of rate control problems. A
controlpanelonamachineprovidesanexampleofadifferenttypeofratecontrolproblem,theasynchr
onousinput.
The control panel of the compression box may, for example, include a compression
modebuttonthatdisablesorenablescompression,sothattheinputtextispassedthroughunchangedw
hencompressionisdisabled.Wecertainlydonotknowwhentheuserwillpush
74|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
the compression mode button the button may be depressed asynchronously relative to
thearrivalofcharacters forcompression.
2.4.2. MultirateSystems
Implementing code that satisfies timing requirements is even more complex when
multipleratesofcomputationmustbehandled. Multirate
embeddedcomputingsystemsareverycommon,includingautomobileengines,printers,andcellph
ones.Inallthesesystems,certain operations must be executed periodically, and each operation
is executed at its ownrate.
2.4.3. TimingRequirementsonProcesses
Processes can have several different types of timing requirements imposed on them by
theapplication. The timing requirements on a set of processes strongly influence the type
ofschedulingthatisappropriate.Aschedulingpolicymustdefinethetimingrequirementsthatit uses
to determine whether a schedule is valid. Before studying scheduling proper,
weoutlinethetypesofprocesstiming requirementsthat areusefulin embeddedsystem design.
Figure illustrates different ways in which we can define two important requirements
onprocesses:releasetime and deadline.
The release time is the time at which the process becomes ready to execute; this is
notnecessarily the time at which it actually takes control of the CPU and starts to run.
Anaperiodic process is by definition initiated by an event, such as external data arriving or
datacomputedby anotherprocess.
The release time is generally measured from that event, although the system may want
tomake the process ready at some interval after the event itself. For a periodically
executedprocess,therearetwo common possibilities.
75|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
In simpler systems, the process may become ready at the beginning of the period.
Moresophisticated systems, such as those with data dependencies between processes, may set
thereleasetime atthearrivaltime ofcertaindata, atatime afterthestartof the period.
Raterequirementsarealsofairlycommon.Araterequirementspecifieshowquicklyprocessesmust
beinitiated.
The period of a process is the time between successive executions. For example, the
periodofadigital filter is defined by the timeinterval between successiveinput samples.
The process’s rate is the inverse of its period. In a multirate system, each process executes
atitsown distinct rate.
The most common case for periodic processes is for the initiation interval to be equal to
theperiod. However, pipelined executionof processesallows the initiation intervaltobe
lessthantheperiod. Figureillustrates processexecutionin a system with fourCPUs.
CPUMetrics
Wealsoneedsometerminologyto describe how the process actually executes.The
initiation time isthe timeatwhichaprocessactuallystartsexecutingontheCPU.Thecompletion
time is thetime atwhich theprocess finishes its work.
The most basic measure of work is the amount of CPU time expended by a process.
TheCPU time of process i is called Ci . Note that the CPU time is not equal to the
completiontime minus initiation time; several other processes may interrupt execution. The
total CPUtimeconsumed by aset of processes is
76|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
T=∑Ti
We need a basic measure of the efficiency with which we use the CPU. The simplest
andmostdirect measureisutilization:
Utilization is the ratio of the CPU time that is being used for useful computations to the
totalavailable CPU time. This ratio ranges between 0 and 1, with 1 meaning that all of
theavailable CPU time is being used for system purposes. The utilization is often expressed
as apercentage. If we measure the total execution time of all processes over an interval of
time t,thentheCPU utilization is
U=T/t.
2.4.4. MultipleTasksandMultipleProcesses
`Most embedded systems require functionality and timing that is too complex to
bodyin a single program. We break the system in to multiple tasks in order to manage when
thingshappen. In this section we will develop the basic abstractions that will be manipulated
by theRTOSto build multirate systems.
Tounderstandwhytheseparathionofanapplicationintotasksmaybereflectedinthe
program structure, consider how we would build a stand-alone compression unit based onthe
compression algorithm,this device is connected to serial ports on both ends. The input tothe
box is an uncompressed stream of bytes. The box emits a compressed string of bits on
theoutput serial line, based on a predefined compression table. Such a box may be used,
forexample, to compress data being sent to a modem. The program’s need to receive and
senddata at different rates—for example, the program may emit 2 bits for the first byte and
then 7bitsforthesecond byte— willobviously finditself reflected inthe structureof the code.
The text compression box provides a simple example of rate control problems.
Acontrol 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, includea compression mode button that disables or enables com- pression, so that
the input text ispassed through unchanged whencompression isdisabled. We certainly do not
know whentheuserwillpushthecompressionmodebutton—
thebuttonmaybedepressedasynchronouslyrelativetothearrivalofcharactersforcompression.We
doknow,however,
77|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
thatthebuttonwillbedepressedatamuchlowerratethancharacterswillbereceived,sinceitisnotphys
icallypossibleforapersontorepeatedlydepressabuttonatevenslowserialline rates. Keeping up
with the input and output data while checking on the button canintroduce some very complex
control code in to the program. Sampling the button’s state tooslowly can cause the machine
to miss a button depression entirely, but sampling it
toofrequentlyandduplicatingadatavaluecancausethemachine toincorrectlycompressdata.
Onesolutionistointroduceacounterintothemaincompressionloop,sothatasubroutinetocheck the
inputbutton iscalled once every times the compression loopisexecuted. Butthis solution does
not work when either the compression loop or the button-handling routinehas highly variable
execution times—if the execution time of either varies significantly, itwill cause the other to
execute later than expected, possibly causing data to be lost. We needto be able to keep track
of these two different tasks separately, applying different timingrequirementsto each.
This is the sort of control that processes allow. The above two examples illustrate
howrequirements on timing and execution rate can create major problems in programming.
Whencode is written to satisfy several different timing requirements at once, the control
structuresnecessarytogetanysortofsolutionbecomeverycomplexveryquickly.Worse,suchcompl
excontrolisusuallyquitedifficultto verify foreither functionalortimingproperties.
2.4.5. MultirateSystems
Implementing code that satisfies timing requirements is even more complex
whenmultiple rates of computation must be handled. Multi rate embedded computing
systems arevery common, including auto mobile engines, printers, and cell phones.In all
these systems,certain operations must be executed periodically, and each oper-ation is
executed at its
ownrate.ApplicationExample6.1describeswhyautomobileenginesrequiremultiratecontrol.
2.4.6. TimingRequirementsonProcesses
Processescanhaveseveraldifferenttypesoftimingrequirementsimposedonthemby the
application. The timing requirements on a set of process strongly influence the type
ofschedulingthatisappropriate.Aschedulingpolicymustdefinethetimingrequirementsthatit uses
to determine whether a schedule is valid. Before studying scheduling proper, weoutline the
types of process timing requirements that are useful in embedded system design.Figure
illustrates different ways in which we can define two important requirements onprocesses:
eg. What happens when a process misses a deadline? The practical effects of atiming
violation depend on the application—the results can be catastrophic in an auto mo-
tivecontrolsystem,whereasamisseddeadlineinamultimediasystemmaycauseanaudioor video
glitch. The system can be designed to take a variety of actions when a deadline
ismissed.Safety-criticalsystemsmaytrytotakecompensatorymeasuressuchasapproximating
data or switching in to a special safety mode. Systems for which safety is notas important
may take simple measures to avoid propagating bad data, such as
insertingsilenceinaphoneline,ormaycompletelyignorethefailure.Evenifthemodulesarefunction
allycorrect,theirtimingimproperbehaviorcanintroducemajorexecutionerrors.
78|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Application Example6.2 describes a timing problem in space shuttle software that caused
thedelay of the first launch of the shuttle. We need a basic measure of the efficiency with
whichweusethe CPU. Thesimplest and most direct measureis utilization:
Utilization is the ratio of the CPU time that is being used for useful computations to the
totalavailable CPUtime.Thisratiorangesbetween0and1,with1meaningthatallof theavailable
CPU time is being used for system purposes. The utilization is often expressed as
apercentage. If we measure the total execution time of all processes over an interval of time
t,thentheCPU utilization is U/T
2.4.7. ProcessStateandScheduling
The first job of the OS is to determine that process runs next. The work of
choosingthe order of running processes is known as scheduling. The OS considers a process
to be inoneof threebasic scheduling states
Schedulability means whether there exists a schedule of execution for the processes in
asystem that satisfies all their timing requirements. In general, we must construct a schedule
toshowschedulability,butinsomecaseswecaneliminatesomesetsofprocessesasunschedulableusi
ngsomeverysimpletests.Utilizationisoneofthekeymetricsinevaluating a scheduling policy. Our
most basic require- ment is that CPU utilization be nomorethan 100%since wecan’t usethe
CPUmorethan100%ofthetime.
When we evaluate the utilization of the CPU, we generally do so over a finite period
thatcovers all possible combinations of process executions. For periodic processes, the length
oftime that must be considered is the hyper period, which is the least-common multiple of
theperiods of all the processes. If we evaluate the hyper period, we are sure to have
consideredallpossible combinations of theperiodicprocesses.
2.4.8. RunningPeriodicProcesses
We need to find a programming technique that allows us to run periodic
processes,ideally at different rates. For the moment, let’s think of a process as a subroutine;
we will
callthemp1(),p2(),etc.forsimplicity.Ourgoalistorunthesesubroutinesatratesdeterminedby the
system
79|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
designer. Here is a very simple program that runs our process subroutines repeatedly: A
timeris a much more reliable way to control execution of the loop. We would probably use
thetimer to generate periodic interrupts. Let’s assume for the moment that the pall() function
iscalled by the timer’s interrupt handler. Then this code will execute each process once after
atimerinterrupt:
voidpall()
{
p1();
p2();
}
But what happens when a process runs too long? The timer’s interrupt will cause the
CPU’sinterrupt 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 wewillhaveto wait forfurther refinements beforewecanfix it.
voidpA()
{
/*processesthatrunatrateA*/
p1();
p3();
}
voidpB()
{
/*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
morecomplex 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
boththecapabilities and reliability ofour systems, weneedto invent theRTOS.
2.5. ContextSwitchinOperatingSystem
An operating system is a program loaded into a system or computer. and manage
allthe other program which is running on that OS Program, it manages the all other
applicationprograms. or in other words, we can say that the OS is an interface between the
user andcomputerhardware.
80|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
we will learn about what is Context switching in an Operating System and see how it
worksalsounderstands thetriggers ofcontext switchingand anoverview oftheOperatingSystem.
ContextSwitch
Context switching in an operating system involves saving the context or state of a
runningprocess so that it can be restored later, and then loading the context or state of
another.processandrun it.
Context Switching refers to the process/method used by the system to change the
processfromone state to another using the CPUs present inthe system to perform itsjob.
Example – Suppose in the OS there (N) numbers of processes are stored in a Process
ControlBlock(PCB). like The process is running using the CPU to do its job. While a process
isrunning, other processes with the highest priority queue up to use the CPU to complete
theirjob.
Theoperatingsystem’sneedforcontextswitchingisexplainedbythereasonslistedbelow.
1. Oneprocessdoesnotdirectlyswitchtoanotherwithinthesystem. Contextswitching makes it
easier for the operating system to use the CPU’s resources to carry outitstasks and storeits
context whileswitching between multiple processes.
2. Context switching enables all processes to share a single CPU to finish their
executionand store the status of the system’s tasks. The execution of the process begins at
the sameplacewherethereis aconflictwhen the process is reloaded intothe system.
3. Context switching enables all processes to share a single CPU to finish their
executionand store the status of the system’s tasks. The execution of the process begins at
the sameplacewherethereis aconflictwhen the process is reloaded intothe system.
4. ContextswitchingonlyallowsasingleCPUtohandlemultipleprocessesrequestsparallellywith
out the need foranyadditional processors.
2.5.2. ContextChangesasaTrigger
Thethreedifferentcategories ofcontext-switchingtriggers areasfollows.
1. Interrupts
2. Multitasking
3. User/Kernelswitch
Interrupts: When a CPU requests that data be read from a disc, if any interruptions
occur,context switching automatically switches to a component of the hardware that can
handle theinterruptions morequickly.
81|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Multitasking: The ability for a process to be switched from the CPU so that another
processcan run is known as context switching. When a process is switched, the previous state
isretainedso that theprocess cancontinuerunning at thesamespot in the system.
Kernel/User Switch: This trigger is used when the OS needed to switch between the
usermodeand kernel mode.
2.5.3.1. StateDiagramofContextSwitching
82|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
2.6. PrioritySchedulingAlgorithm:Preemptive,Non-Preemptive
WhatisPriorityScheduling?
Priority Scheduling is a method of scheduling processes that is based on priority. In
thisalgorithm,thescheduler selects thetasks toworkas per thepriority.
The processeswithhigher priorityshouldbe carriedoutfirst,whereasjobswithequalpriorities are
carried out on a round-robin or FCFS basis. Priority depends upon
memoryrequirements,timerequirements, etc.
2.6.1. TypesofPriorityScheduling
Priorityschedulingdividedintotwomaintypes:
2.6.1.1. PreemptiveScheduling
In Preemptive Scheduling, the tasks are mostly assigned with their priorities. Sometimes it
isimportant to run a task with a higher priority before another lower priority task, even if
thelower priority task is still running. The lower priority task holds for some time and
resumeswhenthe higher priority task finishes its execution.
2.6.1.2. Non-PreemptiveScheduling
In this type of scheduling method, the CPU has been allocated to a specific process.
TheprocessthatkeepstheCPUbusy,willreleasetheCPUeitherbyswitchingcontextorterminating.
It is the only method that can be used for various hardware platforms.
That’sbecauseitdoesn’tneed specialhardware(for example,atimer)likepreemptivescheduling.
2.6.2. CharacteristicsofPriorityScheduling
ACPUalgorithmthatschedulesprocessesbasedonpriority.
ItusedinOperatingsystemsforperformingbatchprocesses.
IftwojobshavingthesamepriorityareREADY,itworksonaFIRSTCOME,FIRSTSERVE
Dbasis.
Inpriorityscheduling,anumberisassignedtoeachprocessthatindicatesitsprioritylevel.
Lowerthenumber,higher isthe priority.
83|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Step2)Attime2,nonewprocessarrives,soyoucancontinuewithP1.P2isinthewaitingqueue.
Step3)Attime3,nonew
processarrivessoyoucancontinuewithP1.P2processstillinthewaitingqueue.
84|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Step4)Attime4,P1hasfinisheditsexecution.P2startsexecution.
Step6)Attime=6,P3arrives.P3isathigherpriority(1)comparedtoP2havingpriority(2).P2is
preempted, and P3 begins its execution.
Process Priority Bursttime Arrivaltime
P1 1 4 0
P2 2 1out of3 pending 0
P3 1 7 6
P4 3 4 11
P5 2 2 12
85|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Step7)At time7,no-newprocessarrives,sowecontinuewithP3.P2isinthewaitingqueue.
Step11)Attime=11,P4arriveswithpriority4.P3hashigherpriority,soitcontinuesitsexecution.
Process Priority Bursttime Arrivaltime
P1 1 4 0
P2 2 1out of3 pending 0
86|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Step12)Attime=12,P5arrives.P3hashigherpriority, soitcontinuesexecution.
Step13)Attime=13,P3completesexecution.WehaveP2,P4,P5inreadyqueue.P2andP5haveequal
priority. Arrival timeofP2 is beforeP5. So P2starts execution.
Process Priority Bursttime Arrivaltime
P1 1 4 0
P2 2 1out of3 pending 0
P3 1 7 6
P4 3 4 11
P5 2 2 12
Step14)Attime=14,theP2processhasfinisheditsexecution.P4andP5areinthewaitingstate.P5 has
the highest priority and starts execution.
87|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Step15)Attime=15,P5continuesexecution.
Step16)Attime=16,P5isfinishedwithitsexecution.P4istheonlyprocessleft.Itstartsexecution.
Step17)Attime=20,P5has completedexecutionandnoprocessisleft.
Step 18) Let’s calculate the average waiting time for the above
example.WaitingTime =start time– arrivaltime+wait timefor nextburst
P1 =o-o =o
P2=4 -o+7 =11
P3=6-6=0
P4=16-11=5
AverageWaitingtime= (0+11+0+5+2)/5=18/5= 3.6
88|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
2.6.4. Advantagesofpriorityscheduling
Here,arebenefits/prosofusingpriorityschedulingmethod:
Easytouseschedulingmethod
Processesareexecutedonthebasisofprioritysohighprioritydoesnotneedtowaitforlong
which saves time
This method provides a good mechanism where the relative important of each
processmaybeprecisely defined.
Suitableforapplications withfluctuatingtimeandresourcerequirements.
2.6.5. Disadvantagesofpriorityscheduling
Here, arecons/drawbacksofpriorityscheduling
Ifthesystemeventuallycrashes,all lowpriorityprocessesgetlost.
If high priority processes take lots of CPU time, then the lower priority processes
maystarveand will bepostponed foran indefinite time.
Thisschedulingalgorithmmayleavesomelowpriorityprocesseswaitingindefinitely.
A processwillbeblockedwhenitisreadytorunbuthastowaitforthe CPUbecausesomeother
process is running currently.
Ifanewhigherpriorityprocesskeepsoncominginthereadyqueue,thentheprocesswhichis
in thewaitingstate may need towait for along durationoftime.
2.6.6. Schedulingpolicies
Tomeettheneedsofvariousapplications,theQNXNeutrinoRTOSprovidestheseschedulingalgorit
hms:
FIFOscheduling
round-robinscheduling
sporadicscheduling
Eachthreadinthesystemmayrunusinganymethod.Themethodsareeffectiveonaper-threadbasis,
not on a globalbasis forall threads and processesonanode.
Remember that the FIFO and round-robin scheduling policies apply only when two or
morethreads that share the same priority are READY (i.e., the threads are directly competing
witheach other). The sporadic method, however, employs a “budget” for a thread's execution.
Inall cases, if a higher-priority thread becomes READY, it immediately preempts all lower-
prioritythreads.
In the following diagram, three threads of equal priority are READY. If Thread A
blocks,ThreadBwillrun.Althoughathreadinheritsitsschedulingpolicyfromitsparentprocess,thet
hread can request to changethealgorithm applied by thekernel.
89|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
ThreadAblocks;ThreadBruns.
Summary:
Priorityschedulingisamethodofschedulingprocessesthatisbasedonpriority.Inthisalgorit
hm, theschedulerselectsthetasks to workas per the priority.
InPriorityPreemptiveScheduling,thetasksaremostlyassignedwiththeirpriorities.
InPriorityNon-
preemptiveschedulingmethod,theCPUhasbeenallocatedtoaspecificprocess.
Processesareexecutedonthebasisofprioritysohighprioritydoesnotneedtowaitforlong
which saves time
If high priority processes take lots of CPU time, then the lower priority processes
maystarveand will bepostponed foran indefinite time.
90|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
UNITIII
IOTANDARDUINOPROGRAMMING
Introductiontothe ConceptofIoTDevices
IoT DevicesVersusComputers
IoTConfigurations
Basic Components
IntroductiontoArduino
Typesof Arduino
Arduino Toolchain
ArduinoProgrammingStructure
Sketches
Pins
IntroductiontoArduinoShields
IntegrationofSensorsand ActuatorswithArduino
3.1. IoT(InternetofThings)
91|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
IoTstandsforInternetofThings,whichmeansaccessingandcontrollingdailyusableequipmentsand
devicesusing Internet.
The term "Things" in the Internet of Things refers to anything and everything in day to
daylifewhich is accessed or connected through theinternet.
IoT is an advanced automation and analytics system which deals with artificial
intelligence,sensor, networking, electronic, cloud messaging etc. to deliver complete systems
for
theproductorservices.ThesystemcreatedbyIoThasgreatertransparency,control,andperformance
.
As we have a platform such as a cloud that contains all the data through which we connect
allthe things around us. For example, a house, where we can connect our home appliances
suchas air conditioner, light, etc. through each other and all these things are managed at the
sameplatform. Since we have a platform, we can connect our car, track its fuel meter, speed
level,andalso track thelocation of thecar.
92|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Ifthereisacommonplatformwhereallthesethingscanconnecttoeachotherwouldbegreat because
based on my preference, I can set the room temperature. For example, if I
lovetheroomtemperaturetotobesetat25or26-
degreeCelsiuswhenIreachbackhomefrommyoffice,thenaccordingtomycarlocation,myACwoul
dstartbefore10minutesIarriveathome. This can bedonethroughtheInternet ofThings (IoT).
3.1.3. FeaturesofIOT
ThemostimportantfeaturesofIoTonwhichitworksareconnectivity,analyzing,integrating,activee
ngagement, and many more. Some ofthemarelisted below:
Connectivity: Connectivity refers to establish a proper connection between all the things
ofIoT to IoT platform it may be server or cloud. After connecting the IoT devices, it needs
ahigh speed messaging between the devices andcloud to enable reliable, secure and bi-
directionalcommunication.
Analyzing: After connecting all the relevant things, it comes to real-time analyzing the
datacollected and use them to build effective business intelligence. If we have a good insight
intodatagathered fromall thesethings, then wecall oursystem has asmartsystem.
Integrating: IoTintegratingthevariousmodelstoimprovetheuserexperienceaswell.
93|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
ArtificialIntelligence:IoTmakesthingssmartandenhanceslifethroughtheuseofdata.For
example, if we have a coffee machine whose beans have going to end, then the
coffeemachineitself order thecoffeebeansof your choicefrom theretailer.
Sensing: The sensor devices used in IoT technologies detect and measure any change in
theenvironment and report on their status. IoT technology brings passive networks to
activenetworks.Without sensors,therecould nothold an effectiveor trueIoTenvironment.
AdvantagesandDisadvantagesof(IoT)
Anytechnologyavailabletodayhasnotreachedtoits100%capability.Italwayshasagapto go. So,
we can say that Internet of Things has a significant technology in a world that
canhelpothertechnologies toreach itsaccurate andcomplete 100%capabilityas well.
3.1.3.2. DisadvantagesofIoT
As the Internet of things facilitates a set of benefits, it also creates a significant set
ofchallenges.Some oftheIoT challengesaregivenbelow:
Security: As the IoT systems are interconnected and communicate over
networks.The system offers little control despite any security measures, and it can be
lead thevariouskinds of networkattacks.
Privacy: Even without the active participation on the user, the IoT system
providessubstantialpersonal datain maximum detail.
94|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Complexity:Thedesigning,developing,andmaintainingandenablingthelargetechnology
to IoT system is quite complicated.
3.1.4. EmbeddedDevices(System)in(IoT)
It is essential to know about the embedded devices while learning the IoT or building
theprojects on IoT. The embedded devices are the objects that build the unique
computingsystem.Thesesystems may ormay not connect to theInternet.
3.1.5. EmbeddedSystemHardware
The embedded system can be of type microcontroller or type microprocessor. Both of
thesetypescontain an integrated circuit (IC).
95|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
BasicEmbeddedSystem
3.1.6. EmbeddedSystemSoftware
The embedded system that uses the devices for the operating system is based on the
languageplatform, mainly where the real-time operation would be performed. Manufacturers
buildembeddedsoftwareinelectronics,e.g.,cars,telephones,modems,appliances,etc.Theembedd
ed system software can be as simple as lighting controls running using an 8-
bitmicrocontroller. It can also be complicated software for missiles, process control
systems,airplanesetc.
3.1.6.1. IoTDecisionFramework
The IoT decision framework provides a structured approach to create a powerful IoT
productstrategy. The IoT decision framework is all about the strategic decision making. The
IoTDecision Framework helps us to understand the areas where we need to make decisions
andensuresconsistency acrossall of ourstrategicbusiness decision,technicaland more.
TheIoTdecisionframeworkismuchmoreimportantastheproductorservicescommunicatesovernet
worksgoesthroughfivedifferentlayersofcomplexityoftechnology.
1. DeviceHardware
2. DeviceSoftware
3. Communications
4. CloudPlatform
5. CloudApplication
96|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
TheIoTdecisionframeworkpaysattentiontosixkeydecisionareasinanyIoTproduct.Thesedecision
areas are:
1. UserExperience(UX)
2. Data
3. Business
4. Technology
5. Security
6. Standards&Regulations
Each of these decision areas is evaluated at each of the IoT Technology Stack. The
UserExperience will be evaluated at Device Hardware, Device Software and so to provide
thebetter user experience. Then at the next step Data Decision Area, we have to explore
dataconsiderationsfor all the stages of IoTTechnology Stack.r
Let'sseeeachoftheDecisionAreaof IoTDecisionFrameworkindetail:
1. User Experience Decision Area: This is the area where we concentrate about
whoare the users, what are their requirements and how to provide a great experience
ateachstep of IoT stackwithout worrying aboutthetechnicaldetails.
2. Data Decision Area: In this area, we make the overall data strategy such as the
dataflowover the entire IoT stackto fulfill the user's requirements.
3. Business Decision Area: Based on the previous decisions area, we make the
decisionhowproductorserviceswillbecamefinancialpotential.AteachoftheIoTStackleve
laremonetized about thecosts of providing services.
97|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
4. Technology Decision Area: In this area, we work with the technology for each
layertofacilitate thefinal solution.
5. Security Decision Area: After going through the implementation of technology it
isimportantto decide andprovidethe securityat each stageof the IoTStack.
6. Standards & Regulations Decision Area: At the last stage of IoT Decision Area,
weidentify the standards and regulations of product or services that will affect
yourproductat each layer oftheIoT Stack.
3.1.7. IoTArchitecture
There is not such a unique or standard consensus on the Internet of Things (IoT)
architecturewhich is universally defined. The IoT architecture differs from their functional
area and
theirsolutions.However,theIoTarchitecturetechnologymainlyconsistsoffourmajorcomponents:
ComponentsofIoT Architecture
o Sensors/Devices
o Gateways andNetworks
o Cloud/ManagementServiceLayer
o ApplicationLayer
There are several layers of IoT built upon the capability and performance of IoT
elementsthatprovidestheoptimalsolutiontothebusinessenterprisesandend-
users.TheIoTarchitectureisafundamentalwaytodesignthevariouselementsofIoT,sothatitcandel
iverservices over thenetworksand servethe needs forthefuture.
StagesofIoTSolutionsArchitecture
Followingaretheprimarystages(layers)ofIoTthatprovidesthesolutionforIoTarchitecture.
1. Sensors/Actuators: Sensors or Actuators are the devices that are able to emit,
acceptandprocessdataoverthenetwork.Thesesensorsoractuatorsmaybeconnectedeither
through wired or wireless. This contains GPS, Electrochemical,
Gyroscope,RFID,etc.Mostofthesensorsneedconnectivitythroughsensorsgateways.The
98|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
3.1.8. DifferenceBetweenIoTDevicesandComputers
we will discuss the overview of the Internet of Things and Computers and mainly will
focusonthe differencebetween IoTdevicesand Computers.Let’s discussit one by one.
InternetofThings(IoT):
TheInternetofThings(IoT)isthenetworkofphysicalobjects/deviceslikevehicles,buildings, cars,
and other items embedded with electronics, software, sensors, and networkconnectivity that
enables these objects to collect and exchange data. IoT devices have madehuman life easier.
The IoT devices like smart homes, smartcars havemade the life ofhumansvery comfortable.
IoTdevicesarenowbeing apartofour day-to-daylife.
99|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Computers:
A computer is a hardware device embedded with software in it. The computer does most
ofthe work like calculations, gaming, web browsers, word processors, e-mails, etc. The
mainfunction of a computer is to compute the functions, to run the programs. It takes input
fromthecomputer and thencomputes/processesit andgenerates theoutput.
FunctionofComputer
3.2. OverviewofIoTVsComputers
One big difference between IoT devices and computers is that the main function of
IoTdevices is not to compute(not to be a computer) and the main function of a computer is
tocompute functions and to run programs. But on IoT devices that is not its main point, it
hassome other function besides that. As an example like in cars, the function of IoT devices
arenottocomputeanti-lockbreakingortodofuelinjection,theirmainfunctionfromthepointof view
of a user is to be driven and to move you from place to place and the computer is justto help
that function. For example, The main function of the car is not to compute like anti-lock
breaking or to do fuel injection their main function from the point of view of a user is
todrive, to move you from place to place. But when we embed software in it then the
softwarecanbeable forfuel limit detection.
3.2.1.DifferencebetweenIoTdevicesandComputers:
IOTDevices Computers
IoTdevicesarespecial-purposedevices. Computersaregeneral-purposedevices.
IoTdevicescandoonlyaparticulartaskfor
Computerscan doso manytasks.
which it is designed.
100|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
IOTDevices Computers
TogetstartedwithIoTdevicediscoveryinyournetwork,allyouneedisasecuritydeviceconnectedto
Juniper ATP Cloud.
IoTDeviceDiscovery andPolicy EnforcementTopology
As shown in the topology, the network includes some IoT devices connected to an
SRXSeries device through wireless access point (AP). The security device is connected to
theJuniperCloud ATP server, and to a host device.
The security device collects IoT device metadata and streams the relevant information to
theJuniper ATP Cloud. To enable streaming of IoT metadata, you'll need to create
securitymetadata streaming policies and attach these policies to security policies. Streaming
of theIoT device traffic pauses automatically when Juniper Cloud server has sufficient details
toclassifytheIoT device.
Juniper ATP cloud discovers and classifies IoT devices. Using the inventory of
discoveredIoT devices, you'll create threat feeds in the form of dynamic address groups.
Once thesecurity device downloads dynamic address groups, you can use the dynamic
address groupstocreateand enforcesecuritypolicies fortheIoTtraffic.
Requirements
SRXSeriesdeviceorNFXSeriesdevice
101|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
JunosOSRelease22.1R1orlater
JuniperAdvancedThreatPreventionCloudAccount .We've verifiedand
testedtheconfigurationusing a vSRX instance with JunosOSRelease 22.1R1.
3.3. IoTConfiguration
1. Access
o Be sure the device’s access control does not allow unauthorized
orunauthenticatedaccessandthatappropriaterestrictionsareinplace.
o Change the default password to something complex with 16 characters
ormoreif feasible.
o Makesurenomanagementinterfaceisaccessedoveranunencryptedchannel(e.g.u
seHTTPS rather than HTTPand disable thelatter).
o ForRaspberryPiDevices:
Makesudo requireapassword.
Modify the sshd configuration to allow only specific users for
SSHaccess.
Usekey-basedauthenticationasanalternativetoapasswordlogin.
o For printers, disable any unnecessary services. Disable the following
wherepossible,astheyare commonlyvisiblewithoutausernameorpassword:
Internalstorageorjobforwarding
Joblogs
Printqueue
Devicemanagementlogs
2. Softwareupdates
1. Keep the device software updated with the latest security patches
andfirmware.
Somepatchescan revert orchangepasswords.
3. Services
1. Disable all unused services, such as telnet, ssh, FTP/TFTP, MySQL,
email,web proxy, SLP/Device Announcement Agent, WS-Discovery/XML
Services,Web Services Print, WINS, LLMNR, IPX/SPX, DLC/LLC,
Multicast IPv4,FileAccess Settings (JPL Disk Access,SNMP Disk Access,
etc.).
2. Forprinters:
Automatically delete data after the printing process is
complete.Options can be set for how long data can be resident on
the printer –setto lowest timeavailable.
102|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
3.4.ComponentsofIoTSystem
Whatarethemajor componentsofInternetofThings?
103|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
3.4.1. IoTComponents
1. Smartdevicesandsensors–Deviceconnectivity
Devicesandsensorsarethecomponentsofthedeviceconnectivitylayer.Thesesmartsensors are
continuously collecting datafrom theenvironment and transmit the informationto the next
layer.The latest techniques in semiconductor technology are capable of producingmicrosmart
sensors for various applications.
Commonsensorsare:
Temperaturesensorsand thermostats
Pressuresensors
Humidity/ Moisturelevel
Lightintensitydetectors
Moisturesensors
Proximitydetection
RFIDtags
Howarethedevicesconnected?
Most modern smart devices and sensors can be connected to low-power wireless
networkslike Wi-Fi, ZigBee, Bluetooth, Z-wave, LoRAWAN, etc. Each of these wireless
technologieshasits pros andcons in termsof power, data transferrate, and overallefficiency.
IoT Gateway manages the bidirectional data traffic between different networks
andprotocols. Another function of the gateway is to translate different network protocols
andmakesureinteroperability of theconnected devices and sensors.
104|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
IoT gateway offers a certain level of security for the network and transmitted data
withhigher-order encryption techniques.It acts as a middle layer between devices and the
cloudtoprotect thesystem frommalicious attacks andunauthorized 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 accessthesedata remotely andmakecritical decisions when necessary.
Cloud system integrates billions of devices, sensors, gateways, protocols, and data
storageand provides predictive analytics. Companies use these analytics data to improve
productsand services, preventive measures for certain steps, and build their new business
modelaccurately.
4. Analytics
Analytics is the process of converting analog data from billions of smart devices
andsensors into useful insights which can be interpreted and used for detailed analysis.
SmartanalyticssolutionsareinevitableforIoTsystemsforthemanagementandimprovementofthee
ntiresystem.
One of the major advantages of an efficient IoT system is real-time smart analytics
whichhelpsengineerstofindoutirregularitiesinthecollecteddataandactfasttopreventan
105|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
undesired scenario.Service providers can prepare for further steps if the information
iscollectedaccurately at theright time.
Big enterprises use the massive data collected from IoT devices and utilize the insights
fortheir future business opportunities. Careful analysis will help organizations to predict
trendsinthemarket and planahead for asuccessful implementation.
Information is very significant in any business model, and predictive analysis ensures
successintheconcerned areaof thebusiness line.
5. Userinterface
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
forusersand encouragemoreinteractions.
Modern technology offers much interactive design to ease complex tasks into simple
touchpanelcontrols.Multicolortouchpanelshavereplacedhardswitchesinourhouseholdappliance
s,and thetrendis increasingforalmost everysmart homedevice.
The user interface design has higher significance in today’s competitive market; it
oftendeterminestheuserwhethertochooseaparticulardeviceorappliance.Userswillbeinterested
in buying new devices or smart gadgets if it is very user-friendly and
compatiblewithcommon wireless standards.
3.4.2. RealLifeExampleDepictingWorkingofIoT
Here,wewilldiscusssomeexamples,which stateshow IoTworksinreal-life:
106|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
i. Say,we have anACinour room, now the temperature sensor installedinit in the roomwill be
integrated with a gateway. A gateway’s purpose is to help connect the
temperaturesensor(insidetheAC)totheInternet by making useofacloud infrastructure.
ii. A Cloud/server infrastructure has detailed records about each and every device
connectedto it such as device id, a status of the device, what time was the device last
accessed, numberoftimes thedevicehas been accessed and muchmore.
iii. A connection with the cloud then implement by making use of web services such
asRESTful.
iv. Weinthissystem,actasend-
usersandthroughthemobileappinteractwithCloud(andinturndevicesinstalledinourhomes).Areq
uestwillsendtothecloudinfrastructurewiththe authentication of the device and device
information. It requires authentication of thedeviceto ensurecybersecurity.
v. Once the cloud has authenticated the device, it sends a request to the appropriate
sensornetworkusing gateways.
vi. After receiving the request, the temperature sensor inside the AC will read the
currenttemperaturein theroomand willsend theresponseback to thecloud.
vii. Cloud infrastructure will then identify the particular user who has requested the data
andwill then push the requested data to the app. So, a user will get the current information
aboutthetemperatureintheroom,pickupthroughAC’stemperaturesensorsdirectlyonhisscreen.
RealLifeExample–InternetofThings works
3.5. Arduino
Adecadeago,workingaroundelectronicsinvolvedknowledgeinphysicsandmath,expensive lab
equipment, a laboratory type setup and important of all, love for
electronics.Butthepicturehaschangedoverthedecadeorsowheretheabove-
mentionedfactorsbecame irrelevant to work around electronics except for the last part: love
for electronics.Onesuch product which made use of the above specified and many other
reasons and madeelectronicsbeablereachanyoneregardlessoftheir background is“Arduino”.
3.5.1. Introduction
Arduino is an open-source prototyping platform in electronics based on easy-to-use
hardwareandsoftware.Subtlyspeaking,Arduinoisamicrocontrollerbasedprototypingboardwhic
h
107|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
canbeusedindevelopingdigitaldevicesthatcanreadinputslikefingeronabutton,touchon a screen,
light on a sensor etc. and turning it in to output like switching on an LED,rotatingamotor,
playing songs through aspeakeretc.
TheArduinoboardcanbeprogrammedtodoanythingbysimplyprogrammingthemicrocontrollero
nboardusingasetofinstructionsforwhich,theArduinoboardconsistsofa USB plug to
communicate with your computer and a bunch of connection sockets that canbewired to
external devices likemotors, LEDs etc.
The aim of Arduino is to introduce the world of electronics to people who have small to
noexperiencein electronicslikehobbyists, designers, artists etc.
108|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
componentsasperthedesignspecification,assembleallthecomponents,andmakeyourownboard.
3.5.2. HardwareandSoftware
Arduino boards are generally based on microcontrollers from Atmel Corporation like 8, 16
or32bit AVR architecturebased microcontrollers.
TheimportantfeatureoftheArduinoboardsisthestandardconnectors.Usingtheseconnectors, we
can connect the Arduino board to other devices like LEDs or add-on modulescalledShields.
The Arduino boards also consists of on board voltage regulator and crystal oscillator.
Theyalso consist of USB to serial adapter using which the Arduino board can be
programmedusingUSB connection.
In order to program the Arduino board, we need to use IDE provided by Arduino.
TheArduinoIDEisbased onProcessingprogramminglanguageandsupports CandC++.
3.5.3. TypesofArduinoBoards
There are many types of Arduino boards available in the market but all the boards have
onething in common: they can be programmed using the Arduino IDE. The reasons for
differenttypesofboardsaredifferentpowersupplyrequirements,connectivityoptions,theirapplicat
ionsetc.
Arduino boards are available in different sizes, form factors, different no. of I/O pins
etc.SomeofthecommonlyknownandfrequentlyusedArduinoboardsareArduinoUNO,Arduino
Mega, ArduinoNano, Arduino Micro andArduino Lilypad.
109|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Step1:TypesofArduino
3.5.3.1. ArduinoUNO
The most common version of Arduino is the Arduino Uno. This board is what
mostpeople are talking about when they refer to an Arduino. In the next step, there is a
morecompleterundown ofitsfeatures.
3.5.3.3. ArduinoMega2560
The Arduino Mega 2560 is the second most commonly encountered version of the
Arduinofamily. The Arduino Mega is like the Arduino Uno's beefier older brother. It boasts
256 KBof memory (8 times more than the Uno). It also had 54 input and output pins, 16 of
which areanalog pins, and 14 of which can do PWM. However, all of the added functionality
comes atthe cost of a slightly larger circuit board. It may make your project more powerful,
but it willalso make your project larger. Check out the official Arduino Mega 2560 page for
moredetails.
3.5.3.4. ArduinoMegaADK
110|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
ThisspecializedversionoftheArduinoisbasicallyanArduinoMegathathasbeenspecifically
designed for interfacing with Android smartphones. This too is now a legacyversion.
3.5.3.5. ArduinoYun
The Arduino Yun uses a ATMega32U4 chip instead of the ATmega328. However,
whatreally sets it apart is the addition of the Atheros AR9331 microprocessor. This extra
chipallows this board to run Linux in addition to the normal Arduino operating system. If all
ofthat were notenough, italso has onboard wifi capability. In other words, you can
programthe board to do stuff like you would with any other Arduino, but you can also access
theLinux side of the board to connect to the internet via wifi. The Arduino-side and Linux-
sidecantheneasilycommunicatebackandforthwitheachother.Thismakesthisboardextremely
powerful and versatile. I'm barely scratching the surface of what you can do withthis,but to
learn more, check out theofficialArduino Yun page.
3.5.3.6. ArduinoNano
If you want to go smaller than the standard Arduino board, the Arduino Nano is for
you!Based on a surface mount ATmega328 chip, this version of the Arduino has been
shrunkdown to a small footprint capable of fitting into tight spaces. It can also be inserted
directlyintoabreadboard, making it easy to prototypewith.
3.5.3.7. ArduinoLilyPad
The LilyPad was designed for wearable and e-textile applications. It is intended to be sewn
tofabricandconnected toother sewable componentsusingconductive
thread.Thisboardrequirestheuseofaspecial FTDI-
USBTTLserialprogrammingcable.Formoreinformation,theArduinoLilyPad page is
adecentstarting point.
(Note that some of the links on this page are affiliate links. This does not change the cost
ofthe item for you. I reinvest whatever proceeds I receive into making new projects. If
youwouldlikeany suggestions foralternativesuppliers,pleaselet me know.)
Step2:ArduinoUnoFeatures
Some people think of the entire Arduino board as a microcontroller, but this is
inaccurate.TheArduinoboardactuallyisaspeciallydesignedcircuitboardforprogrammingandprot
otypingwith Atmelmicrocontrollers.
The nice thing about the Arduino board is that it is relatively cheap, plugs straight into
acomputer's USB port, and it is dead-simple to setup and use (compared to other
developmentboards).
Someofthe keyfeaturesoftheArduino Unoinclude:
Anopensourcedesign.Theadvantageofitbeingopensourceisthatithasa
largecommunityofpeopleusingandtroubleshootingit.Thismakesiteasytofindsomeonetohelpyou
debug yourprojects.
111|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
An easy USB interface . The chip on the board plugs straight into your USB port
andregisters on your computer as a virtual serial port. This allows you to interface with it
asthrough it were a serial device. The benefit of this setup is that serial communication is
anextremelyeasy(andtime-
tested)protocol,andUSBmakesconnectingittomoderncomputersreally convenient.
Very convenient power management and built-in voltage regulation. You can connect
anexternal power source of up to 12v and it will regulate it to both 5v and 3.3v. It also can
bepowereddirectly offof a USB port withoutany external power.
An easy-to-find, and dirt cheap, microcontroller "brain." The ATmega328 chip retails
forabout $2.88 on Digikey. It has countless number of nice hardware features like timers,
PWMpins,externalandinternalinterrupts,andmultiplesleepmodes. Check out
theofficialdatasheet formoredetails.
A 16mhz clock. This makes it not the speediest microcontroller around, but fast enough
formostapplications.
32KB offlash memory forstoringyour code.
13 digital pins and 6 analog pins. These pins allow you to connect external hardware to
yourArduino. These pins are key for extending the computing capability of the Arduino into
thereal world. Simply plug your devices and sensors into the sockets that correspond to each
ofthesepins and you aregood to go.
An ICSP connector for bypassing the USB port and interfacing the Arduino directly as
aserial device. This port is necessary to re-bootload your chip if it corrupts and can no
longertalkto your computer.
Anon-boardLEDattachedtodigitalpin 13forfastaneasydebuggingof code.
Andlast,but notleast, abutton toresettheprogramon thechip.
Step3:ArduinoIDE
112|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
BeforeyoucanstartdoinganythingwiththeArduino,youneedtodownloadandinstallthe
ArduinoIDE (integrateddevelopmentenvironment).Fromthispointonwewillbereferringto the
ArduinoIDE as theArduino Programmer.
The Arduino Programmer is based on the Processing IDE and uses a variation of the C
andC++programming languages.
YoucanfindthemostrecentversionoftheArduinoProgrammeronthis page.
Step4: PlugIt In
ConnecttheArduinotoyourcomputer'sUSBport.
Please note that although the Arduino plugs into your computer, it is not a true USB
device.The board has a specialchipthat allows it to show up on your computer as a virtual
serialport when it is plugged into a USB port. This is why it is important to plug the board
in.When the board is not plugged in, the virtual serial port that the Arduino operates upon
willnotbe present (sinceallof theinformationaboutit liveson theArduino board).
ItisalsogoodtoknowthateverysingleArduinohasauniquevirtualserialportaddress.This means
that every time you plug in a different Arduino board into your computer, youwillneed to
reconfiguretheserial port that is in use.
113|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Step5:Settings
BeforeyoucanstartdoinganythingintheArduinoprogrammer,youmustsettheboard-typeandserial
port.
To set the board, go to the
following:Tools-->Boards
Selecttheversionofboardthatyouareusing.SinceIhaveanArduinoUnopluggedin,Iobviouslyselec
ted "Arduino Uno."
To set the serial port, go to the
following:Tools-->Serial Port
Selecttheserialportthatlookslike:
/dev/tty.usbmodem[randomnumbers]
114|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Step6:RunaSketch
Arduinoprogramsarecalledsketches.TheArduinoprogrammercomeswithatonofexample
sketches preloaded. This is great because even if you have
neverprogrammedanythinginyourlife,youcanloadoneofthesesketchesandgettheArduinotodoso
mething.
Oncetheblinkexampleisopen,itcanbeinstalledontotheATMEGA328chipbypressingtheupload
button, which looks like an arrowpointing to the right.
Notice that the surface mount status LED connected to pin 13 on the Arduino will start
toblink. You can change the rate of the blinking by changing the length of the delay
andpressingthe upload button again.
Step7:SerialMonitor
115|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
TheserialmonitorallowsyourcomputertoconnectseriallywiththeArduino.Thisisimportant
because it takes data that your Arduino is receiving from sensors and other devicesand
displays it in real-time on your computer. Having this ability is invaluable to debug
yourcodeand understand what number valuesthechipis actually receiving.
For instance, connect center sweep (middle pin) of a potentiometer to A0, and the outer
pins,respectively,to 5v and ground.Next uploadthe sketch shown below:
File-->Examples -->1.Basics-->AnalogReadSerial
Click the button to engage the serial monitor which looks like a magnifying glass. You
cannow see the numbers being read by the analog pin in the serial monitor. When you turn
theknobthe numbers will increaseand decrease.
116|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Thenumberswillbebetweentherangeof0and1023.Thereasonforthisisthattheanalogpinis
converting avoltagebetween 0 and5V to adiscreet number.
Step8:DigitalIn
The Arduino has two different types of input pins, those being analog and
digital.Tobegin with, lets look at thedigital input pins.
Digitalinputpinsonlyhavetwopossiblestates,whichareonoroff.Thesetwoonandoffstatesare also
referred toas:
HIGHorLOW
1 or 0
5Vor0V.
This input is commonly used to sense the presence of voltage when a switch is opened
orclosed.
Digital inputs can also be used as the basis for countless digital communication protocols.
Bycreating a 5V (HIGH) pulse or 0V (LOW) pulse, you can create a binary signal, the basis
ofall computing. This is useful for talking to digital sensors like a PING ultrasonic sensor,
orcommunicatingwith other devices.
For a simple example of a digital input in use, connect a switch from digital pin 2 to 5V,
a10Kresistor** from digital pin 2to ground, and run thefollowing code:
File-->Examples -->2.Digital -->Button
**The 10K resistor is called a pull-down resistor because it connects the digital pin to
groundwhen the switch is not pressed. When the switch is pressed, the electrical connections
in theswitch has less resistance than the resistor, and the electricity no longer connects to
ground.Instead, electricity flows between 5V and the digital pin. This is because electricity
alwayschoosesthepath ofleastresistance.To learnmore about this,visit theDigital Pins page.
Step9:AnalogIn
117|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Aside from the digital input pins, the Arduino also boasts a number of analog input
pins.Analoginputpinstakeananalogsignalandperforma10-bitanalog-to-
digital(ADC)conversionto turn it into a numberbetween 0 and1023 (4.9mV steps).
This type of input is good for reading resistive sensors. These are basically sensors
whichprovide resistance to the circuit. They are also good for reading a varying voltage
signalbetween0and5V.This isusefulwheninterfacingwith varioustypesofanalogcircuitry.
If you followed the example in Step 7 for engaging the serial monitor, you have already
triedusingan analog input pin.
Step10:DigitalOut
A digital out pin can be set to be HIGH (5v) or LOW (0v). This allows you to turn things
onandoff.
Aside from turning things on and off (and making LEDs blink), this formof output
isconvenientforanumber 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
electronicdevices as a binary signal. By using this method, you can communicate using a
number ofdifferentprotocols.
118|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Digital communication is an advanced topic, but to get a general idea of what can be
done,checkout theInterfacingWith Hardware page.
If you followed the example in Step 6 for getting an LED to blink, you have already
triedusingadigital output pin.
Step11:AnalogOut
As mentioned earlier, the Arduino has a number of built in special functions. One of
thesespecial functions is pulse width modulation, which is the way an Arduino is able to
create ananalog-likeoutput.
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 onandoffrapidlyenough(aboutfivemillisecondseach),itwouldseemtoaveragethebrightness
and only appear to be receiving half the power. Alternately, if it were to blink onfor 1
millisecond and then blink off for 9 millisecond, the LED would appear to be 1/10
asbrightandonly be receiving 1/10 the voltage.
PWM is key for a number of applications including making sound, controlling the
brightnessoflights, and controlling thespeed of motors.
TotryoutPWMyourself,connectanLEDand220ohmresistortodigitalpin9,inseriestoground.Run
the following examplecode:
File-->Examples-->3.Analog-->Fading
Step12: WriteYour Own Code
119|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
To write your own code, you will need to learn some basic programming language syntax.
Inotherwords,youhavetolearnhowtoproperlyformthecodefortheprogrammertounderstandit.Yo
ucanthinkofthiskindoflikeunderstandinggrammarandpunctuation.You can write an entire
book without proper grammar and punctuation, but no one will beablerto understand it, even
if it is in English.
1. The sketch usually starts with a header that explains what the sketch is doing, and
whowroteit.
2. Next, it usually defines global variables. Often, this is where constant names are
giventothedifferent Arduinopins.
3. After the initial variables are set, the Arduino begins the setup routine. In the
setupfunction,wesetinitialconditionsofvariableswhennecessary,andrunanypreliminary
code that we only want to run once. This is where serial communication
isinitiated,which is required forrunning theserial monitor.
120|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
4. From the setup function, we go to the loop routine. This is the main routine of
thesketch. This is not only where your main code goes, but it will be executed over
andover,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
thesefunctions are called, the Arduino processes all of the code in the function from
top tobottom and then goes back to the next line in the sketch where it left off when
thefunctionwascalled.Functionsaregoodbecausetheyallowyoutorunstandardroutines -
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 onthe chip
because the function routine is only written once. It also makes code easier toread.
Allofthatsaid,theonlytwopartsofthesketchwhicharemandatoryaretheSetupandLooproutines.
Codemust bewritten inthe ArduinoLanguage, which isroughly basedonC.
Almostallstatements writtenintheArduinolanguagemustendwith a;
Conditionals(suchas ifstatements andforloops) do notneed a;
Conditionalshavetheirownrulesandcanbefoundunder"ControlStructures"ontheArduino
Language
Variablesare storage compartments for numbers. You canpass values into and out
ofvariables. Variables must be defined (stated in the code) before they can be used and need
tohaveadatatypeassociatedwithit.Tolearnsomeofthebasicdatatypes,reviewtheLanguagePage.
Step13:Shields
Shields are expansion apdapter boards that plug in over top of the Arduino Uno and gives
itspecialfunctions.
Since the Arduino is open hardware, anyone who has the inclination is free to make
anArduino shield for whatever task they wish to accomplish. On account of this, there
arecountlessnumberofArduinoshieldsoutinthewild.Youcanfindanever-growinglistof Arduino
shields in the Arduino playground. Keep in mind that there will be more shield
inexistencethan youwill find onlisted onthat page(asalways,Googleisyour friend).
Step14:Buildingan ExternalCircuit
121|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
As your projects get more complex, you will want to build your own circuits to
interfacewiththe Arduino. While you won't learn electronics overnight, the internet is an
unbelievableresourcefor electronicknowledgeandcircuit diagrams.
Togetstartedwithelectronics,visitthe BasicElectronicsInstructable.
Step15:GoingBeyond
3.6. ArduinoToolChain
Today we’re going to talk about how the Arduino tool chain converts instructions you
typeintothe text editor intomachine languagethe microcontrollercan understand.
A tool chain is simply a set of software tools that work together to complete a task.
forexample, if we were going to hang a picture, the tool chain might include a hammer,
maybe atapemeasureand somenails.
ArduinoHardware/SoftwareInterface
122|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
WhenprogrammingtheArduino(oranythingelse),itispossibletowritesomeprettycomplexinstruct
ions and gettheArduino to dosomereally cool things.
The problem is that a microcontroller (like the ATmega328 on the Uno) can only
executesimple, low-level instructions. These simple instructions include things like add
variable a tovariablebortake variable b and put it in register x.
And, to complicate matters, microcontrollers only speak in binary.For those who don’tknow,
binary numbers are long strings of 1s and 0s. If you need to brush up on binarynumbers,seeA
Bit ofFun with Binary Number Basics.
Arduinoandothermicrocontrollersonlyunderstandbinary.
The statement here may make total sense to you if you’ve been working with Arduino for
awhile. Or, if not, it may not make any sense at all. Either way, just go with me here for
aminute.Thisisjustanillustrationwhichdoesnotrequirecompleteunderstandingofthecode.
Int Temp =
analogRead(sensorPin);If(T
emp>500)
{
//morecomplexinstructionsgohere
}
A good way to think of binary numbers and digital signals is like a single pole light
switch.Thelight is eitheron or itsoff, thereisnothing in between.Zero is off andoneison.
123|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
HowtheArduinoCompilerWorks
The compiler first transforms the code you write into assembly language. The name of
thecompiler we’ll be using on our Uno is AVR-GCC. If you’re new to this, that may sound
kindofweird but try not to obsessoverit.It’s just a name.
The assembler, which come with the IDE with the compiler, then translates the
assemblylanguageprogramintomachinelanguage.Itthencreatesobjectfiles,whichcombinemachi
ne language, data, and information it needs to place instructions properly in
memory.Often,theassemblercreates multiple fileswhich will eventuallybe put together.
This is where the linker — another part of the compiler software package — shines.
Thelinker will take all the independently assembled machine language programs and object
filesand put them together. This produces a .hex file that the microprocessor can understand
andrun.
The two figures below, though they apply to C/C++ programming in general, are a
goodillustrationofthis process.
124|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
anotherwaytovisualizetheArduinocodecompilation process.
Another piece of software, called AVR Dude (for Downloader UploaDEr) starts when
wepress the upload button. This software sends the .hex file to the ATMega328 on the
Arduinoboard. On the chip resides the bootloader. This bootloader was put there on purpose
by thefolksatArduinoandworkswithAVRDudetogetthe.hexintotheflashmemoryonthechip.
Allofthis happensveryquicklyand seamlesslybehind thescenesof theArduino IDE.
ProgramminginC vsArduino
125|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
AfewwordsareinorderonthissubjectduetotheenormouspopularityofArduinoboardsandthe
C/C++languagein general.
Others use platforms or ecosystems such as the Arduino almost (or entirely)
exclusively.Finally,someof you may usebothdepending onyourgoals and background.
When we talk about programming the Arduino, we’ll talk about the C/C++ languages.
Thetruthis,sketchesarewritteninalanguagesimilartoC,thoughasketchitselfisnotcompletelycom
patiblewith 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
absolutelyrequires:setup()and loop(). Theonlyfunction C requires ismain().
Calsolacksbuilt-infunctionsforusingmicrocontrollerI/OsuchasdigitalWrite().
To make learning simple, the Arduino IDE designers hide a lot of detail and
functionalitybehind layers of abstraction, many of which come in the form of libraries. Note
that the Cprogramminglanguage also useslibraries.Thelinkeraddsthem duringthe linking
process.
3.7. Arduinoprogramstructure
ArduinoprogramstructureandwewilllearnmorenewterminologiesusedintheArduino
world.TheArduinosoftwareisopen-
source.ThesourcecodefortheJavaenvironmentisreleasedundertheGPLandtheC/C++
microcontrollerlibrariesareundertheLGPL.
Sketch:ThefirstnewterminologyistheArduinoprogramcalled“sketch”.
3.7.1. StructureArduinoprogramscanbedividedinthreemainparts:Structure,Values(vari
ablesandconstants),andFunctions.wewilllearnabouttheArduinosoftwareprogram,stepbyst
ep,andhowwecanwritetheprogramwithoutanysyntaxorcompilationerror.Letusstartwiththe
Structure.Softwarestructureconsistoftwomainfunctions:
Setup()function
Loop()function
126|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
PURPOSE:Thesetup()functioniscalledwhenasketchstarts.Use ittoinitialize
thevariables,pin modes,startusinglibraries,etc. The setup functionwillonlyrunonce,
after each poweruporreset oftheArduinoboard.
PURPOSE:Aftercreatingasetup()function,whichinitializesandsetsthe
initialvalues,theloop()functiondoespreciselywhatitsnamesuggests,andloopsconsecutively,all
owingyourprogramtochangeandrespond.UseittoactivelycontroltheArduinoboard.
2. Arduino–DataTypes
DatatypesinCreferstoanextensivesystemusedfordeclaringvariablesorfunctionsof
differenttypes.Thetypeofavariabledetermineshowmuchspaceitoccupiesinthestorageandh
owthebitpatternstoredisinterpreted.
ThefollowingtableprovidesallthedatatypesthatyouwilluseduringArduinoprogramming.
void
Thevoidkeywordisusedonlyinfunctiondeclarations.Itindicatesthatthefunction
is
expectedtoreturnnoinformationtothefunctionfromwhichitwascalled.
127|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Boolean
ABooleanholdsoneoftwovalues,trueorfalse.EachBooleanvariableoccupiesonebyteofmemory.
Char
Adatatypethattakes uponebyteof memory thatstores a
charactervalue.Characterliteralsarewritteninsinglequoteslikethis:'A'andformultip
lecharacters,stringsusedoublequotes:"ABC".
However,charactersarestoredasnumbers.YoucanseethespecificencodingintheASCII
chart.Thismeansthatitispossibletodoarithmeticoperationsoncharacters,inwhichtheASCIIvalueofthecharacteri
sused.Forexample,'A'+1hasthevalue66,sincetheASCIIvalueofthecapitalletterAis65.
3.7.2. ASCIICharTable
unsignedchar
Unsignedchar isanunsigneddata type thatoccupies onebyte of
memory.Theunsignedchardatatypeencodes numbers from 0 to 255.
128|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
byte
Example
UnsignedCharchr_y=121;//declarationofvariablewithtypeUnsignedcharandinitializeit with
character y
Int
Example
bytem=25;//declarationofvariablewithtypebyteandinitializeitwith25
Integersarethe primary data-typefor numberstorage.int storesa16-bit (2-byte)value.
129|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Thisyieldsarangeof-32,768to32,767(minimumvalueof-2^15andamaximumvalueof(2^15)-1).
Theintsizevariesfromboardtoboard.On theArduinoDue,forexample,anintstoresa
32-bit(4-byte)value.Thisyieldsarangeof-2,147,483,648to2,147,483,647(minimumvalueof-
2^31and amaximum valueof (2^31)-1).
Example
intcounter=32;//declarationofvariablewithtypeintandinitializeitwith32
Unsignedint
Unsignedints(unsignedintegers)arethesameasintinthewaythattheystorea2bytevalue. Instead of
storing negative numbers, however, they only store positive values, yieldinga useful range of
0 to 65,535 (2^16) - 1). The Due stores a 4 byte (32-bit) value, ranging from0 to
4,294,967,295 (2^32 -1).
Example
Unsignedintcounter=60;//declarationofvariablewithtypeunsignedintandinitializeitwith60
Word
OntheUnoandotherATMEGAbasedboards,awordstoresa16-bitunsignednumber.OntheDueand
Zero, it stores a32-bit unsigned number.
Example
wordw=1000;//declarationofvariablewithtypewordandinitializeitwith1000
Long
Longvariablesareextendedsizevariablesfornumberstorage,andstore32bits(4bytes),from2,147,4
83,648 to 2,147,483,647.
Example
Longvelocity=102346;//declarationofvariablewithtypeLongandinitializeitwith102346
unsignedlong
Unsigned long variables are extended size variables for number storage and store 32 bits
(4bytes).Unlikestandardlongs,unsignedlongswillnotstorenegativenumbers,
makingtheirrangefrom 0 to 4,294,967,295 (2^32-1).
UnsignedLongvelocity=101006;//declarationofvariablewithtypeUnsignedLongand
initializeit with 101006
130|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
short
Ashortis a16-bitdata-type. OnallArduinos (ATMegaandARM based),ashort storesa
16-bit(2-byte)value.Thisyieldsarangeof-32,768to32,767(minimumvalueof-
2^15andamaximum value of(2^15) -1).
Float
shortval=13;//declarationofvariablewithtypeshortandinitializeitwith13
Data type for floating-point number is a number that has a decimal point. Floating-
pointnumbers are often used to approximate the analog and continuous values because they
havegreaterresolution than integers.
double
OntheUnoandotherATMEGAbasedboards,Doubleprecision floating-pointnumber occupies
four bytes. That is, the double implementation is exactly the sameasthefloat, with no
gain in precision. On the Arduino Due, doubles have 8-byte (64 bit)precision.
3. Arduino–VariablesandConstant
Before we start explaining the variable types, a very important subject we need to make
sure,youfully understand is called the variablescope.
LocalVariables
Variables that are declared inside a function or block are local variables. They can be
usedonly by the statements that are inside that function or block of code. Local variables are
notknowntofunction outsidetheir own.Following isthe exampleusing localvariables:
131|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
GlobalVariablesGlobalvariablesaredefinedoutsideofallthefunctions,usuallyatthe
topoftheprogram. Theglobalvariableswillholdtheirvaluethroughoutthelife-
timeofyourprogram.
Aglobalvariablecanbeaccessedbyanyfunction.Thatis,aglobalvariableisavailable
forusethroughoutyourentireprogramafteritsdeclaration.
Thefollowingexampleusesglobalandlocalvariables:
3.7.3. Arduino-Operators
132|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
ArithmeticOperators
Assumevariable Aholds10andvariableBholds20then−
Operator Operator Description Example
name simple
ModulusOperatorandremainderofafteranin
modulo % B%A will give0
teger division
ComparisonOperators
Assumevariable Aholds10andvariableBholds20then−
Checksifthevalueofleftoperandislessthanthevalueof (A<B)is
lessthan <
rightoperand,ifyesthencondition true
133|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
becomestrue.
BooleanOperators
Assumevariable Aholds10andvariableBholds20then−
Operator Operator Description Example
name simple
CalledLogicalANDoperator.Ifboththeoperandsaren (A&&B)istrue
and &&
on-zero thenthen conditionbecomes true.
CalledLogicalOROperator.Ifanyofthetwooperands
or || is non-zero then then condition becomestrue. (A||B) is true
BitwiseOperators
Assumevariable Aholds60andvariableBholds13then−
Operator Operator Description Example
name simple
BinaryANDOperatorcopiesabittotheresultifit (A&B)willgive12wh
and &
exists in both operands. ichis 0000 1100
BinaryOROperatorcopiesabitifitexistsineithero (A|B)willgive61which
or |
perand is 0011 1101
BinaryXOROperatorcopiesthebitifitissetinone (A^B)willgive49whi
xor ^
operand but notboth. chis 0011 0001
134|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
BinaryOnesComplementOperatorisunaryandha (~A)willgive-
not ~
s the effect of 'flipping' bits. 60whichis 1100
0011
Binary Left Shift Operator. The left
A<<2willgive240
shiftleft << operandsvalueismovedleftbythenumberofbitss
whichis 1111 0000
pecifiedby the right operand.
CompoundOperators
Assumevariable Aholds10andvariableBholds20then−
Operator Operator Description Example
name simple
Incrementoperator,increasesintegervalueby A++willgive11
increment ++
one
Decrementoperator,decreasesintegervalueby
decrement -- A--will give9
one
135|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
compound A&=2issameas
&= BitwiseANDassignmentoperator
bitwiseand A =A & 2
ArduinoIDE
TheArduinoIDEisvery simpleandeasytouse.
Let’s see how to use it with the help of Blink example that comes in the Built-In
exampleswiththeIDE.
1. Openthe Arduino IDE fromthe folderyou installed/unzippedit in.
2. In the File tab, go to the Examples option. Here you will find a list of all the Built-
Inexamples that come along with the IDE. You will also see Examples For Any Board in
belowtheBuilt-In examples.
Here,wewill seetheBlink examplewhich blinkstheLEDonthe Arduino board.
3. Once you click on Blink, a new window will open with the sketch (Arduino refers
tocodeswritten in itsIDEas sketch) for Blink.
136|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
4. Before burning this code into the Arduino board, we need to configure the IDE for
theboard we need to burn this sketch into. We also need to select the appropriate
communicationportand the method usedforburning thecode.
5. Go to the Tools tab and find the Board option in it. It will have a list of all the
ArduinoBoardsinit.Selecttheboardyouareusingfromthatlist.Here,wehaveusedArduino/Genuin
oUno Board.
ArduinoandGenuinoareoneandthesamething.OutsidetheUSA,theArduinoboardsarecalledGenu
ino.
6. Nowweneedtoselecttheappropriatecommunicationportoverwhichthecomputer/laptopwillc
ommunicatewiththeArduinoboard.UndertheToolstab,youwill
137|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
findthePortoption.SelecttheportyouhaveconnectedtheArduinoboardtofromthePortsavailablein
this list.
7. Nowthatwehaveselectedtheboardandthecommunicationport,weneedtoselecttheappropriate
programmer.
WewillbeusingtheAVRISPmk2programmer.
138|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Thisisusedtoupload(Arduinorefersburningaprogramasuploading)thesketchonto
the board.
ThisisusedtoopentheserialmonitorthatcomeswiththeArduino IDE.
Note : You can use any other serial terminal program if you want instead of the
Arduinoserial monitor. The serial monitor that comes with Arduino IDE can open only one
serial
portforcommunication.Ifyouneedtoobservemultipleports(multipleArduinoboardsconnectedtot
hesamecomputer/laptop),youneedtouseotherprogramslikePutty,RealTerm,TeraTerm, etc.
139|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
9. Nowthatwehaveselectedtheappropriateboard,communicationport,andtheprogrammer,
weneed to upload the Blink sketchon to the board.
We caneitherverifythesketchbefore
theuploadprocessorskiptheverificationprocess.TheIDEdoesthepartofverifyingthesketchbefore
uploadingasapartoftheuploadprocess.
10. Since this is a built-in example sketch, we will not get any warnings or errors
uponverifying. If there are any warnings or errors, they are displayed by the IDE in the
blackcoloured area below the area for writing code. This area is shown in the image in the
nextpoint,highlighted in red.
11. Now upload the sketch onto the board. When the upload process is done, you will get
adone uploading message. You should be able to see the LED on your Arduino board
blinkingat1 second intervals.
140|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
12. This process needs to be followed for all the sketches that are built-in or created by
theuser.
Understanding how the Arduino IDE sets up its file directory system can spare you
someconfusionwhenitcomestosaving,organizingandopeningyourArduinosketches(orsketches
you havedownloaded from theinternet).
Thisweek’s episodecoversthefollowing:
1. TheArduinoSketchbook folder
2. HowtochangethedefaultlocationwhereyourArduinosketchesgetsaved
3. WhathappenswhenanArduinofiledoesnothaveanenclosingsketchfolderofthesame
name
4. Whereand howmultipletabs getsaved in anArduino sketch
5. Whythe pancreasof awoodchuck isbetter suited than ourown
TheArduinoSketchbookFolderAnd ChangingTheDefaultSaveLocation
ThedefaultlocationwhereArduinosketchesyouwritewillbesavediscalledtheSketchbook.
TheSketchbookissimplyafolderonyourcomputerlikeanyother.Itactsasahandyrepositoryfor
sketches andis also where add-oncodelibraries get saved.
ThedefaultnameoftheSketchbookfolderis“Arduino”andthedefaultlocationoftheSketchbookfol
deris inthe“MyDocuments”folder(or just“Documents”for Macusers).
IfyourSketchbookdoesnotappeartobeinthisdefaultlocation,youcanseeexactlywhereitis by
opening theArduino IDEand goingto Arduino > Preferences.
141|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
ThedefaultfilepathforyoursketchesislistedatthetopofArduinoPreferenceswindow.Mine is:
/Users/michaelJames/Documents/Arduino
When I save a file in the Arduino IDE, this “Arduino” folder is the default location where
thesketch will be saved, unless I choose to change that location by selecting a different folder
onmycomputer’s directory.
If you want to change this default location, you click the Browse button next to the
filedirectorypathand chooseadifferent place.Prettysimple.
3.8. ArduinoSketches
AsketchisthenamethatArduinousesforaprogram.It'stheunitofcodethatisuploadedtoandr
unonanArduinoboard.
ThefirstfewlinesoftheBlinksketchareacomment:
/*
* Blink
*
* ThebasicArduino example. Turnson an LEDon for onesecond,
* thenoff for onesecond,and so on... Weusepin13 because,
* dependingon your Arduino board, it has either a built-in LED
* ora built-inresistor so thatyou needonly an LED.
*/
Everythingbetweenthe
/*
142|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
and
*/
isignored bythe Arduino whenit runs thesketch(the
*
at the start of each line is only there to make the comment look pretty, and isn't required).
It'sthereforpeoplereadingthecode:toexplainwhattheprogramdoes,howitworks,orwhyit's written
the way it is. It's a good practice to comment your sketches, and to keep thecomments up-to-
date when you modify the code. This helps other people to learn from ormodifyyour code.
There'sanotherstyleforshort,single-linecomments.Thesestartwith
//
andcontinuetotheendoftheline.For example,intheline:
1int ledPin = 13;// LED connected to digital pin 13the message "LED connected to
digitalpin13"isacomment.
Variables
A variable is a place for storing a piece of data. It has a name, a type, and a value.
Forexample, the line from the Blink sketch above declares a variable with the name ledPin,
thetype int, and an initial value of 13. It's being used to indicate which Arduino pin the LED
isconnected to. Every time the name ledPin appears in the code, its value will be retrieved.
Inthiscase,thepersonwritingtheprogram couldhavechosennot tobothercreatingthe ledPin
variable and instead have simply written 13 everywhere they needed to specify apin number.
The advantage of using a variable is that it's easier to move the LED to adifferent pin: you
only need to edit the one line that assigns the initial value to the variable.Often,however, the
valueofa variable willchangewhile the sketch runs.For
example,youcouldstorethevaluereadfromaninputintoavariable.
Functions
Afunction(otherwiseknownasaprocedureorsub-
routine)isanamedpieceofcodethatcanbeusedfromelsewhereinasketch.Forexample,here'sthedef
initionofthe
setup()
functionfromtheBlinkexample:
voidsetup()
{
pinMode(ledPin,OUTPUT); //sets thedigitalpin as output
}
Thefirstline provides informationaboutthefunction,like itsname,
"setup".Thetextbeforeandafterthenamespecifyitsreturntypeandparameters:thesewillbeexplaine
dlater.Thecode betweenthe { and } is called the body of the function: what the functiondoes.
143|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
pinMode(),digitalWrite(),anddelay()
ThepinMode()functionconfiguresapinaseitheraninputoranoutput.Touseit,you pass it
the number of the pin to configure and the constant INPUT or OUTPUT.
Whenconfiguredasaninput,apincandetectthestateofasensorlikeapushbutton.Asanoutput,itcan
driveanactuatorlikean LED.
ThedigitalWrite()
functionsoutputsa valueon apin. Forexample, theline:
digitalWrite(ledPin,HIGH);
set the ledPin (pin 13) to HIGH, or 5 volts. Writing a LOW to pin connects it to ground, or
0volts.
Thedelay()causestheArduinotowaitforthespecifiednumberofmillisecondsbeforecontinuing on
to the next line. There are 1000 milliseconds in a second, so the line:delay(1000);
createsadelayofonesecond.
setup()andloop()
TherearetwospecialfunctionsthatareapartofeveryArduinosketch:
setup() and loop(). The setup() is called once, when the sketch starts. It's a good place to
dosetup tasks like setting pin modes or initializing libraries. The loop() function is called
overand over and is heart of most sketches. You need to include both functions in your
sketch,evenif you don't need them foranything.
3.8. ArduinoSketchesusingsoftware
If you go into your file directory system and open up the Sketchbook folder (again,
named“Arduino” by default), you may see a bunch of folders that you didn’t make.This is
becauseevery Arduino file must be inside a folder that has the same name as the file (there
are someexceptionsto thisthat we’ll talk about in amoment).
Let me say that one more time because it is really important to understand.Every Arduino
filemust be inside a folder that has the same name as the fileWhen I write a new sketch and
saveit, the Arduino IDE automatically creates a new folder that has the exact same name as
thesketch itself. The Arduino file (which has the extension .ino) is placed inside this
enclosingfolder,which is called asketch folder.
144|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
If you go into the Sketchbook folder and change the name of the enclosing folder, it
willcreate some issues. The first issue is that when you go to File > Sketchbook, the sketch
willno longer show up! If you want to open this sketch you need to go to the .ino file in
yourdirectoryand open it from there.
If you open a .ino file that is not inside an enclosing sketch folder of the exact same
name,thenyou will get apop-up from theArduinoIDE that says:
If you choose Cancel, the sketch will not open. If you choose OK, then a folder gets
created(itwill havethe samename as the sketch) andthe.ino fileis placedinsideit.
This sketch folder will be created in whatever directory the .ino file was that you tried
toopen.Forexample,ifyoutriedtoopena.inofilethatwasinyourMyDownloadsfolder,thentheenclo
sing sketch folder also will becreated insidetheMy Downloads folder.
SavingTabsInArduino
Theexceptiontotheruleaboutthesketchfolderhavingthesamenameasthe.inofileiswhenyou create
multipletabs in an Arduino sketch.
Theadditionaltabs doNOTneedto bearthesamenameas the enclosing sketchfolder.
145|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Once you get a handle on some of these intricacies of the Arduino IDE file system, it
canreallyhelp to clear things up.
ArduinoShields
3.9. ArduinoPins
AnIntroductiontoArduinoUnoPinout
Arduino Uno is based on the ATmega328 by Atmel. The Arduino Uno pinout consists of
14digital pins, 6 analog inputs, a power jack, USB connection and ICSP header. The
versatilityof the pinout provides many different options such as driving motors, LEDs,
reading sensorsandmore.In thispost, we’ll goover thecapabilitiesofthe Arduino Unopinout.
ArduinoUnopinout-PowerSupply
Thereare3 waysto powertheArduinoUno:
Barrel Jack - The Barrel jack, or DC Power Jack can be used to power your
Arduinoboard. The barrel jack is usually connected to a wall adapter. The board can
bepowered by 5-20 volts but the manufacturer recommends to keep it between 7-
12volts. Above 12 volts, the regulators might overheat, and below 7 volts, might
notsuffice.
146|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
ArduinoUnoPinout–Diagram
VINPin-
ThispinisusedtopowertheArduinoUnoboardusinganexternalpowersource.Thevoltagesh
ould be within therangementionedabove.
USBcable-whenconnected tothe computer, provides5 voltsat 500mA.
There is a polarity protection diode connecting between the positive of the barrel jack to
theVINpin, ratedat 1 Ampere.
The power source you use determines the power you have available for your circuit.
Forinstance, powering the circuit using the USB limits you to 500mA. Take into
considerationthat this is also used for powering the MCU, its peripherals, the on-board
regulators, and thecomponents connected to it. When powering your circuit through the
barrel jack or VIN, themaximum capacity available is determined by the 5 and 3.3 volts
regulators on-board theArduino.
147|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
5vand 3v3
Theyprovideregulated5and3.3vtopowerexternalcomponentsaccordingtomanufacturerspecifica
tions.
ArduinoUnoPinout-AnalogIN
The Arduino Uno has 6 analog pins, which utilize ADC (Analog to Digital
converter).Thesepinsserveasanaloginputs butcanalso functionasdigital
inputsordigitaloutputs.
GND
Inthe ArduinoUno pinout,youcanfind 5GNDpins,which areallinterconnected.
The GND pins are used to close the electrical circuit and provide a common logic
referencelevel throughout your circuit. Always make sure that all GNDs (of the Arduino,
peripheralsandcomponents) areconnected to oneanotherand haveacommon ground.
AnalogtoDigitalConversion
ADC stands for Analog to Digital Converter. ADC is an electronic circuit used to
convertanalog signals into digital signals. This digital representation of analog signals allows
theprocessor (which is a digital device) to measure the analog signal and use it through
itsoperation.
Arduino Pins A0-A5 are capable of reading analog voltages. On Arduino the ADC has 10-
bitresolution,meaningitcanrepresentanalogvoltageby1,024digitallevels.TheADCconvertsvolta
geinto bits which the microprocessorcan understand.
OnecommonexampleofanADCisVoiceoverIP(VoIP).Everysmartphonehasamicrophone that
converts sound waves (voice) into analog voltage. This goes through thedevice’sADC, gets
converted into digital data,which is transmitted tothe receiving sideovertheinternet.
148|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
It’simportanttonotethat:
● Eachpincan provide/sinkup to40 mAmax.But therecommendedcurrentis 20mA.
● Theabsolutemaxcurrent provided(orsank) from allpinstogetheris200mA
Whatdoesdigitalmean?
Digital is a way of representing voltage in 1 bit: either 0 or 1. Digital pins on the Arduino
arepins designed to be configured as inputs or outputs according to the needs of the user.
Digitalpins are either on or off. When ON they are in a HIGH voltage state of 5V and when
OFFtheyarein aLOWvoltagestateof 0V.
On the Arduino, When the digital pins are configured as output, they are set to 0 or 5
volts.Whenthedigitalpinsareconfiguredasinput, thevoltageissuppliedfromanexternaldevice.
This voltage can vary between 0-5 volts which is converted into digital representation(0or1).
To determinethis, thereare2 thresholds:
● Below0.8v-consideredas0.
● Above2v- considered as1.
Whenconnectingacomponenttoadigitalpin,makesurethatthelogiclevelsmatch.Ifthevoltageis in
betweenthethresholds, thereturningvalue will be undefined.
WhatisPWM?
Ingeneral,PulseWidthModulation(PWM)isamodulation techniqueusedtoencodea message
intoa pulsingsignal.APWMiscomprisedoftwokeycomponents:frequency and duty cycle. The
PWM frequency dictates how long it takes to complete asingle cycle (period) and how
quickly the signal fluctuates from high to low. The duty cycledetermines how long a signal
stays high out of the total period. Duty cycle is represented inpercentage.
InArduino,thePWMenabledpinsproduceaconstantfrequencyof~500Hz,whilethedutycyclechan
ges according to theparametersset by theuser. Seethefollowing illustration:
149|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
CommunicationProtocols
Serial (TTL) - Digital pins 0 and 1 are the serial pins of the Arduino
Uno.Theyareused by the onboard USB module.
WhatisSerialCommunication?
Serial communication is used to exchange data between the Arduino board and another
serialdevice such as computers, displays, sensors and more. Each Arduino board has at least
oneserial port. Serial communication occurs on digital pins 0 (RX) and 1 (TX) as well as
viaUSB. Arduino supports serial communication through digital pins with the
SoftwareSerialLibrary as well. This allows the user to connect multiple serial-enabled
devices and leave themainserial port availableforthe USB.
150|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Softwareserialandhardwareserial -
Mostmicrocontrollershavehardwaredesignedtocommunicatewithotherserialdevices.
Softwareserial portsuseapin-changeinterruptsystemtocommunicate.Thereisabuilt-
inlibraryforSoftwareSerialcommunication.Software serial is usedby the processor to simulate
extra serial ports. The only drawbackwith software serial is that it requires more processing
and cannot support the same highspeedsas hardwareserial.
SPI - SS/SCK/MISO/MOSI pins are the dedicated pins for SPI communication. They can
befoundon digital pins 10-13 ofthe Arduino Uno and on the ICSP headers.
Whatis SPI?
SerialPeripheralInterface(SPI)isaserialdataprotocolusedbymicrocontrollerstocommunicate
with one or more external devices in a bus like connection. The SPI can also beused to
connect 2 microcontrollers. On the SPI bus, there is always one device that is denotedas a
Master device and all the rest as Slaves. In most cases, the microcontroller is the
Masterdevice.TheSS(SlaveSelect)pindetermineswhichdevicetheMasteriscurrentlycommunica
tingwith.
SPIenabled devicesalways havethefollowingpins:
MISO(Master InSlaveOut) -Aline forsendingdatato theMasterdevice
MOSI(MasterOut SlaveIn)-TheMasterlineforsendingdatato peripheraldevices
SCK (Serial Clock) - A clock signal generated by the Master device to
synchronizedatatransmission.
I2C - SCL/SDA pins are the dedicated pins for I2C communication. On the Arduino
Unotheyare foundon Analogpins A4 and A5.
Whatis I2C?
I2C is a communication protocol commonly referred to as the “I2C bus”. The I2C
protocolwas designed to enable communication between components on a single circuit
board. WithI2Cthereare2 wires referred to as SCLand SDA.
SCLis theclock line whichis designed tosynchronizedata transfers.
SDAis thelineusedtotransmit data.
Each device on the I2C bus has a unique address, up to 255 devices can be connected on
thesame bus.
151|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
External
PinChange
There are two external interrupt pins on the ATmega168/328 called INT0 and INT1.
bothINT0 and INT1 are mapped to pins 2 and 3. In contrast, Pin Change interrupts can
beactivated onany of thepins.
ArduinoUnoPinout-ICSPHeader
ICSPstandsforIn-CircuitSerialProgramming.ThenameoriginatedfromIn-
SystemProgrammingheaders(ISP).ManufacturerslikeAtmelwhoworkwithArduinohavedevelo
ped their own in-circuit serial programming headers. These pins enable the user toprogram
the Arduino boards’ firmware. There are six ICSP pins available on the Arduinoboardthat
can behookedto aprogrammer device via aprogramming cable.
3.10. Input/outputpinsontheArduino
Outputpins
An output pin provides VDDor 0 V, by makinga connectionto VDDor groundvia atransistor.
You set its stateto HIGH (for VDD ) or LOW (for 0 V) using the
digitalWrite()function.A(simplified)schematicofanoutputpinisshownbelow.Youmightnoticeth
atitlooks abit likeaCMOS inverter(or rather, two).
Inputpins
Aninputpinreadsthevoltageonthepinasifitwereavoltmeter,andreturnseitherHIGH
(1)insoftwareifthevoltageisclosetoVDD,orLOW(0)ifitiscloseto0V.Aninputpincanberead using
the digitalRead()function.
152|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Arduino-I/OFunctions
The pins on the Arduino board can be configured as either inputs or outputs. We
willexplain the functioning of the pins in those modes. It is important to note that a majority
ofArduinoanalogpins,maybeconfigured,andused,inexactlythesamemannerasdigitalpins.
PinsConfiguredas INPUT
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
orreadingan LED as aphotodiode.
153|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Pull-upResistors
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 toground)onthe input. A 10K resistor isa good valueforapull-up or pull-
downresistor.
UsingBuilt-inPull-upResistorwithPinsConfiguredas Input
There are 20,000 pull-up resistors built into the Atmega chip that can be accessed
fromsoftware.Thesebuilt-inpull-upresistorsareaccessedbysettingthe pinMode()
asINPUT_PULLUP. This effectively inverts the behavior of the INPUT mode, where
HIGHmeansthesensorisOFFandLOWmeansthesensorisON.Thevalueofthispull-updepends on
the microcontroller used. On most AVR-based boards, the value is guaranteed tobe between
20kΩ and 50kΩ. On the Arduino Due, it is between 50kΩ and 150kΩ. For theexactvalue,
consult thedatasheet of themicrocontrolleron your board.
When connecting a sensor to a pinconfigured with INPUT_PULLUP, the other end shouldbe
connected tothe ground. Incase ofa simple switch, thiscausesthepintoread HIGHwhen the
switch is open and LOW when the switch is pressed. The pull-up resistors provideenough
current to light an LED dimly connected to a pin configured as an input. If LEDs in
aprojectseem to beworking,but very dimly, this islikely what is going on.
Same registers (internal chip memory locations) that control whether a pin is HIGH or
LOWcontrol the pull-up resistors. Consequently, a pin that is configured to have pull-up
resistorsturned on when the pin is in INPUTmode, will have the pin configured as HIGH if
the pin isthen switched to an OUTPUT mode with pinMode(). This works in the other
direction aswell, and an output pin that is left in a HIGH state will have the pull-up resistor
set ifswitchedto an input with pinMode().
Example
PinsConfiguredasOUTPUT
Attemptingtorunhighcurrentdevicesfromtheoutputpins,candamageordestroytheoutputtransisto
rsinthe pin,or damagetheentireAtmega chip.Often,thisresultsina "dead"
154|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
pin in the microcontroller but the remaining chips still function adequately. For this reason,
itis a good idea to connect the OUTPUT pins to other devices through 470Ω or 1k
resistors,unlessmaximum currentdrawn from thepins is requiredforaparticularapplication.
pinMode()Function
The pinMode() function is used to configure a specific pin to behave either as an input or
anoutput. It is possible to enable the internal pull-up resistors with the mode
INPUT_PULLUP.Additionally,the INPUTmode explicitlydisables theinternal pull-ups.
pinMode() Function
SyntaxVoidsetup ()
{
pinMode(pin ,mode);
}
pin −the numberofthe pin whosemode youwish toset
mode−INPUT,OUTPUT,orINPUT_PULLUP.
Example
intbutton=5;//buttonconnectedtopin5int
LED=6;// LEDconnected to pin6
voidsetup(){
pinMode(button,INPUT_PULLUP);
// set the digital pin as input with pull-up
resistorpinMode(button,OUTPUT);// setthedigital
pinasoutput
}
voidsetup(){
If(digitalRead(button )== LOW)// if button pressed
{digitalWrite(LED,HIGH);// turn on
leddelay(500);// delay for 500
msdigitalWrite(LED,LOW);// turn off
leddelay(500);//delay for 500ms
}
}
digitalWrite()Function
The digitalWrite() function is used to write a HIGH or a LOW value to a digital pin. If
thepinhasbeenconfiguredasanOUTPUT with pinMode(),itsvoltagewillbe
settothecorrespondingvalue:5V(or3.3Von3.3Vboards)forHIGH,0V(ground)forLOW.Ifthe
155|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
If you do not set the pinMode() to OUTPUT, and connect an LED to a pin, when
callingdigitalWrite(HIGH),theLEDmayappeardim.WithoutexplicitlysettingpinMode(),digital
Write() will have enabled the internal pull-up resistor, which acts like a large current-
limitingresistor.
digitalWrite() Function
SyntaxVoid loop()
{
digitalWrite(pin,value);
}
pin −the numberofthe pin whosemode youwish toset
value−HIGH,or LOW.
Example
voidsetup()
{
pinMode(LED,OUTPUT);//setthedigital pinasoutput
}
voidsetup()
{
digitalWrite(LED,HIGH);// turn on
leddelay(500);// delay for 500
msdigitalWrite(LED,LOW);// turn off
leddelay(500);//delay for500ms
}
analogRead()function
Arduino is able to detect whether there is a voltage applied to one of its pins and report
itthrough the digitalRead() function. There is a difference between an on/off sensor
(whichdetects the presence of an object) and an analogsensor, whosevalue continuously
changes.Inorder to read this type of sensor, weneedadifferenttypeof pin.
156|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
analogRead()functionSyntax
analogRead(pin);
pin −thenumberoftheanaloginputpintoreadfrom(0to5onmostboards,0to7onthe Mini
and Nano, 0to 15 on theMega)
Example
intanalogPin=3;//potentiometerwiper(middleterminal)
//connected toanalog pin3
int val=0;//variabletostorethevalueread
voidsetup()
{
Serial.begin(9600);//setupserial
}
voidloop()
{
val = analogRead(analogPin);// read the input
pinSerial.println(val);//debug value
}
3.11. ArduinoShields
Arduino shields are the boards, which are plugged over the Arduino board to expand
itsfunctionalities. There are different varieties of shields used for various tasks, such as
Arduinomotorshields, Arduino communication shields, etc.
Shield is defined as the hardware device that can be mounted over the board to increase
thecapabilities of the projects. It also makes our work easy. For example, Ethernet shields
areusedto connect theArduino boardto theInternet.
ThepinpositionoftheshieldsissimilartotheArduinoboards.Wecanalsoconnectthemodulesand
sensors to theshields with the help ofthe connection cable.
Arduino motor shields help us to control the motors with the Arduino
157|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
o TheshieldscanbeattachedanddetachedeasilyfromtheArduinoboard.Itdoesnotrequireany
complex wiring.
o Itiseasy toconnect theshields bymounting themover theArduino board.
o Thehardware components on theshields can beeasily implemented.
TypesofShields
ThepopularArduinoshields arelisted below:
o Ethernetshield
o XbeeShield
o Protoshield
o Relayshield
o Motorshield
o LCDshield
o Bluetoothshield
o CapacitiveTouchpadShield
Let'sdiscusstheshieldsthatarelistedabove:
Ethernetshield
o TheEthernetshieldsareusedtoconnecttheArduinoboardtotheInternet.Weneedtomount
theshield on thetop ofthespecified Arduino board.
o TheUSB portwill play theusual roletouploadsketches ontheboard.
o ThelatestversionofEthernetshieldsconsistsofamicroSDcardslot.ThemicroSDcardslot
can beinterfaced with thehelp of the SD card library.
o
TheEthernetshield isshownbelow:
XbeeShield
o WecancommunicatewirelesslywiththeArduinoboardbyusingtheXbeeShieldwithZigbee
.
158|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
o Itreducesthehassleofthecable,whichmakesXbeeawirelesscommunicationmodel.
o TheXbeewirelessmoduleallowsustocommunicateoutdoorupto300feetandindoorupto
100 feet.
o TheXbeeshieldis shown below:
o ItcanalsobeusedwithdifferentmodelsofXbee.
Protoshield
o Protoshieldsaredesigned forcustomcircuits.
o Wecansolderelectronic circuitsdirectlyontheshield.
o Theshieldconsists oftwo LEDpads, twopower lines,and SPIsignal pads.
o TheIOREF(InputOutputvoltageREFerence)andGND(Ground)arethetwopowerlineson
the board.
Theproto shield isshown below:
o WecanalsosoldertheSMD(SurfaceMountDevice)ICsontheprototypingarea.Amaximum
of 24pins can beintegrated onto theSMD area.
Relayshield
o The Arduino digital I/O pins cannot bear the high current due to its voltage
andcurrent limits. The relay shield is used to overcome such situation. It provides
asolutionforcontrolling thedevicescarryinghigh currentandvoltage.
159|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
o Theshieldconsistsof fourrelaysandfourLEDindicators.
o ItalsoprovidesNO/NCinterfacesandashieldformfactorforthesimpleconnectiontotheArd
uino board.
o TheLEDindicatorsdepicts theON/OFFcondition ofeachrelay.
o Therelay used in thestructureis of high quality.
o TheNO(Normally Open), NC (NormallyClosed), and COMpins arepresenton
eachrelay.
o Therelay shieldis shown below:
Motorshield
o Themotor shieldhelps us tocontrol themotor using theArduino board.
o It controls the direction and working speed of the motor. We can power the
motorshield either by the external power supply through the input terminal ordirectly
bythe Arduino.
o We can also measure the absorption current of each motor with the help of the
motorshield.
o The motor shield is based on the L298 chip that can drive a step motor or two
DCmotors. L298 chip is a full bridge IC. It also consists of the heat sinker,
whichincreasesthe performanceof themotor shield.
o Itcandriveinductiveloads, suchas solenoids,etc.
o The operating voltage is from 5V to
160|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
LCDshield
o ThekeypadofLCD(LiquidCrystalDisplay)shieldincludesfivebuttonscalledasup,down,
left, right, andselect.
o Thereare6pushbuttonspresentontheshieldthatcanbeusedasacustommenucontrolpanel.
o Itconsistsofthe1602whitecharacters,whicharedisplayedonthebluebacklightLCD.
o TheLEDpresent ontheboard indicatesthepower ON.
o Thefivekeyspresentontheboardhelpsustomaketheselectiononmenusandfromboardto
ourproject.
o
TheLCDshieldisshownbelow:
o TheLCDshieldispopularlydesignedfortheclassicboardssuchasDuemilanove,UNO,etc.
Bluetoothshield
o TheBluetoothshieldcanbeusedasawirelessmodulefortransparentserialcommunication.
161|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
o It includes a serial Bluetooth module. D0 and D1 are the serial hardware ports in
theBluetooth shield, which can be used to communicate with the two serial ports
(fromD0to D7)of theArduino board.
o We can install Groves through the two serial ports of the Bluetooth shield called
aGroveconnector. OneGroveconnectoris digital, whiletheother is analog.
o The communication distance of the Bluetooth shield is upto 10m at home without
anyobstaclein between.
CapacitiveTouchpadshield
o IthasatouchpadinterfacethatallowstointegratetheArduinoboardwiththetouchshield.
o TheCapacitivetouchpadshieldconsistsof12sensitivetouchbuttons,whichincludes3electr
ode connections and 9 capacitive touch pads.
o Thecapacitiveshield isshownbelow:
SensorsandActuatorsin IoT|EnablingIndustrialAutomation
162|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
The Internet of Things is a major contributing factor of the new Data Economy. The value
ofan IoT system goes beyond the original intended use case, for instance in automation. This
isbecausefurther valuelies in the intelligence that anIoT systemcreates. Sensors are thesource
of IoT data. Furthermore, sensors and actuators in IoT can work together to
enableautomation at industrial scale. Finally, analysis of the data that these sensors and
actuatorsproducecan provide valuable business insights overtime.
Drivenbynewinnovationsinmaterialsandnanotechnology,sensortechnology isdeveloping at a
never before seen pace, with a result of increased accuracy, decreased sizeand cost, and the
ability to measure or detect things that weren’t previously possible. In fact,sensing
technology is developing so rapidly and becoming so advanced that we will see
atrillionnewsensors deployed annually within a fewyears.
Sensors
A better term for a sensor is a transducer. A transducer is any physical device that
convertsone form of energy into another. So, in the case of a sensor, the transducer converts
somephysical phenomenon into an electrical impulse that determines the reading. A
microphone isa sensor that takes vibrational energy (sound waves), and converts it to
electrical energy in ausefulway for othercomponentsin the system tocorrelate back to
theoriginalsound.
Actuators
Another type of transducer that you will encounter in many IoT systems is an actuator.
Insimple terms, an actuator operates in the reverse direction of a sensor. It takes an
electricalinputandturnsitintophysicalaction.Forinstance,anelectricmotor,ahydraulicsystem,and
apneumatic systemareall different types ofactuators.
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
controlsanactuatorinresponsetothatsensedinput.Thus,sensorsandactuatorsinIoTworktogether
163|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
from opposite ends. Later, we will discuss where the control center resides in the greater
IoTsystem.
2. InstalltheArduinoIDE:
DownloadandinstalltheArduinoIntegratedDevelopmentEnvironment(IDE)onyourcomputerfro
m the official Arduino website(https://www.arduino.cc/en/software).
3. ConnecttheHardware:
Connectthesensor andactuatorcomponentsto theArduino usingjumperwires.
Makesuretoconnectthesensor'soutputpintoadigitaloranaloginputpinontheArduinoandthe
actuator to adigital output pin.
4. WriteArduinoSketch(Code):
OpentheArduino IDEandcreateanewsketch.
Writethecodethatreadsdatafromthesensor(s)andcontrolstheactuator(s)basedonthatdata.
Usetheappropriate librariesforyoursensorsandactuators ifneeded.
5. UploadtheCodetotheArduino:
Connect the Arduino to your computer using a USB
cable.Select the correct Arduino board and port in the Arduino
IDE.Clickthe"Upload"buttontouploadyourcodeto theArduino.
6. Monitorand Debug:
OpentheArduinoSerialMonitor(Tools->SerialMonitor)toviewsensorreadingsanddebug
yourcode.
Adjustthecodeasnecessary toachievethedesiredbehavior.
7. PowerConsiderations:
Ensurethatyourpowersupplycanhandlethepowerrequirementsofyoursensorsandactuators.Some
components may require anexternal power supply.
164|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
8. AdditionalComponentsandCircuitry:
Dependingonyourproject,youmayneedadditionalcomponentssuchasresistors,capacitors,andtra
nsistorstointerface withcertainsensorsordrive high-poweractuators.
9. ExpandandCustomize:
Continuetoaddmoresensorsand actuatorstocreatecomplexprojects.
Explorethird-partylibrariesandonlineresourcesforadditionalfunctionalityandprojectideas.
10. EnclosureandMounting:
Depending on your project's requirements, you may need to design and build an enclosure
tohousethe Arduino, sensors,and actuators, and mountthem in the desiredlocation.
Remembertorefertothedatasheetsanddocumentationforyourspecificsensorsandactuators to
understand their pinouts and operation. Arduino's online community and forumsarealso
valuableresources forgettinghelp andfinding project inspiration.
165|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
UNITIV
IOTCOMMUNICATIONANDOPENPLATFORMS
IoT CommunicationModelsandAPIs
IoTCommunicationProtocols
Bluetooth
WiFi
ZigBee
GPS
GSMmodules
OpenPlatform(like RaspberryPi)
Architecture
Programming
Interfacing
AccessingGPIOPins
ConnectingtotheCloud.
166|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
4.1. InternetofThings:CommunicationModelsandAPIs
“The Internet of Things is not a concept; it is a network, the true technology-
enabledNetworkof all networks.” — EdewedeOriwoh
"InternetofThingsisthenetworkofphysicalobjectsor‘things’embeddedwithelectronics,
software, sensors and connectivity to enable it to achieve greater value
andservicebyexchangingdatawiththemanufacturer,operatorand/orotherconnecteddevices.
Each thing is uniquely identifiable through its embedded computing system but isableto
interoperate withintheexisting Internet infrastructure."
CommunicationModelsinIoT
Understanding how the different IoT devices communicate with
eachotherisimportantandusefulcauseIoTdevicesarefoundalmosteveryw
here now. Communication models are the way to understand it.IoTs
enable people and things to be connected anytime, in any
space,withanything and anyone, throughany network and service.
NowletusunderstandthedifferentcommunicationmodelsinIoT.
Request&ResponseModel
Thecommunicationtakesplacebetween a clientandaserver.
Wheneverrequired,theclientwillrequestinformationfromtheserver.Thisrequestisusually in the
encoded format.So in this model, basically a client sends requests to the
serverandtheserverrespondstotherequests.ThatiswhyitiscalledasRequest-
Responsemodel.After receiving the request from the client, the server decides how to
respond, fetchesthe data from the database and its resource representation, prepares a
response and ultimatelysendstheresponse to theclient.
Publish-SubscribeModel(Pub-Sub)
167|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
In this model, you will find three main entities:- Publisher, Broker and Consumer Let us
seethe roles of each of these 3 entities.Publishers, send the data to the topics that are managed
bythebroker.Theyarethesourceofdata.TheManintheMiddle,theBroker,hastheresponsibilitytoac
ceptthedatasentbythepublisheranddeliverthatdatatotheconsumers.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 allconsumers who have subscribed to
the specific topic. It works a bit like YouTube. When yousubscribe to a channel and tap the
Bell icon, you'll get notifications if the YouTube channelposts avideo.
Push-PullModel
168|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
ExclusivePairModel
IoTCommunicationAPIs
An API is an interface used by programs to access an application.It enablesa program
tosendcommandstoanother programandreceive repliesfromtheapp.IoTAPIsare
theinterfacepointsbetweenanIoTdeviceandthe Internetand/orothernetworkcomponents.
HerewewilltalkabouttheREST-based APIandtheWebsocketbasedAPI.
169|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
REST-basedAPIs(Representationalstatetransfer)
Representationalstatetransfer(REST)isasetofarchitecturalprinciplesbywhichyoucandesign
Web services the Web APIs that focus on the system's resources and how
resourcestatesare addressed and transferred.
Client-server
Let me explain it to you by giving a suitable example. The client should not be
concernedwith the storage of data which is a concern of the server, similarly, the server
should not beconcerned about the user interface, which is the concern of the client.
Separation makes itpossiblefor theclientand server to bedevelopedand updated
independently.
170|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Stateless
Thestatusofthesessionremainsentirelyonthe client.
Cache-able
This property defines whether the response to any request can be cached or not. If a
responsecan be cached, then a client cache is granted the right to reuse that response data
forsubsequentmatching requests.
Layeredsystem
A layered system defines the boundaries of the components within each specific layer.
Forexample, A client is unable to tell whether it is connected to the end server or an
intermediatenode.As simple as that!
Uniforminterface
This specifies that the technique of communication between a client and a server must
beuniformthroughout thecommunication period.
CodeonDemand
Serversmayprovideexecutablecodeorscripts
forexecutionbyclientsintheircontext.Websocketbased APIs
WebsocketAPIs enablebi-directionalandduplex
communicationbetweencustomersandservers.
Unlike REST, There is no need to set up a connection every now and then to send
messagesbetweenaclient and aserver.
It works on the principle of the exclusive pair model. Can you recall it? Yes. Once
aconnectionissetup,thereisaconstantexchange ofmessagesbetweentheclientandtheserver.
All we need is to establish a dedicated connection to start the process.
thecommunicationgoes on unless theconnection is terminated.
Itisastatefultype.
171|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Due to onetime dedicated connection setup, there is less overhead, lower traffic and
lesslatencyand high throughput.
4.2. IoTCommunicationProtocols
Several Communication Protocols and Technology used in the internet of
Things.SomeofthemajorIoTtechnologyandprotocol(IoTCommunicationProtocols)areBluetoot
h,Wifi, RadioProtocols, LTE-A,andWiFi-Direct.
4.2.1. Bluetooth
An important short-range IoT communications Protocols / Technology. Bluetooth, which
hasbecome very important in computing and many consumer product markets. It is expected
tobe key for wearable products in particular, again connecting to the IoT albeit probably via
asmartphonein manycases.
IotTechnology –Bluetooth
4.2.2. Zigbee
ZigBeeissimilartoBluetoothandismajorlyusedinindustrialsettings.Ithassomesignificantadvanta
gesincomplexsystemsofferinglow-poweroperation,highsecurity,robustness and high and is
well positioned to take advantage of wireless control and sensornetworksin IoT applications.
The latest version of ZigBee is the recently launched 3.0, which is essentially the
unificationofthevarious ZigBeewireless standards into asinglestandard.
172|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
IotTechnology–ZigBee
4.2.3. Z-Wave
Z-Wave is a low-power RF communications IoT technology that primarily design for
homeautomationforproductssuch aslampcontrollersand sensorsamongmany otherdevices.
A Z-Wave uses a simpler protocol than some others, which can enable faster and
simplerdevelopment, but the only maker of chips is Sigma Designs compared to multiple
sources forotherwireless technologiessuch as ZigBeeand others.
IotTechnology–Z-Waved.Wi-Fi
WiFi connectivity is one of the most popular IoT communication protocol, often an
obviouschoiceformanydevelopers,especiallygiventheavailabilityofWiFiwithinthehomeenviro
nmentwithin LANs.
There is a wide existing infrastructure as well as offering fast data transfer and the ability
tohandlehigh quantities ofdata.
173|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
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 maybetoo power-consumingformanyIoTapplications.
4.2.4. Cellular
Any IoT application that requires operation over longer distances can take advantage
ofGSM/3G/4Gcellularcommunicationcapabilities.Whilecellularisclearlycapableofsending
high quantities of data, especially for 4G, the cost and also power consumption willbetoohigh
formanyapplications.
But it can be ideal for sensor-based low-bandwidth-data projects that will send very
lowamountsofdataovertheInternet.
IoTCommunicationProtocols–Cellular
4.2.5. NFC
NFC(NearFieldCommunication)isanIoTtechnology.Itenablessimpleandsafecommunicationsb
etweenelectronicdevices,andspecificallyforsmartphones,allowingconsumersto
performtransactionsinwhich onedoes not haveto bephysicallypresent.
Ithelpsthe user toaccessdigitalcontentandconnectelectronic
devices.Essentiallyitextendsthecapabilityofcontactlesscardtechnologyandenablesdevicestosha
reinformationat adistancethat is less than 4cm.
174|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
IoTCommunicationProtocols –NFC
4.2.6. LoRaWAN
LoRaWANisoneofpopularIoTTechnology,targetswide-areanetwork(WAN)applications. The
LoRaWAN design to provide low-power WANs with features specificallyneeded to support
low-cost mobile secure communication in IoT, smart city, and industrialapplications.
Specifically meets requirements for low-power consumption and supports large
networkswithmillionsand millions ofdevices, dataratesrangefrom 0.3kbps to 50kbps.
IotTechnology –LoRaWAN
4.3. Bluetooth
To understand the architecture of Bluetooth first lets understand what actually Bluetooth
is.Bluetoothisaradio-wavetechnologythatismainlydesignedtoenablewirelesscommunications
over short distances. The frequency of these waves ranges between 2.400and 2.485 GHz,
which can extend a maximum of 164 feet between two devices. EveryBluetooth device has a
Transmitter and a Receiver. The power of the device transmittergoverns the range over
which a Bluetooth device can operate in other words
transmitterdecidestherangeofcommunication.
175|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
These days Bluetooth is the common technology present in most of the products. It is used
inmany fields such as the health sector, sports and fitness, electronics, home automation,
andsecurity,etc.
Someoftheapplications ofBluetooth:
–>Wirelesscontrolandcommunicationbetweenamobilephoneandahandsfreeheadset.
4.3.1. BluetoothArchitecture.
4.3.1.1. Piconet
The Bluetooth network is called a piconet. If it contains one master and one slave then
itscalled a single piconet. Similarly, if it contains one master and multiple slaves are
calledmultiplepiconets.
176|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
The Master isthe one thatinitiates the communication withother devices and it
dictateswhenaslave devicemaytransmit.
DirectSlavetoSlavecommunication isnot possible.
Maximum7activeslavescanbepresentinmultiplepiconets,inotherwords,only8maximumdevices
includingthe mastercancommunicateat anyonetimein apiconet.
4.3.1.2. Scatternet
ItsaCombination ofmultiplepiconets.
Here Master of one piconet can be a slave in another piconet. This node can receive
amessage from a master in one piconet and deliver the message to its slave into the
otherpiconet.
Therefore, this type of node is referred to as a bridge node. Above all, a station cannot
bemasterin two piconets.Read More
TheArchitectureofaBluetooth IoTApplication
Firstly,wemustfirstdiveintotheBluetooth“stack”tounderstandwhyrecentshiftsin
Bluetooth standards are significant for IoT applications The evolution of Bluetooth from
areplacement for RS-232 data cables to a powerful and massive IoT connectivity solution is
astoryofadding newlayersto thestack.Thenewest Bluetooth specificationforIoT—
177|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Bluetooth mesh—must be engineered upon either the BLE 4.xx or 5.xx stack—an
extensionoftheBluetoothCore(“classic”)specification.TheemergingBluetoothmeshstack,theref
ore,comprises three-stack layers: Core,thenBLE, and meshon top.
BluetoothTopologies:Pair,Broadcast,Mesh
Pair:Bluetoothasameansofpairingtwo devices
ForExample,acomputer pairedwithawirelessmouse
Broadcasting:Bluetoothasameansofhavingonedevicebroadcastinformationtomanydevice
s or viceversa
ForExample:Playingmusiconsmartspeakersandsimultaneouslycastingphotostoaprojector
—bothusing a single iPhone
Mesh: Bluetoothasawayof connectingmanydevicestomanyothersasifin a spider’sweb
ForExample:Connecting1,278overheadlightsinawarehousetoeachothertodimandbrighte
n lightsautomatically basedupon activityand personal preferences.
4.3.2. BluetoothProtocolTypes
The main function of the Bluetooth is a Bluetooth protocol stack in architecture
ofBluetooth.Inotherwords,Itdefinesandprovidesdifferenttypesoflayersandfunctionalities.
Bluetooth can run the differentapplications over different protocol stacks,but,each oneof
theseprotocolstacks uses thesame Bluetoothlink and physicallayers.
The below diagram shows a complete Bluetooth protocol stack. It shows the
relationshipbetween the protocols that use the services of other protocols when there is a
payload to betransferred in the air. Anyhow, the protocols have many other relationships
between the otherprotocols – for example, some protocols (L2CAP, TCS Binary) use the
LMP to control thelinkmanager.
178|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
applications to work with the Bluetooth technology to measure the smooth operations
andinteroperabilityofapplications.Hence,manyapplicationsarebeingdevelopedtotakeimmediat
eadvantageof thesoftwareand hardware.
Protocollayers Protocolinthestacks
BluetoothCoreProtocol Baseband,LMP,L2CAP,SDP
CableReplacementProtocol RFCOMM
TelephonyControlProtocol TCS Binary,AT-commands
AdoptedProtocols PPP,OBEX,UDP/TCP/IP,WAP,Vcard,Vcall, IrMC,WAE
LayersofArchitectureofBluetooth :
Host Acommandinterfaceforthecontrollerandforthelinkmanager,whichallo
Controller wsaccessto thehardwarestatusandcontrolregisters.
Interface
Logical Link It is also known as the heart of the Bluetooth protocol stack.Itallows
Controland the communication between the upper and lower layers of
Adaptation theBluetoothprotocol stack.
Protocol
Radio(RF)layer Itperformsmodulation/demodulation ofthedatainto RFsignals.
BasebandLinklayer Inshort,itperformstheconnectionestablishmentwithinapiconet.
ItisshortforServiceDiscoveryProtocol.Itallowsfordiscoveringtheservi
SDPlayer
cesavailable on anotherBluetoothenabled device.
TCS ItisshortforTelephonyControlProtocol.Itprovidesatelephony
179|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
service.
AdvantagesofBluetoothProtocols
Bluetoothofferseconomicwirelesssolutions(bothdata& voice)but,for shortdistances
Ontheotherhand,Mobileand stationaryenvironmentuseBluetooth protocol.
Thereisno setupfiletoinstall theBluetooth, inother words,it isan inbuiltdevice.
Aboveall,Theyareup-gradable
CharacteristicsofBluetoothProtocols
Inshort,UptoeightdevicesincludingthemastercancommunicateinthePiconetbyusingBluetooth.
BluetoothsignalsareOmnidirectionalasaresultdevicesdon’tpointateachother.
Governmentsregulatedworldwidebecauseitispossibletoutilizethesamestandard.
Inshort,Signalscantransmitthroughwallsandbriefcases.
BluetoothSecurity
Firstly, the security of any wireless technologyis very important. With hackers gainingaccess
to an ever-increasing number of systems, as a result,Bluetooth security is
increasinglyimportant.
Bluetoothsecuritymustalsoaddressmorespecific Bluetoothrelatedattacksthattargetknown
vulnerabilities in Bluetooth implementations and specifications. In other words,
thesemayincludeattacksagainstimproperlysecuredBluetoothimplementationswhichcanprovide
attackers with unauthorized access.
180|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Many users may not believe there is anissue with Bluetooth security, but hackers may beable
to gain access to information from phone lists to more sensitive information that
othersmayhold on Bluetooth enabled phones and otherdevices.
Firstly,therearethreebasic meansofprovidingBluetoothsecurity:
Authentication:In this process, that is to say,the identity of the communicating devices
isverified. But ,user authentication is not part of the main Bluetooth security elements of
thespecification.
Confidentiality:In Short, this process prevents the information from being eavesdropped
byensuringthat only authorized devices canaccess andviewthe data.
Authorization:This process prevents access by ensuring that a device is authorized to use
aservicebeforeenabling itto do so.
CommonBluetoothsecurityissues
Bluebugging: In short, it’s capable of accessing all the information such as photos,
apps,contacts,etc.It’s moredangerous than bluejackingand bluesnarfing.
InConclusion,SomepreventiontipsforBluetoothhacksaretosetinvisiblemode.Therefore, makes
it more difficult for hackers to gain access to your data. Lastly, stay awakefrom the open Wi-
Fi networks in busy or untrusted locations, so that you can minimize theriskoffalling victim
to hackers.
4.4. Wi-Fi
A ubiquitousInternetof Things(IoT) dependsupon wireless connectivity,
buttherearemanyoptionsfor wireless andnotevery deviceisIPaddressable–arequisitefeaturefor
IoT.
181|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
What’smore,RFdesignisinherentlydifficult.Fewcompaniesareequippedwiththeappropriate
skills to implement RF and antenna design, and even when done, keeping thatdesign up to
date with the latest standards and getting it through FCC compliance is timeconsuming.
Figure: The wide range of IoT applications that use Wi-Fi modules shows the flexibility
andscalabilityof the interface,as well asits ubiquity.(Source:Tektronix.)
For designers, there is a very solid and proven option for wireless connectivity and the
IoT.That option is Wi-Fiand the use of modules.This feature will explain why, offer
somedesign solutions, discuss soon-to-arrive upgrades to IEEE 802.11 protocols, and show
how tobridgeZigBeeto Wi-Fi for nativeIP 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,
meshnetworking, interference immunity, and ease of use. However, some interfaces are not
yetnative-IP enabled, so cannot be addressed directly or exchange data with other devices
andserversovertheInternet.Thesethenrequireaseparategateway,addingexpenseandcomplexityt
o thefinal solution.
This is where Wi-Fi stands out: it is based on the IEEE 802.11 standards with native
IPaddressability, is ubiquitous, well understood, and can scale well in terms of data rates
tooptimize for power consumption. According to the Wi-Fi Alliance, there are more than
6.8billion installed Wi-Fi-capable devices, so the odds are pretty high that there is a local Wi-
Fiaccess point available . Note too that 802.11 standards are also IPv6 compliant, so
there’salmostno limitto thenumberof unique addresses.
While Wi-Fi is widespread and well understood, it is still a wireless interface, with all
thevagariesof design that RFentails. Understanding next steps iscritical.
182|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Easingwirelessdevelopment
After selecting Wi-Fi for an IoT application, the designer often faces the daunting
challengeof building a custom RF implementation, which requires time, money and
expertise.Designrequirementsfordevelopingawirelessdeviceinclude,ataminimum,directRFICi
ntegrationandtheabilitytospecifycomponentssuchasfilters,amplifiers,clocks,capacitors,
inductors,crystaloscillators, and the antennasthatneed tobe on the board, aswell as their
placement. There also needs to be network-matching circuitry to ensure that theradio and
antenna are well matched to avoid signal loss. Other knowledge areas includesystem layout,
software stack development, device security, connection reliability, signalinterference and
degradation,and last butsurely not least,FCC certification.
How does this task get done within typical time to market parameters given that RF
designexpertise is not something readily available to every electronics company? An
increasinglycommon way to add Wi-Fi capability is to use a pre-packaged module. This
approach greatlysimplifiestheprocess.Modulesaresuppliedtested,calibratedandpre-
certifiedtotherequired 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 forsoftwaredevelopment.Whatismore,manufacturerswhodesignandbuildtheWi-
Fimodulescan beyourRFconsultants duringthe design integration stage.
The Wi-Fi module generally contains two main parts: a Wi-Fi chip and an application
hostprocessor. The Wi-Fi subsystem includes an 802.11 radio physical layer (PHY),
baseband,mediaaccesscontrol(MAC),andperhapsacryptoengineforfast,secureInternetconnecti
on. 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),crystaloscillators, and adebug interface.
In designing a Wi-Fi IoT solution, the starting point is an understanding that IEEE
802.11represents a family of standards that until just recently operated only in the 2.4 GHz
(IEEE802.11b/g/n) and 5 GHz(IEEE 802.11a/n/ac) unlicensed bands.There are three key
factorsto consider when evaluating these protocols: data rate, range, and power requirements.
Whenyou comparethe different Wi-Fi protocols, 802.11b/g has the advantagein
compatibilitywithinstalleddevicesandpowerrequirementswhile802.11nand802.11achavethead
vantage of higher datathroughputfor multimediaapplicationssuchasvideostreaming(seeTable).
183|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
When designing for IoT applications, however, a higher data rate protocol is not
alwayspreferable. Even though 802.11ac can crank it up to a maximum of 1.3 Gbps, most
embeddedapplications(e.g.,machinetomachine[M2M]dataandcontroldevices)arepowerconstra
inedandcan get by with amuchlower datarate.
One more good reason to choose Wi-Fi is that within the next year or so technology
upgradeswill make it much more capable. For example, the Wi-Fi Alliance recently
announced theWi-Fi HaLow (pronounced "halo") designation for products incorporating
IEEE 802.11ahtechnology. 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 casesareprimarily forwirelesssensor networks,aclassicIoT application.
AlsounderdevelopmentisIEEE802.11ai,whichwillprovideafastinitiallinksetup(achieving a
secure link setup in less than 100 ms) and IEEE 802.11aq, being developed
toprovideacellular-likeautomaticnetwork-discovery experience.
Modulesand devkits
RFengineeringcanbeatrickybusiness,especiallyforneophytesinthediscipline.Recognizing this,
RF silicon suppliers are providing modules, dev kits and reference designsthatmakeadding
wireless connectivity to a product much easier.
184|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Microchip,forexample,suppliesanIoTdevelopmentkit(DM990001)usingamoduledriven by
a 32-bit controller. It employs two Microchip components,the
MRF24WG0MA/B pre-certifiedWi-Fimodule,whichsupportsboth802.11band802.11g, and
the PIC32MX695F512H microcontroller with 128 Kbytes of RAM and 512Kbits 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 dedicateddirectmemory
access(DMA)channelsforUSB OTG andEthernet.
The starter kit is powered by Amazon Web Services (AWS), a managed cloud platform
thatlets connected devices securely interact with cloud applications. With AWS IoT
applicationscan keep track of and communicate with all networked devices, all the time, even
when theyaren’t connected.
AmazonhasputtogetherQuickstartreferencedeploymentsforitsAWSIoT,whichisdesigned to
show off some of the capabilities of the platform. AWS IoT can be especiallyhelpful if you
plan to use Amazon as your hosting provider. It supports HTTP, WebSocketsfor web
browsers and web servers, and MQ Telemetry Transport (MQTT), a
lightweightcommunicationprotocolforsmallsensorsandmobiledevicesspecificallydesignedtoto
lerate intermittent connections, minimize the code footprint on devices, and reduce
networkbandwidthrequirements.
185|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Figure:TI’sCC3100MODisdesignedtosimplifytheimplementationofInternetconnectivity. It
integrates all protocols for Wi-Fi and the Internet, which greatly reduces
hostMCUsoftwarerequirements.
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
memoryfootprint requirement toless than 7 Kbytes for code and 700bytes of RAM for data
foraTCP client application. The CC3100MOD IoT module solution is also FCC, IC, CE, and
Wi-Ficertified.
186|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
BlockdiagramoftheSTSPWF01Sserial-to-Wi-Fib/g/nmodule.Withlowpowerconsumption and
a small form factor, it can be used for both fixed and mobile wirelessapplications.
The SPWF01S comes with CE, FCC and IC certification and meets industrial temperature-
rangerequirements.
While we have focused on Wi-Fi, the ZigBee wireless standard is a popular choice for a
widerange of applications that require low power, medium range, and flexible networking
that isrelativelyeasytoinstall,configureandmaintain.ZigBee,however,lacksacrucialrequirement
for IoT applications: native IP connectivity. Digi International’s XBee ® Wi-Fimodules bridge
this gap. To get you started, the company’s XBee Wi-Fi Cloud kit (xka2B-wft-
0)includesanXBeeWi-Fi(S6B)module,XBeeUSBdevelopmentboardwithbreadboard, 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-
Fimodules share a common footprint with other XBee modules, which allows different
XBeetechnologiesto bedrop-in replacements for eachother.
IoT applications depend upon wireless connectivity, but there are numerous wireless
protocoloptions. RF design also is inherently difficult and few companies are equipped with
theappropriate 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
complianceis time consuming.This Wi-Fi modules and their associated kits and reference
designs
candramaticallysimplifytheimplementationchallengesfacingdesignersofnewIoTdevices.
4.5. Zigbee
When you are designing, planning and prototyping a wireless application, the protocol
youchoose is a key component, with considerations for security, flexibility and the ability
todeployto multiple regions.
187|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
The802.15.4specificationuponwhichtheZigbeestackoperatesgainedratificationbythe Institute
of Electrical and Electronics Engineers (IEEE) in 2003. The specification is apacket-based
radio protocol intended for low-cost, battery-operated devices. The protocolallows devices to
communicate in a variety of network topologies and can have battery lifelastingseveral years.
TheZigbeeAdvantage
The Zigbee 3.0 protocolisdesigned tocommunicate data through noisyRF
environmentsthatarecommonincommercialandindustrialapplications.Version3.0buildsontheex
isting Zigbee standard but unifies the market-specific application profiles to allow
alldevicestobewirelesslyconnectedinthesamenetwork,irrespectiveoftheirmarketdesignationan
d function.
188|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
monitoring and control from devices such as smartphones and tablets on a LAN or
WAN,includingtheInternet, andbrings the trueInternetof Things to fruition.
Zigbeeprotocolfeaturesinclude:
Support for multiple network topologies such as point-to-
point,point-to-multipointandmesh networks
Lowdutycycle –provideslong batterylife
Lowlatency
DirectSequenceSpreadSpectrum(DSSS)Upto65,000nodespernetwork
128-bitAESencryptionforsecuredataconnections
Collisionavoidance,retriesandacknowledgements
ZigbeeWirelessMeshNetworking
What IsZigbee?
Zigbee is a wireless technology developed as an open global market connectivity standard
toaddress the unique needs of low-cost, low-power wireless IoT data networks. The
Zigbeeconnectivity standard operates on the IEEE 802.15.4 physical board radio
specification andoperatesin unlicensed radiobands including 2.4 GHz,900 MHz and
868MHz.
The 802.15.4 wireless specification upon whichthe Zigbee stack operates gained
boardratificationbythe InstituteofElectricalandElectronicsEngineers
(IEEE)in2003.Thespecification is a packet-based radio board protocol intended for low-cost,
battery-operateddevices and products. The protocol allows devices to communicate data in a
variety ofnetworktopologies and can havebatterylifelasting severalyears.
TheZigbee3.0Protocol
The Zigbee protocol has been created and ratified by member companies of the Zigbee
BoardAlliance.Over 300 market leading semiconductor manufacturers, technology firms,
OEMsandservicecompaniescomprisetheZigbeeAlliancemembershipboard.TheZigbeeprotocol
was designed to provide an easy-to-use wireless data solution characterized bysecure,reliable
wirelessnetworkarchitectures.
TheZigbeeAdvantage
The Zigbee 3.0 protocol is designed tocommunicate data through noisyRF environmentsthat
are common in commercial and industrial market applications. Version 3.0 builds on
theexisting Zigbee connectivity standard but unifies the market-specific application profiles
toallow all devices to be wirelessly connected in the same network, irrespective of their
marketdesignationandfunction.Furthermore,aZigbee3.0certificationschemeensurestheinterope
rabilityof productsfromdifferentdevice manufacturers. ConnectingZigbee 3.0networks to the
IP domain opens up wireless monitoring and control from radio devices suchas smartphones
and tablets on a LAN or WAN, including the Internet, and brings the trueInternetof Things to
fruition.
189|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Zigbeeprotocolfeaturesinclude:
Support for multiple network topologies such as point-to-
point,point-to-multipointandmesh networks
Lowduty cycle– provideslong batterylife
Lowlatency
DirectSequenceSpread Spectrum(DSSS)
Upto 65,000 nodesper network
128-bitAESencryptionforsecuredataconnections
Collisionavoidance,retriesandacknowledgements
The Zigbee 3.0 software stack incorporates a ‘base device’ that provides consistent
behaviorfor commissioning nodes and devices into a network. A common set of
commissioningmethodsis provided, including Touchlink,amethod ofproximity
commissioning.
ZigbeeWirelessSecurity
Zigbee 3.0 provides enhanced network security. There are two methods of security that
giveriseto two types of network:
Centralized security: This method employs a coordinator/trust center that forms
thenetwork and manages the allocation of network and link security keys to
joiningnodes.
Distributed security: This method has no coordinator/trust center and is formed by
arouter. Any Zigbee router node can subsequently provide the network key to
joiningnodes.
Nodes adopt whichever security method is used by the hub network they join. Zigbee
3.0supports the increasing scale and complexity of wireless networks, and copes with large
localnetworks of greater than 250 nodes. Zigbee also handles the dynamic behavior of
thesenetworks (with nodes appearing, disappearing and re-appearing in the network) and
allowsorphaned nodes, which result from the loss of a parent, to re-join the network via a
differentparent. The self-healing nature of Zigbee Mesh networks also allows nodes to drop
out of thenetworkwithout any disruption to internal routing.
ZigbeeProtocolCompatibility
The backward compatibility of Zigbee 3.0 means that applications and smart home
devicesalreadydeveloped underthe Zigbee Light Link1.0 or Home Automation 1.2
profileareready for Zigbee 3.0. The Zigbee Smart Energy profile is also compatible with
Zigbee 3.0 atthe functional level, but Smart Energy has additional security requirements that
are onlyaddressed within the profile.
ZigbeeDeviceData
Zigbee’s Over-The-Air (OTA) upgrade feature for software updates during device
operationensures that applications on devices already deployed in the field/market can be
seamlesslymigrated to Zigbee 3.0. OTA upgrade is an optional functionality that
manufacturers areencouragedto support in theirZigbeeproducts'application layer.
ZigbeeMeshNetworks
190|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
A key component of the Zigbee protocol is the ability to support mesh networking. In a
meshnetwork, nodes are interconnected with other nodes so that multiple pathways connect
eachnode.Connectionsbetweennodesaredynamicallyupdatedandoptimizedthroughsophisticate
d,built-in mesh routing table.
ZigbeeWirelessApplications
Zigbee enablesbroad-basedwave deploymentof wirelessnetworks withlow-cost,low-power
solutions. It provides the ability to run for years on inexpensive batteries for a host
ofmonitoringandcontrolapplications.Smartenergy/smartgrid,AMR(AutomaticMeterReading),
lighting controls, building automation systems, tank monitoring, HVAC
control,medicaldevices,dbmradio,ghzwirelessprotocols,wirelesssensornetworksandfleetapplic
ations are just some of the many spaces where Zigbee technology is making
significantadvancements.
DigiXBee3 ZigbeeTechnology
Digi is a member of the Zigbee Alliance and has developed a wide range of data
networkingsolutions based on the Zigbee protocol. Digi XBee 3 is the latest in a long line of
radiodevices that provide an easy-to-implement solution that provides functionality to
connect to awidevariety of deviceswith robust connectivitystandards.
4.6. GPS
GPS uses satellites to monitor the movement of anything equipped with such a
GPStracking device, including automobiles, humans, and even pets. It operates in any
weatherconditionand offers precise location updates inreal-time. As one of
theearliestwaystotrack and disseminate digital information from the real environment, GPS
has significantlyimpacted IoT technology. The Internet of Things (IoT) may gather and
measure enormousamounts of data on anything from individual health to public
transportation; GPS tracking isrequiredto providelocation information forsuch objects.
191|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
A more reliable and easily accessible data set can be built using GPS and the
Internetof Things. In the same way that GPS pinpoints the precise location of a vehicle, the
InternetofThings isabletomonitor movingitems and collectdataontheirmovementsin real time.
HowDoesGPS Function?
GPS satellites complete two accurate orbits around the planet every day. An
individualsatellite's signal and orbiting parameters can be decoded and used to pinpoint the
satellite'slocation via a GPS receiver. This data, together with triangulation, is used by GPS
receiverstopinpoint the precise location ofits owners.
TheLong-Term PerspectiveofGPSwithIoT
It is possible that all of your belongings can be located using GPS. Italian firm Sherlock,
forinstance, uses GPS and the Internet of Things to keep tabs on your bike. Bicycle owners
canuse this kind of tracking to prevent bike theft. In addition, the owner of the vehicle will
beinformedofany modifications doneto it.
Cut back on the money spent on managing employees. By equipping workers with
GPStrackers, 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
cutadministrativeexpenses
SomeDevicesthatarepartoftheInternetofThingsanduseaglobalpositioningsystem
192|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
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 theweatherbecomes.Itiscompact, lightweight,and built towithstand theelements.
LORAWANSENSORDATA:TheInertialSensorisabattery-operateddatacommunicator that
connects to various sensors, GPS, inputs, and outputs and then uploadsthatdata to
aLoRaWAN network. Useful for sensorsandagricultural uses.
NEO-6MGPSModule withArduino
ThisguideshowshowtousetheNEO-6MGPSmodulewiththeArduinotogetGPSdata. GPS stands
for Global Positioning System and can be used to determine position, time,andspeed if
you’retravelling.
You’lllearnhowto:
WiretheNEO-6MGPSmoduleto theArduino UNO
Getraw GPS data
ParserawdatatoobtainselectedandreadableGPSinformation
Getlocation
IntroducingtheNEO-6MGPSModule
The NEO-6M GPS module is shown in the figure below. It comes with an external
antenna,anddoes’tcome withheaderpins. So,you’ll needtoget andsolder some.
193|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Thismodulehas anexternalantennaandbuilt-inEEPROM.
Interface:RS232TTL
Powersupply: 3Vto 5V
Defaultbaudrate:9600bps
WorkswithstandardNMEAsentences
PinWiring
TheNEO-6MGPSmodulehasfourpins: VCC, RX, TX,and GND.Themodulecommunicates
with the Arduino via serial communication using the TX and RX pins, so thewiringcouldn’t
besimpler:
VCC 5V
TX RXpindefined inthesoftwareserial
GND GND
GettingGPSRawData
To get raw GPS data you just need to start a serial communication with the
GPSmoduleusingSoftwareSerial. Continuereading to seehow to do that.
PartsRequired
WiretheNEO-6M GPS moduleto yourArduino byfollowingthe schematicbelow.
194|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
void
setup(){Serial.begi
n(9600);ss.begin(9
600);
}
voidloop(){
while(ss.available()>0){
// get the byte data from the
GPSbyte gpsData =
ss.read();Serial.write(gpsData);
}
}
4.7. GSM/GPRSModule
GSM/GPRSmodule isusedtoestablishcommunicationbetweenacomputeranda GSM-
GPRSsystem. GlobalSystemforMobilecommunication(GSM)
isanarchitectureusedformobilecommunication in mostofthe countries.
195|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
BlockDiagramShowingDiffrentParts OfTypicalGSM/GPRSModule
Global Packet Radio Service (GPRS) is an extension of GSM that enables
higherdata transmission rate. GSM/GPRS module consists of a GSM/GPRS modem
assembledtogetherwith power supplycircuit andcommunicationinterfaces (like RS-232,
USB,etc)for computer. TheMODEM is the soul of such modules.
WirelessMODEMs
Wireless MODEMs are the MODEM devices that generate, transmit or decode data from
acellularnetwork,forestablishingcommunicationbetweenthecellularnetworkandthecomputer.
These are manufactured for specific cellular network (GSM/UMTS/CDMA)
orspecificcellulardatastandard(GSM/UMTS/GPRS/EDGE/HSDPA)ortechnology(GPS/SIM).
Wireless MODEMs like other MODEM devices use serial communication
tointerfacewithandneed Hayescompatible ATcommands
forcommunicationwiththecomputer(any microprocessor ormicrocontrollersystem).
GSM/GPRSMODEM
GSM/GPRSMODEMisaclassofwirelessMODEMdevicesthataredesignedforcommunicationof
acomputerwiththeGSMandGPRSnetwork.ItrequiresaSIM
196|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
(Subscriber Identity Module) card just like mobile phones to activate communication
withthe network. Also they have IMEI (International Mobile Equipment Identity) number
similarto mobile phones for their identification. A GSM/GPRS MODEM can perform the
followingoperations:
1. Receive,sendordeleteSMSmessagesinaSIM.
2. Read,add,searchphonebookentriesoftheSIM.
3. Make,Receive,orrejectavoicecall.
The MODEM needs AT commands, for interacting with processor or controller, which
arecommunicatedthroughserialcommunication.Thesecommandsaresentbythecontroller/proces
sor. The MODEM sends back a result after it receives a command.
DifferentATcommandssupportedbytheMODEMcanbesentbytheprocessor/controller/compute
rtointeract with the GSMand GPRS cellular network.
GSM/GPRSModule
AnImageof
AssembledCircuitForGSM/GPRSModuleWithStandardCommunicationInterfacesLikeRS-
232Or USB
AGSM/GPRSmoduleassemblesaGSM/GPRSmodemwithstandardcommunicationinterfaces
like RS-232 (Serial Port), USB etc., so that it can be easily interfaced with acomputer or a
microprocessor / microcontroller based system. The power supply circuit isalsobuilt in
themodule that can be activated by usinga suitable adaptor.
MobileStation(CellphonesandSIM)
A mobile phone and Subscriber Identity Module (SIM) together form a mobile station. It
isthe user equipment that communicates with the mobile network. A mobile phone
comprisesofMobile Termination,Terminal EquipmentandTerminal Adapter.
197|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Mobile Termination is interfaced with the GSM mobile network and is controlled by
abaseband processor. It handles access to SIM, speech encoding and decoding, signaling
andother network related tasks. The Terminal Equipment is an application processor that
dealswith handling operations related to keypad, screen, phone memory and other hardware
andsoftwareservicesembeddedintothehandset.The TerminalAdapter
establishescommunication between the Terminal Equipment and the Mobile Termination
using ATcommands. The communication with the network in a GSM/GPRS mobile is
carried out bythebaseband processor.
GSMTechnologyArchitecture
Themain elementsin the GSM architectureincludethefollowing.
TheArchitectureofGSMTechnology
NetworkandSwitchingSubsystem(NSS)
Base-StationSubsystem(BSS)
Themobile station (MS)
OperationandSupportSubsystem(OSS)
NetworkSwitchingSubsystem(NSS)
InGSMsystemarchitecture,itincludesdifferentelements,whicharefrequentlyknownasthecoresys
tem/network.Here,itisbasicallyadatanetworkincludingavarietyofunitsto
198|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
MobileSwitchingCentre(MSC)
The Mobile Switching Centre or MSC is the key element in the core network region of
theGSM network architecture. This mobile services switching center works like a
standardswitching node in an ISDN otherwise PSTN, however, it also gives extra
functionality toallow the mobile user necessities to be supported like authentication,
registration, inter-MSChandoverscall location&routingof thecall to a cell phonesubscriber.
And, it also provides an edge toward the public switched telephone network so that the
phonecalls can be connected from the network of the mobile to a phone to a landline.
Interfaces toother mobile switching center server are providedtoallow mobile callstobe made
tomobilesover dissimilarnetworks.
HomeLocationRegister(HLR)
ThisHLRdatabaseincludestheinformationregardingtheadministrativelikeeverysubscriber with
their previous identified location. Like this, the GSM network is capable toconnect the calls
to the related base station for the mobile switch. Once an operator turns ONhis/her phone,
and then the phone registers through the network so that it is probable
todecidewhichbasetransceiverstationiscommunicatingsothatincomingcallscanbeconnectedpro
perly.
Even once the mobile is switched on, but not active then it again registers to make sure
thatthe HLR network is responsive to its most recent location. There is one HLRfor
eachnetwork, even though it may be dispersed across a variety of sub-centers for
operationalcauses.
VisitorLocationRegister(VLR)
The VLR includes preferred information that is received from the HLR network to allow
thepreferred services for the separate subscriber. The visitor location register can be
executedlike a separate unit; however, it is usually realized like an essential element of the
MSC,before an individual unit.Thus, access is finishedquicker & moreconvenient.
EquipmentIdentityRegister(EIR)
The EIR (Equipment Identity Register) is the unit that makes a decision whether
specifiedmobile gear may be permitted over the network. Every mobile gear includes a
numberidentifiedliketheIMEIorInternationalMobile Equipment Identity.
So, this IMEI number is fixed within the mobile equipment & is verified through the
networkwhile registration. It mainly depends on the information that is held within the EIR,
and themobile device may be assigned one of 3 conditions which allowed over the network,
barredaccess,otherwise watched in caseits problems.
199|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
AuthenticationCentre(AuC)
TheAuC(authenticationcenter)isaprotectedfilethatincludesthesecretkeyintheSIMcardoftheuser
.TheAuC ismainly used forverification & forcodingonthe radiochannel.
GatewayMobileSwitchingCentre(GMSC)
The GMSC/ Gateway Mobile Switching Centre is the end to which a ME finishing call
isprimarily connected without any information about the MS’s place. The GMSC obtains
theMobile Station Roaming Number (MSRN) from the MSISDN based on HLR &
connectingthe call toward the exact visited MSC. The “MSC” division of the name GMSC is
confusingasthe gateway process does not needany linkingtoward an MSC.
SMSGateway(SMS-G)
The SMS gateway or SMS-G is used jointly to explain two SMS-Gateways in the
GSMstandards.Thesegatewayscontrol messages whicharedirectedin dissimilar ways.
The Short Message Service Gateway Mobile Switching Centre (SMS-GMSC) is used
forshort messages which are being transmitted to an ME. The Short Message Service Inter-
WorkingMobileSwitchingCentre(SMS-IWMSC)isusedforshortmessagescreatedthrough a
mobile network. The main role of SMS-GMSC is related to GMSC, but the SMS-
IWMSCoffersapermanent accessend to theSMS Centre.
These units were the major ones that are used in the network of GSM technology. They
werenormally co-located, however frequently the overall middle network was transmitted
aroundthe country wherever the network was situated. In case of malfunction, it will give
someflexibility.
BaseStation Subsystem(BSS)
Itactsasaninterfacebetweenthemobilestationandthenetworksubsystem.Itconsistsofthe Base
Transceiver Station which contains the radio transceivers and handles the
protocolsforcommunicationwithmobiles.ItalsoconsistsoftheBaseStationControllerwhichcontr
ols the Base Transceiver station and acts as an interface between the mobile station
andmobileswitching center.
The network subsystem provides the basic network connection to the mobile stations.
Thebasic part of the Network Subsystem is the Mobile Service Switching Centre which
providesaccess to different networks like ISDN, PSTN, etc. It also consists of the Home
LocationRegister and the Visitor Location Register which provides the call routing and
roamingcapabilitiesofGSM.
It also contains the Equipment Identity Register which maintains an account of all the
mobileequipment wherein each mobile is identified by its own IMEI number. IMEI stands
forInternationalMobile Equipment Identity.
200|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
TheBSSorBaseStationSubsystemsectionofthesecondgenerationGSMnetworkarchitectureisbas
icallyconnectedwiththemobilesoverthenetwork.Thissubsystemincludestwo elements which
arediscussed below.
BaseTransceiverStation (BTS)
The BTS (Base Transceiver Station) which is utilized within a GSM network includes
theradio Tx, Rx & their related antennas to transmit, receive & directly converse through
themobiles.Thisstationisthe importantelementfor everycellanditconverseswiththemobiles &
the interface among the two is identified like the Um interface with relatedprotocols.
BaseStationController(BSC)
TheBSC(basestationcontroller)isusedtoformthenextphasereverseintotheGSMtechnology.This
controllerisusedtocontrolacollectionofbasetransceiverstations&itisfrequentlyco-located
throughoneof the transceiver stationswithinthe
group.Thiscontrollermanagestheresourcesofradiotocontroldifferentitemslikehandoverinthecol
lectionofBTSs, assigns channels. It converses with the Base Transceiver Stations over Abis
interface.ThesubsystemelementinthebasestationoftheGSMnetworkusestheradioallowabletech
nologytoallowanumberofoperatorstorighttousethesystemconcurrently.Everychannelsupportsu
pto8operatorsbyallowingabasestationtoincludedifferentchannels;ahugenumberof operators
could be accommodatedthrough every basestation.
Thesearelocatedcarefullythroughtheproviderofthenetworktoallowwholeareacoverage. This
area can be enclosed with a base station that is often being called a cell.Because it is not
achievable to stop the signals from overlapping into the nearby cells
andchannelswhichareusedin single-cellarenot utilized in thenext.
MobileStation
Itisthemobilephonewhichconsistsofthetransceiver,thedisplay,andtheprocessorandiscontrolled
by aSIM cardoperating over thenetwork.
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
bebroadcasted.
The mobile station includes a number called the IMEI. This can be set up on the
mobilephonewhile manufacturing & it cannot be modified.
It is accessed by the network during registration to check whether the equipment has
beenreportedas stolen.
201|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
The SIM (Subscriber Identity Module) card includes the data which gives the
useridentity toward the network. And also, it includes different information like a number
calledthe IMSI (International Mobile Subscriber Identity). When this IMSI is used in the
SIM card,the mobile user couldsimplychange mobilesbymovingthe SIMfromone mobile
toanother.
So mobile changing is easy without changing the same mobile number means that
peoplewould frequently improve, thus making a further income stream for the providers of
network&serving to enhancethetotal financial victory ofGSM.
OperationandSupportSubsystem (OSS)
The operation support subsystem (OSS) is a part of the complete GSM
networkarchitecture. This is connected to the NSS & the BSC components. This OSS is
mainly usedto control the GSM network & the BSS traffic load. It should be noted down that
when
thenumberofBSenhancesthroughthesubscriberpopulationscalingthensomeofthepreservation
tasks are moved to the base transceiver stations so that the ownership cost of thesystemcan
bereduced.
FeaturesofGSM Module
Thefeatures oftheGSMmodule includethefollowing.
Improvedspectrumefficiency
Internationalroaming
Compatibilitywithintegratedservicesdigitalnetwork(ISDN)
Supportfornewservices.
SIMphonebookmanagement
Fixeddialingnumber(FDN)
Real-timeclockwithalarmmanagement
High-qualityspeech
Usesencryptionto makephonecalls moresecure
Shortmessageservice(SMS)
ThesecuritystrategiesstandardizedfortheGSMsystemmakeitthemostsecuretelecommunications
standard currently accessible. Although the confidentiality of a call andsecrecy of the GSM
subscriber is just ensured on the radio channel, this is a major step inachievingend-to-end
security.
GSMModem
202|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
A GSM modem is a device that can be either a mobile phone or a modem device
thatcan be used to make a computer or any other processor communicateover a network.
AGSMmodemrequiresaSIMcardtobeoperatedandoperatesoveranetworkrangesubscribed by
the network operator.It can be connected to a computer through serial, USB,orBluetooth
connection.
A GSM modem can also be a standard GSM mobile phone with the appropriate
cableandsoftwaredrivertoconnecttoaserialportorUSBportonyourcomputer.GSMmodemisusual
lypreferabletoaGSMmobilephone.TheGSMmodemhasawiderangeofapplicationsintransactiont
erminals,supplychainmanagement,securityapplications,weatherstations, and GPRS mode
remotedata logging.
Workingof GSMModule
From the below circuit, a GSM modem duly interfaced to the MC through the
levelshifter IC Max232. The SIM card mounted GSM modem upon receiving digit command
bySMS from any cell phone sends that data to the MC through serial communication. While
theprogram is executed, the GSM modem receives the command ‘STOP’ to develop an
output attheMC, thecontact point of which areusedto disable theignitionswitch.
The commandso sentby the user is based onan intimation received byhim through theGSM
modem ‘ALERT’ a programmed message only if the input is driven low. The
completeoperationis displayed over a16×2LCD display.
203|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
GMSModemCircuit
DifferencebetweenGSMmobileandGSM/GPRSmodule
A GSM mobile is a complete system in itself with embedded processors that
arededicatedtoprovideaninterfacebetweentheuserandthemobilenetwork.TheATcommands are
served between the processors of the mobile termination and the terminalequipment. The
mobile handset can also be equipped with a USB interface to connect with acomputer, but it
may or may not support AT commands from the computer or an externalprocessor/controller.
TheGSM/GPRSmodule,ontheotherhand,alwaysneedsacomputerorexternalprocessor/controlle
r toreceive ATcommandsfrom.GSM/GPRS module itselfdoesnotprovide any interface
between the user and the network, but the computer to which module isconnectedis
theinterfacebetween user and network.
An advantage that GSM/GPRS modules offer is that they support concatenated SMS
whichmay not be supported in some GSM mobile handsets. Also some mobile handsets
can’treceiveMMSwhen connected to acomputer.
ApplicationsofGSM/GPRSmodule
204|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
The GSM/GPRS module demonstrates the use of AT commands. They can feature all
thefunctionalities of a mobile phone through computer like making and receiving calls,
SMS,MMS etc. Thesearemainly employedfor computer basedSMS andMMSservices.
4.8. RaspberryPiOperatingSystems
Raspberry Pi isa low-cost pocket computer that is veryeconomical toown.It isabout
the size of an ATM Card and can work as a fully functional computer in certain normaluse
cases, like working with simple applications, playing low-end games, etc. It was firstreleased
in 2012 by the Raspberry Pi foundation with the aim to provide easy access
tocomputingeducationtoeveryone. It can cost as less as 5$ to a maximum
priceof100$(which is rare).
Scope
wewillbeunderstandingOperatingsystemsthatcan beinstalledonaRaspberryPi.
We'lllearn aboutWhatanoperatingsystemingeneralis.
We'llgothroughaVarietyofOperating SystemsthataRaspberry Picanrun.
Introduction
Asreadabove, RaspberryPi isaverylow-costcomputerthatcomesalongwiththeadvantage of
portability. However, being in such a small form factor, it gets bounded by thetype of
hardware to use in making it; hence, it will be significantly tough to run
regularoperatingsystems on it.
Due to this, specific operating systems were designed to power a Raspberry Pi; some of
themwere entirely new, while some originated from existing popular operating systems. Most
oftheRaspberryPiOSisLinuxbased,butitalsohaswindows10-based RaspberryPiOS(Windows
10IoTcore) built explicitlyforlow-powered deviceslikethis.
WhatisanOperatingSystem?
The technical definition is An operating system is an interface between the hardware of
amachine and the user who is using it, but what does this really mean? It means it
isbasically the medium using which we communicate with our computer machine. It does
notmatter if we have the fastest system in the world; at the end of the day, that is just
hardware,an object; and we do not know how to work with it, so we need some medium that
works asan intermediate between us and the computer, i.e., when we press ctrl on our
keyboard, itshould instruct the computer what to react based on that; when we want to open
someapplication,itshouldprovideusawaytodoso,bylistingalltheavailableapplicationsonthe
system.
Meaning an operating system is a software program that helps us to use and to connect
withthe computer hardware. For example, if we want to use our mouse or keyboard, only
with thehelp of an OS we can do that; if we want to install some program on our computer,
we wouldbe needing an OS; if we want to create a file, we need an OS; we want to delete a
file, wewouldagainbeneedinganOS,i.e.,withoutanoperatingsystemwecannotusethecomputer
205|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
hardware, we would be needing some underlying software, i.e., some operating system,
usingwhich wewould do so.
WhatisaRaspberryPiOperatingSystem?
Now, what is Raspberry Pi operating system? Before that, let's first try to understand
whatRaspberryPiis. RaspberryPiisasmall,low-
costcomputer,anditssizeisaboutthesizeofanATMcard,whichisdevelopedbytheRaspberryPifoun
dation.Theorganization'smissionistoeducatepeopleincomputingandtoprovideeasieraccesstoco
mputereducation.
The above image is a picture of a Raspberry Pi; we can see that there are various
portsavailablein it on which differentdevicescan bemounted andused.
It was first launched in 2012, and from then onwards, various variations of it have
beenlaunched. The original Raspberry Pi had a single-core 700mhz CPU and a 256MB of
RAM,butithasevolvedalotsincethen;today,wehaveaquad-coreRaspberryPiwithaclock
206|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
speed of around 1.5Ghz and up to 4GB of RAM. Surprisingly the cost of Raspberry Pi
hasalways been less than 100 USD. In fact, the Raspberry Pi Zero (an even low-cost version
ofregular Raspberry Pi) costs as less as 5 USD. A full-fledged general-purpose CPU under
5$,that'swhattheorganization'smissionis"Aimingtoprovidepeopleeasierandlow-costaccessto
the computers."
Raspberry Pi is used by people all around the world in learning how to program,
buildhardware projects, do home automation, and implement Kubernetes clusters, and it is
evengetting used in some industrial applications. Raspberry Pi is a very economical computer
thatrunsLinux Operating System.
Now, let's talk about which specific distribution of Linux Raspberry Pi uses. Raspberry
Piofficially recommends the use of the Raspbian Operating System. It is a Debian-based
OS,explicitlymadeforRaspberry Pi and henceits nameRaspbian.
ExplorefreecoursesbyourtopinstructorsViewAll
TARUNLUTHRA
JavaCourse-
MasteringtheFundamentals56k+enrolled
RAHULJANGHU
PythonCertificationCourse:Mastertheessentials42k+e
nrolled
PRATEEKNARANG
C++Course:LearntheEssentials29k
+enrolled
35,262+learnershaveattendedtheseCourses.
Raspbian
RaspbianorRaspberryPiOS isaLinux-basedoperatingsystembuiltspecificallyforRaspberry 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 computingpower.
207|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
NOOBS
New Out Of the Box Software, or simply NOOBS is an operating system installer
forRaspberry Pi, delivered primarily on an SD card, which contains a variety of
operatingsystems, out of which we can choose which one we want to install on our Raspberry
Pi. It ismade for people who are absolutely new to the Raspberry Pi and do not want to deal
with
thecomplexsettingupprocessofburninganOSimageonanSDcard.NOOBSisprovidedalongwith
every new Raspberry Pi at the timeof its purchase.
With NOOBS, the user only needs to connect their Raspberry Pi to a display screen and
akeyboard and then power it up; the NOOBs will boot. There we can select which
operatingsystem we want to install, and NOOBS will install the respective OS on the same
SD cardwithinafew minutes.
OtherOperating Systems
Let's now look at some of the other Operating systems apart from the Raspbian OS,
whichcanbebooted on theRaspberry Pi.
Minibian
While Raspbian OS is very lightweight as far as we talk about operating systems, but if
wewant something even more straightforward, then we can go for Minibian OS. It is a
minimalversionofRaspbianforRaspberryPimachines.Thenow-goingversionofminibianisbased
208|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
on the recent Raspbianbuild and will run on all the versions of Raspberry Pi. Minibiandiffers
from Raspbian in a number of ways, but the main difference is it is built more forelectronics
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,
someelectronicsapplications,etc.Notably,itdoesnotincludeaGraphicalinterfaceforinteraction,
which makes it an excellent choice for embedded projects. The result then is, wehave a
capable and working operating system in less than 500MB which merely uses 30MBof
RAM.
RaspbianLite
ItisalsoalightweightoperatingsystemforRaspberryPi withaminimalsetofpackages.Itis advised
only for experienced users who are able to establish ssh connections and remotemanagement
using the command line, as it does not includes the GUI interface. Itis morelike a command
line-based operating system where we would be needing to type commandsto control our
Raspberry Pi computer. One advantage of this is that it can run on a very lowamount of CPU
and RAM. It should be noted that Raspbiain lite OS can also be
convertedintoacompletedesktopenvironmentwithaGUIinterfacebyinstallingthenecessarypacka
ges.
RISCOS
RISC OS is an open-source OS initially developed in Cambridge in the 1980s and was
thefirst operating system for ARM processors. It is neither related to Linux, Windows, or
anyother operatingsystem;hence,divingintoitwillignore our
previousoperatingsystemexperiences. Understanding the RISC OS will be a completely
different thing, and it will taketimefor us to get used to it.
WindowsIoT Core
ItisaversionofWindowsOS,specificallywindows10,builtexplicitlyforRaspberryPi.Itishelpfulfo
rwindowsenthusiastswho wishtoutilize the RaspberryPi environmenttodevelop their projects.
It is mostly used to construct and build IoT prototype requirementsbased on windows 10.
This version of Raspberry Pi OS lays emphasis on the device mainlyonconnectivity,
security,cloud integration, etc.,regions.
UbuntuMate
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-
poweror oldappliances.ItisaflavorofUbuntuthatusesthe Matedesktopenvironment.Itprioritizes
pre-packaging the apt package manager into its software deployment and
talkingaboutthecommunicationtoremote
workstations;ubuntuMATEisdependable.TorunitonaRaspberryPidevice,a4GBsdcardisallthatis
required.ItshouldalsobenotedthatubuntumateOSisconsistentlymaintainedandupdatedbyitsdeve
lopers.Itcanbedownloadedfrom theofficial websiteofUbuntuMATE.
GentooLinux
209|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
SARPI
SlackwareARM,or SARPI,isawell-knownoperatingsystemintheRaspberryPicommunity. It is
often regarded as one of the substantial operating systems to run on theRaspberry Pi. This is
because it has a very simple-to-implement software architecture. TheboottimeofSARPIOSis
reallyless, making it livein lessthan 30 seconds of time.
FreeBSD
FreeBSD is an open-source Unix-like operating system derived from the Berkeley
SoftwareDistribution or BSD, which was based on the research of Unix (early versions of the
Unixoperatingsystem).Itworksseamlesslywithpowerfulhardware.Itssoftwaredesignmakesita
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 alsobeaperfect choiceforone'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
upemulatorson systems like Raspberry Pi.
OpenELEC
Open Embedded Linux Entertainment Center or OpenELEC. It is a minimal-sized OS,
oftenreferred to as Just Enough Operating System or JeOS. If one is aware of the Kodi
MediaCenter, which is a tool for managing media files. The primary purpose of this OS is
totransformtherunning system into Kodi.
OSMC
OSMC isa free andopen-source operating systemof raspberry pithatstands for OpenSource
Media Center. It is simple and easy to work with the program that can independentlysupply
KodiOperatingSystem functionslikemediafileformatmanagement.Itsuser-friendly interface is
simple and sophisticated, and its built-in image library contributes to itsextensive
customization possibilities. Therefore, it is an excellent choice if we majorly
wanttohandlemediamaterials 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 ofRaspBSD features FreeBSD with the pre-installed Openbox window manager and
the LXDEdesktopenvironment. RaspBSD isbased on FreeBSD's currenttree.
210|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Linutop
Linutop is a Raspbian OS-based Linux operating system of the raspberry pi. It's
softwaresecurity makes it the ideal choice for web kiosks and digital signage players.
Moreover,
itobligatesitsfeaturesandperformancespecificationstobusinessuserswhowishforRaspberryPi's
digital signageand internet stall solutions.
KaliLinux
Kali is a Debian-based operating system particularly made for penetration testing. It
comeswith both the 32bit and 64bit architecture and is also one of the most feature-rich OS
we havetalked about so far. It has all the necessary tools needed for penetration testing
installed bydefault. In addition, Kali's community is very effective and helpful. With Kali
Linux, aRaspberryPi devicecanbecome atoolsetfor penetration inside one'spocket.
Domoticz
Domoticz is a free and open-source home automation system that allows users to design
andmonitorvariousdeviceslikeswitches,sensors,andmetersfortemperature,power,etc.Domoticz
's main user interface is an expandable and scalable HTML5 frontend. Some of
itsoutstanding features are its interactiveness with any browser, extensive logging, support
forexternaldevices, andauto-learning for sensors andswitches.
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 serveroperating systems. OpenSUSE operating system for Raspberry Pi is a part of the
openSUSEproject. The initiative's primary goal is to educate people about Linux. The
openSUSE OS isdeveloped,distributed, and maintained by an open-sourcecommunity.
RetroPie
RetroPie is an emulator which can be used to play some low-end games on one's
RaspberryPi. It is a Debian-based open-source software library. It is elementary to set up and
has broadcommunity support. RetroPie uses the Emulation Station frontend RetroArch etc.,
whichmakes it possible to play old-school console games, nostalgic arcade games, and
classic pcgames. 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.RetroPieis apopular emulationplatform forplaying retrogames on
theRaspberryPi.
ArchLinuxARM
Arch Linux ARM is an easy-to-operate and lightweight Linux distribution, which is
theofficial port of the ArchLinux OS. ArchLinuxARM maintains the initial philosophy
ofArch developers, which is emphasizing simplicity, ownership, and use. It is built
explicitlyfortheprocessorswhichsupportARMarchitecture.Usingthis,theuserswillhavecomplet
e
211|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
control of the system and can modify and customize it as per their needs. It could be an
idealchoicefor low-powered systems like Raspberry Pi.
UbuntuCore
Ubuntu core is essentially designed to meet the needs of IoT devices. It is a minimal
versionof Ubuntu which requires less storage and memory to function. As Ubuntu is one of
the mostpopular Linux distributions, hence its community has plenty of support and
resources forusers who are interested in ubuntu core. It is simple to set up and can be
installed using theubuntusnappy coreinstaller.
Batocera.Linux
Batocera is a widespread open-source Linux distribution built primarily for retro
gaming.Whileitcouldrunonsomestandardcomputersystems,butisdesignedexplicitlyformicroco
mputerslikeRaspberryPi.PeoplewhowanttotransformtheirRaspberryPicomputerinto agaming
consolearerecommendedto download Batocera.Linux
BMC64
BMC64 isafreeandopen-sourcesystemthatisabaremetalversionof
VICE'sC64emulator.BMC64provestobeanappropriateoperatingsystemfordeviceslikeRaspberr
yPi. The reasons are it has the GIPO pins to connect simple keyboards and joysticks, it
offersPCB scanning, real 50Hz/60Hz scrolling, low audio and video latency, an optimal
startuptime,etc., helpful features.
Notes:-
RaspberryPiisalow-cost,economicalpocket-sizedcomputer,thesizeofanATMCard.
Itwasdevelopedby
RaspberryPiFoundationin2012withtheaimofprovidingpeopleeasyaccess to computing
andcomputer education.
Duetoitssmallformfactor,itisboundedbycertainhardwarelimitations,andhencerunningre
gularoperatingsystems on itwill becomparativelyeffortful.
Therefore,specificoperatingsystemsweredesignedtopowerdeviceslikeRaspberryPi.
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
OperatingSystem), RISC OS (a completely different OS model, which is neither
Linux norwindows),etc.
RaspberryPidevicesaremainlyusedasportablecomputersusedforbuildinghardwareproje
cts,IoT applications, homeautomation, etc.
Alongwithallthese,wecanalsouseaRaspberryPitoplaygames,listentomusic,doregularpr
ogramming,etc.
Raspberry Pi could be a great tool if one wants the power of an on-the-go
computeralongwith the advantageof great portability.
212|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
4.9. Raspberry-PiArchitecture
WhatisaRaspberryPi? Raspberrypiisthenameofthe“creditcard-sizedcomputer board”
developed by the Raspberry pi foundation, based in the U.K. It gets pluggedin a TV or
monitor and provides a fully functional computer capability. It isaimed atimparting
knowledge about computing to even younger students at the cheapest
possibleprice.Althoughitisaimedatteachingcomputingtokids,butcanbeusedbyeveryonewilling
to learn programming, the basics of computing, and building different projects byutilizingits
versatility.
RaspberryPiisdevelopedbyRaspberryPiFoundationintheUnitedKingdom.TheRaspberryPi is
aseries ofpowerful, small single-boardcomputers.
Raspberry Pi islaunched in 2012 and there have been several iterations and
variationsreleasedsincethen.
Various versions of Raspberry Pi have been out till date. All versions consist of a
Broadcomsystem on a chip (SoC) with an integrated ARM-compatible CPU and on-chip
graphicsprocessingunit(GPU).
The original device had a single-core Processor speed of device ranges from 700 MHz to
1.2GHzandamemory rangefrom 256MB to 1 GB RAM.
To store the operating system and program memory Secure Digital (SD) cards are
used.RaspbianOSwhichisa LinuxoperatingsystemisrecommendedOSbyRaspberry
PiFoundation. Some other third party operating systems like RISC OS Pi. Diet Pi, Kali,
Linuxcanalso berun on RaspberryPi.
Used:
Italsoprovidesasetofgeneralpurposeinput/outputpinsallowingyoutocontrolelectroniccomponen
tsforphysicalcomputingand explorethe Internet ofThings (IOT).
RaspberrypiDiagram:
213|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
RaspberryPimodel –
There have been many generations of raspberry Pi from Pi 1 to Pi 4. There is generally
amodel A and model B. Model A is a less expensive variant and it trends to have
reducedRAMand dual cores such as USBand Ethernet.
ListofRaspberrypimodelsandreleasesyear:
1. pi1 model B– 2012
2. pi1 model A –2013
3. pi1 modelB+-2014
4. pi1 model A+– 2014
5. Pi 2Model B– 2015
6. Pi 3 Model B-2016
7. Pi3 Model B+-2018
8. Pi3 Model A+-2019
9. Pi4 Model A – 2019
10. Pi Model B –
202011. Pi 400 –2021
214|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Specs of the Computer: – The computer hasa quad-core ARM processor that doesn’tsupport
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.5mmaudio/video
port, and a Bluetooth connection. It has got a series of input and output pins
thatareusedformaking projects like– homesecurity cameras, EncryptedDoor lock, etc.
BuildPhysicalProjectsWithPythonontheRaspberryPi
The Raspberry Pi is one of the leading physical computing boards on the market.
Fromhobbyists building DIY projects to students learning to program for the first time,
people usethe Raspberry Pi every day to interact with the world around them. Python comes
built in onthe Raspberry Pi, so you can take your skills and start building your own
Raspberry Piprojectstoday.
GettingtoKnowtheRaspberryPi
The Raspberry Pi is a single-board computer developed by the Raspberry Pi Foundation,
aUK-basedcharityorganization.Originallydesignedtoprovideyoungpeoplewithan
215|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
affordablecomputingoptiontolearnhowtoprogram,ithasdevelopedamassivefollowingin the
maker and DIY communities because of its compact size, full Linux environment,
andgeneral-purposeinput–output (GPIO) pins.
Withallthefeaturesandcapabilitiesthatarepackedintothissmallboard,there’snoshortageof
projects anduse casesforthe Raspberry Pi.
If you can think of a project that would benefit from having a credit card–sized
computerattached to it, then someone has probably used a Raspberry Pi to do it. The
Raspberry Pi is afantasticway to bring your Python projectideas to life.
RaspberryPiBoardOverview
Below is the board layout of the Raspberry Pi 4. While this layout is slightly different
fromprevious models of the Raspberry Pi, most of the connections are the same. The
setupdescribed in the next section should be the same for both a Raspberry Pi 3 and a
Raspberry Pi4:
216|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
People often wonder what the difference is between a Raspberry Pi and an Arduino.
TheArduino is another device that is widely used in physical computing. While there is
someoverlap in the capabilities of the Arduino and the Raspberry Pi, there are some
distinctdifferences.
For running Python, the Raspberry Pi is often the better choice, as you get a full-
fledgedPythoninstallation out ofthe box without any configuration.
4.10. RaspberryPiProgramming
"Helloworld"isthebeginningofeverythingwhenitcomestocomputingandprogramming.
It's the first thing you learn in a new programming language, and it's the
wayyoutestsomethingout or checktosee ifsomething'sworkingbecause
it'susuallythesimplestway of testing simplefunctionality.
217|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Warriorsofprogramminglanguagewarsoftencitetheirownlanguage's"helloworld"againstthatofa
nother,sayingtheirsis shorter or moreconcise or moreexplicit orsomething. Having a nice
simple readable "hello world" program makes for a good intro forbeginnerslearning
yourlanguage, library, framework, or tool.
I thought it would be cool to create a list of as many different "hello world" programs
aspossible that can be run on the Raspberry Pi using its Raspbian operating system, but
withoutinstalling any additional software than what comes bundled when you download it
from theRaspberry Pi website. I've created a GitHub repository of these programs, and I've
explained10ofthem for you here.
1.Scratch
2. ClickLooks.
2.Python
Python is a powerful and professional language that's also great for beginners— and it's
lotsof fun to learn. Because one of Python's main objectives was to be readable and stick
tosimpleEnglish, its "helloworld" program is assimpleas possible.
218|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
1. OpenThonnyPythonIDEfromthemainmenu.
2. Enterthefollowingcode:
print("Helloworld")
3. Savethefileashello3.py.
4. Clickthe Runbutton.
opensource.com
3.Ruby/Sonic Pi
Rubyisanotherpowerfullanguagethat'sfriendlyforbeginners.SonicPi,thelivecodingmusicsynth,
is built ontopofRuby, so what usersactuallytypeis a formofRuby.
puts"Helloworld"
3. PressRun.
219|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Alternatively,tousingtheSonicPiapplicationforthisexample,youcanwriteRubycodeinatext
editor and run it inthe terminal:
puts"Helloworld"
3. Savethefileashello.rbin thehomedirectory.
4. OpenTerminalfromthemainmenu.
5. Runthefollowingcommand:
rubyhello.rb
4.JavaScript
ThisisabitofacheatasIjustmakeuseofclient-sideJavaScript withinthewebbrowserusingthe
WebInspectorconsole, but itstill counts!
1. OpenChromium WebBrowserfromthemainmenu.
2. Right-clicktheemptywebpageandselectInspectfromthecontextmenu.
3. Clickthe Consoletab.
4. Enterthefollowingcode:
console.log("Helloworld")
5. PressEntertorun.
220|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
You can also install NodeJS on the Raspberry Pi, and write server-side JavaScript, but
that'snotavailable in the standard Raspbian image.
5.Bash
echo"Helloworld"
3. Savethefileashello.sh in thehomedirectory.
4. OpenTerminal from themainmenu.
5. Run the following
command:6.
ashhello.sh
Note you'd usually see a "hashbang" at the top of the script (#!/bin/bash), but because
I'mcalling this script directly using the bash command, it's not necessary (and I'm trying to
keepalltheseexamplesas short as possible).
You'dalsousuallymakethefileexecutablewithchmod+x,butagain,thisisnotnecessaryasI'm
executing withbash.
6. Java
221|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
3.publicclassHello{
4.publicstaticvoidmain(String[]args){
5. System.out.println("Helloworld");
6. }
7. }
8.
9. Savethe fileas Hello.javain thehome directory.
10. OpenTerminal from themainmenu.
11. Runthefollowingcommands:
12. javacHello.java
javaHello
I could almost remember the "hello world" for Java off the top of my head, but not quite.
Ialwaysforget wheretheString[]argsbit goes, butit's obvious whenyou think aboutit...
7.C
222|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
4. intmain() {
5. printf("Helloworld\n");
6. Savethefileashello.cin thehomedirectory.
7. OpenTerminal from themainmenu.
8. Runthefollowingcommands:
./hello
Notethatinthepreviousexamples,onlyonecommandwasrequiredtorunthecode(e.g., python3
hello.py or ruby hello.rb) because these languages are interpreted rather thancompiled.
(Actually Python is compiled at runtime but that's a minor detail.) C code iscompiledinto
bytecodeand the bytecodeis executed.
8. C++
C's younger bother, C++ (that's C incremented by one...) is another fundamental low-
levellanguage, with more advanced language features included, such as classes. It's popular
in arange of uses, including game development, and chunks of your operating system will
bewrittenin C++too.
223|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
using namespace
std;intmain() {
cout<<"Hello world\n";
}
Runthefollowingcommands:
1.g++-ohellopp hello.cpp
./hellocpp
ReadersfamiliarwithC/C++willnoticeIhavenotincludedthemainfunctionreturnvaluesinmyexa
mples. Thisisintentional asto removeboilerplate,which isnot strictlynecessary.
9. Perl
Perlgetsalotofstickforbeinghardtoread,butnothingmuchgetsinthewayofunderstandingits "hello
world" program. So far, so good!
print"Helloworld\n"
3. Savethefileashello.pl in thehomedirectory.
4. OpenTerminal from themainmenu.
5. Runthefollowingcommand:
perlhello.pl
224|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Again, I learned Perl at university, but unlike Java, I have managed to successfully
avoidusing it.
So that's nine different programming languages covered, but let's finish with a bit
morePython. The popular computer game Minecraft is available for Raspberry Pi, and
comesbundled with Raspbian. A Python library allows you to communicate with your
Minecraftworld, so open Minecraft and a Python editor side-by-side for some fun hacking
your virtualworldwith code.
1. OpenMinecraftPifrom themainmenu.
2. CreateandenteraMinecraftworld.
3. PressTab toreleaseyour focusfromtheMinecraftwindow.
4. OpenThonnyPythonIDEfromthemainmenu.
5. Enterthefollowingcode:
6.frommcpi.minecraftimportMinecraft
7.
8.mc =Minecraft.create()
9.
mc.postToChat("Helloworld")
10. Savethefileashellomc.py.
11. Clickthe Runbutton.
225|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Finally,let'slookattheSenseHATEmulator.ThistoolprovidesagraphicalrepresentationoftheSens
eHAT.
The sense_emu Python library is identical to the sense_hat library except that its
commandsget executed in the emulator rather than on a physical piece of hardware. Because
the SenseHAT includes an 8x8 LED display, we can use its show_message function to write
"helloworld".
3.
4.sense = SenseHat()
5.
sense.show_message("Helloworld")
6. Savethefileassense.py.
7. Clickthe Runbutton.
226|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Example:
PiCameraModuleInterface withRaspberryPiusingPython
PiCameraModule(v1.3)
ThepiCameramoduleisacamerathatcanbeusedtotakepicturesandhighdefinitionvideo.
RaspberryPiBoardhasCSI(CameraSerialInterface)interfacetowhichwecanattachthePiCamera
moduledirectly.
ThisPiCameramodulecanattachtotheRaspberryPi’sCSIportusinga15-pinribboncable.
FeaturesofPiCamera
Here, wehaveusedPicamerav1.3. Itsfeaturesarelistedbelow,
Resolution – 5 MP
227|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
HowtoattachPiCameratoRaspberryPi?
ConnectPi Camerato theCSIinterfaceof theRaspberry Piboard asshown below,
228|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
HowtoEnableCamerafunctionalityonRaspberryPi
ForenablingthecamerainRaspberryPi,opentheraspberrypiconfigurationusingthefollowingcom
mand,
sudoraspi-config
then select Interfacing options in which select the camera option to enable its
functionality.rebootRaspberry Pi.
Nowwecan accessthe cameraon RaspberryPi.
Nowwecancaptureimages andvideos usingPi CameraonRaspberry Pi.
Example
Captureimagesandsave it tothespecifieddirectory.
We can capture images using Python. Here, we will write a Python program to
captureimagesusing Pi Cameraon Raspberry Pi.
Here,wehaveused picamera package(library)whichprovidesdifferentclassesforRaspberry Pi.
Out of which we are mainly interested in PiCamera class which is for cameramodule.
PiCamera PythonProgramforImageCapture
Camera
importpicamera
fromtimeimportsleep
#create object for PiCamera
classcamera =
picamera.PiCamera()#setresoluti
on
camera.resolution=(1024,768)
camera.brightness =
60camera.start_previe
w()#addtext on image
camera.annotate_text = 'Hi Pi
User'sleep(5)
#store
imagecamera.capture('image1
.jpeg')
229|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
camera.stop_preview()
FunctionsUsed
To use picamera python based library we have to include it in our program as given
belowimportpicamera
ThispicameralibraryhasPiCameraclassforthecameramodule.So,wehavetocreateanobjectforPi
Cameraclass.
PiCameraClass
TousePiCamerainPythononRaspberryPi,wecanusePiCameraclasswhichhasdifferentAPIsfor
camerafunctionality. Weneedtocreate objectforPiCameraclass.
E.g.
Camera=picamera.PiCamera()
The above PiCamera class has different member variables and functions which we can
accessbysimply inserting adot(.)in between object nameand membername.
E.g.
Camera.resolution=(1080,648)
capture()
It is used to capture images using Pi
Camera.E.g.
Camera.capture(“/home/pi/image.jpeg”)
Thecapture() functionhasdifferentparameterswhichwecanpassfordifferentoperationslikeresize,
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
willdisplay.Theresolutioncanbespecifiedas (width, height) tuple, as a stringformatted
WIDTHxHEIGHT,orasastringcontainingcommonlyrecognizeddisplayresolutionnamese.g.
“HD”, “VGA”, “1080p”,etc.
E.g.
Camera.resolution=(720,480)
Camera.resolution=“720x480”
230|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Camera.resolution =
“720p”Camera.resolution =
“HD”Annotate_text=“Tex
t”
It is used to add text on images, videos,
etc.E.g.
Camera.annotate_text=“HiPiUser”
start_preview()
It displays the preview overlay of the default or specified
resolution.E.g.
Camera.start_preview()
stop_preview()
It is used to close the preview
overlay.E.g.
Camera.stop_preview()
Note:TherearevariousAPIsofPiCameraclass.So,toknowmoreAPIindetailyoucanrefer
PiCameraAPIs.
PiCameraPythonProgram forVideoRecording
importpicamera
fromtimeimportsleepcamera =
picamera.PiCamera()camera.re
solution = (640, 480)print()
#start recording using pi
cameracamera.start_recording("/home/pi/demo
.h264")#wait for video to
recordcamera.wait_recording(20)
#stop
recordingcamera.stop_r
ecording()
231|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
camera.close()
print("videorecordingstopped")
Functionsused
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’)
Itrecordsvideonameddemoofh264format.
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()
PlayRecordedVideo
Toopenavideo,wecanuseomxplayerbyusingthefollowingcommand,omxplayerv
ideo_name
4.11. InterfaceaRaspberryPiwithanArduino
232|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Interface a Raspberry Pi with an Arduino so the two boards can communicate with
oneanother.
Sometimes you may need to connect an Arduino to a Raspberry Pi. For example, if you
havesensors, motors, and actuators, you can connect these to the Arduino and make the
Arduinosend values to and from the Raspberry Pi. This way, we can separate the computing
intensivetasks(doneby the Raspberry Pi) and controlling tasks (doneby the Arduino).
we will connect an Arduino to a Raspberry Pi and have the Arduino send “Hello
fromArduino” to the Raspberry Pi, and the Raspberry Pi will blink an LED upon receiving
thecommandfrom theArduino.
233|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Writethefollowingcodeinthenewwindowandsaveit.(Savetoyourdesktopsoyoudon'tlose it.)
importserial
import RPi.GPIO as
GPIOimport time
GPIO.output(pin,GPIO.HIGH)time.sleep
(1)GPIO.output(pin,GPIO.LOW)time.sle
ep(1)
return
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.OUT)
whileTrue:
read_ser=ser.readline()
print(read_ser)
if(read_ser=="HelloFromArduino!"):
blink(11)
Now open Arduino IDE and upload the following code to your
Arduino.Stringdata="Hello FromArduino!";
voidsetup()
{
234|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
InyourRaspberryPiinterface,besuretoenableSerialand I2CinPiConfig.
235|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Next,you'llneedtorestartyourRaspberryPi.OpentheTerminalandexecutethesecommands:
Thenfindalinewith/dev/ttyACM0orsomethinglike/dev/ttyACM1etc.(checkforanACM with
any number0,1,2 etc.)
236|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
4.12. RaspberryPiGPIOAccess
GPIO (General Purpose Input Output) pins can be used as input or output and
allowsraspberrypi to connect with general purpose I/Odevices.
RaspberryPi3ModelBGPIOPinMapping
237|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
We should define GPIO pin which we want to use as an output or input. But Raspberry
Pihastwo ways of defining pin numberwhich areasfollows:
GPIONumbering
PhysicalNumbering
ControlLEDusingRaspberryPi InterfacingDiagram
Example
Now, let’s control LED using a switch connected to the Raspberry Pi. Here, we are
usingPythonand C (WiringPi) for LEDON-OFF control.
ControlLEDusingPython
Now, let’s turn an ON and OFF LED using Python on Raspberry Pi. The switch is used
tocontroltheLEDON-OFF.
238|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
239|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
GPIO.setmode(GPIO.BOARD)GPIO.setup(4
0,GPIO.OUT)
GPIO.setup(channel,direction,initialvalue,pullup/pull down)
This function is used to set the direction of GPIO pin as an
input/output.channel–
GPIOpinnumberaspernumberingsystem.direction – set direction
of GPIO pin as either Input or Output.initial value– can provide
initial value
pull up/pull down – enable pull up or pull down if
requiredFew examples aregivenas follows,
GPIOasOutput
GPIO.setup(channel,GPIO.OUT)
GPIOas Input
GPIO.setup(channel,GPIO.IN)
GPIO asOutputwithinitialvalue
GPIO.setup(channel,GPIO.OUT,initial=GPIO.HIGH)
GPIOasInputwithPullupresistor
GPIO.input(channel)
This function is used to read the value of GPIO
pin.e.g.
GPIO.input(9)
240|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
ControlLEDusingC(WiringPi)
We can access Raspberry Pi GPIO using C. Here, we are using WiringPi library
foraccessingRaspberry PiGPIO using C.
Before implementing LED blinking using wiringPi, you can refer How to use
WiringPilibrary.
C(WiringPi)Program forRaspberryPitocontrolLEDusingPushButton
#include
<wiringPi.h>#include
<stdio.h>
intLED=26;/*GPIO26asperwiringPi, GPIO12 asper BCM,pin no.32*/
int switch_input = 21;/* GPIO21 as per WiringPi, GPIO5 as per BCM, pin no.29 */int
main(){
wiringPiSetup(); /* initialize wiringPi setup
*/pinMode(LED,OUTPUT);/* set GPIO as output
*/pullUpDnControl(switch_input,PUD_UP);
while(1){
if(digitalRead(switch_input))
digitalWrite(LED,LOW);/*writeLOWonGPIO */
else
digitalWrite(LED,HIGH);/*writeHIGHonGPIO */
}
}
It’s these pins that hold the true power of the Pi. They can control homes, machines,
newinventions,and evenrobots, sowhyis itsomanypeople don’t knowwhat theyreally are?
241|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
GPIO stands for ‘General Purpose Input/Output’, and it’s these pins that let the Raspberry
Pido its magic. This is because the pins have no specific function, and can be set to a
dedicatedpurpose,such ascontrolling a signal.
A GPIO pin set to output can provide either 3.3 volts, known as a HIGH signal, or 0
volts,knownas aLOWsignal.When set toinput, it canreadthesesame voltages.
GPIOPinsDon’tProvideMuchPower
It’s important to remember that GPIO pins (and the 3.3-volt power pins) are meant to
controlandcommunicate with other components.
You can get about 51mA from all 3.3 volt pins combined, but you’ll want to take care
whenconnecting; if your circuit tries to pull too much current through these 3.3 volt pins, you
canfrythe whole board.
The 5-volt power pins, on the other hand, give you all the power available from the
powersupply,minus thebit used by the Raspberry Pi itself.
When you first start using these GPIO pins, it’s wise to use a breadboard. This makes it
easytobuild circuits without solderand to modify them.
Ifyou’veneverusedabreadboardbefore,familiarizeyourselfwiththebasicshere:
A GPIO extension board also helps immensely. This connects the GPIO header via a
ribbonandplaces the pins directly on thebreadboard, ina clearly labeled manner.
242|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
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
spaceforbeginnerprojects.
Every GPIO pin can be set to send and receive HIGH and LOW signals. Some have
specialuses too.
HardwarePWM
GPIO pins output either 3.3 or 0 volts: a HIGH or LOW signal. Pulse width modulation,
orPWM,isawayofsimulatingtherangeofvoltagesinbetweenbyflickeringthepinonandoffrapidly.
You can also use a low pass filter to smooth a PWM into an analog signal. This can be
usedforanalogueaudio, ifyou aren’t fussyabout quality. It’sfinefor adoorbellor toy.
You can generate a PWM signal from any GPIO pin using software, but the operating
systemjugglesthis with other tasks, so this signalcan jitter.
Hardware PWM is available on GPIO pins 18 and 19. Hardware PWM and the
headphonejackusethe samecircuits,soshouldn’t beusedsimultaneously.
If you take a look below at the diagram (known as a Raspberry Pi ‘Pinout’) you’ll see
thatsome pins are I2C, SPI, and UART serial. These are serial bus protocols that can be used
tosendand receive data from other components.
243|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
4.13.4. PullUpandPullDownResistors
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 readHIGH,or to ground to read LOW.
The problem is that when this circuit is open and nothing else is attached to the pin, it
mightreturnany value.This isknownas“floating,”andit’s extremely unhelpful.
Youcanpreventfloating with“pullup”or“pulldown”resistors.
A pull up resistor is wired to your control voltage; when nothing else is attached, the pin
willread HIGH. A pull down resistor is wired to ground; the pin will read LOW. Use
whicheverprovidesthe oppositevalueto your switch orbutton.
You don’t need to wire these resistors into your circuit. They’re inside the Raspberry
Pialreadyand you cancontrol them from software.
Among the easiest ways to control GPIO pins is by using the GPIO Zero library in Python.
Ifyou’vewritten any Python before, you’llpick thisup easy.
244|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
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
WithPython’is excellent andcosts nothing.
GPIO Zero is installed by default on Raspbian Desktop images. If you are using
RaspbianLiteoradifferent operating system, you may needto install it.
Let’shaveagoatturningonanLED!Ajobthissimpledoesn’treallyrequireacomputer,butwe’ll
involve theRaspberry Pi in the GPIOpins.
Forthis,you’llneed….
ARaspberry Pi
withpowersupplyandan
SDcard with
Raspbian installed
Abreadboard
AGPIO
extension
board (optional,
butrecom
mended)
245|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
AnLED
You’llalsoneedsomemoregeneralequipment,suchas;
Connectingand TestingtheButton
Now add your button to the middle of the breadboard. Connect one pin of the button to
aRaspberryPi GPIOpin.I’m using13, becauseit’s my lucky number.
Then, connect the diagonally opposite pin of the button to the negative power rail. When
youpushthis button down, thecircuit closes.
Finally, we need to tell the Pi to pay attention to this pin, so let’s open the Python
interpreter.Atthe command prompt, type:
python3
Nowattheinterpreter,type:
fromgpiozeroimportButton
If you get a message saying ‘ImportError’, make sure you capitalized it correctly. If it
says‘ModuleNotFoundError’, you need to install GPIO Zero. Otherwise, it’s time to assign
ourpin to the button:
button=Button(13)
This Button class takes care of assigning the pull up resistor. Now let’s test that it works
bytypingthe following lines:
whileTrue:
ifbutton.is_pressed:
246|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Pythonisfussyaboutindentation,sobesuretocopythespacestoo.ThenpressEnteragainto run
theloop.
This loop will run until someone presses the button, so press it. It should produce a
messagesaying the button works. This means you’ve successfully built a simple circuit that
sends amessage to your Raspberry Pi. If this doesn’t work, check that everything is
connectedproperlyand tryagain.
4.13.6. ConnectingandTestingtheLED
The D in LED stands for “diode”, which means electricity only runs in one direction
throughit.
You will notice that one leg of the LED is slightly longer: this connects to positive. Here,
thatmeansconnectingtotheGPIOpin.I’musingpin 26, for no particular
reason.PlacetheLEDinthebreadboard,makingsurethatthelegsarespacedhorizontallysothatyouar
en’tshortingtheconnectionout.NowconnectthispositivelegtoyourGPIOpin.An LED should be
wired in series with a resistor, so attach one end of your resistor to theshort leg of the LED,
and the other end to the negative power rail. Resistors can go in eitherwayaround.
Now let’s go tell the Raspberry Pi what’s going on. Type: Image: Pi &
Breadboardfromgpiozeroimport LED
led=LED(26)
Ifeverything’swiredcorrectly,youcanswitchitonandoffwiththese commands:
led.on()
led.off()
ControllingtheLEDWith theButton
Nowthateverything’sconnectedandyou’vecheckedtheywork, type:
button.when_pressed =led.on
Nowpress thebutton.TheLEDshouldswitch onandstay on. Nowtype:
247|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
button.when_released=led.off
Pressthebuttonagain;the LEDshouldswitchoffwhen thebuttonisreleased.
4.14. ConnectingIOTdevicestothecloud
With the developmentof smart things, sensors and telecommunication, IoT (Internet
ofThings) technology has greatly developed and become more and more standardized.
Butfragmenteddevice-
sidecommunicationconnectionproblemsoftenimpedetheprojectimplementationprocess.
Directlyintegrate IoTSDK(SoftwareDevelopmentKit)forresource-richdevices
Relyonacommunicationmoduleforresource-constrained devices
Usealocalgatewayfornon-networkdevices
Use a cloud gateway for private-protocol devices with network
IoT Device SDK is used to help us quickly connecthardware devices to the IoT platform.We
can download theIoT Device SDK from the corresponding cloud platform, e.g. AWSIoT
DeviceSDK.
248|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
1. TheHAL(hardwareabstractionlayer)abstractsthesupportfunctioninterfaceofdifferentOS
(operating systems) to the SDK. This enables the SDK to be ported to different
hardwareenvironments,differentOS, and even bare chip environments.
3. Interface layer, providing API and callback function definitions, isolating the core layer
andtheapplication.
When developing applications on a device, we can always choose higher-level SDKs such
asAndroid IoT SDK on an Android device. That’s because the hardware environment
portingworkhas already been doneby the SDK itself.
However, when developing applications for an MCU (Micro Controller Unit) which
hasLinuxorRTOS(RealTimeOperatingSystem),weshouldchooseEmbeddedCSDKandportthe
codeto a specifichardware environment.
DirectlyintegrateIoTSDKforresource-richdevices
With the development of high-performance hardware, many smart devices have complete
OSsuchas Linux, Android etc. Thesedevices also haveaWi-Fiorcellularnetwork.
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 andthecommunication link with thecloud will have beenestablished.
249|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Examplesofsmartdevicesincludesmartphones,tablets,smartwearables,smartPOS,computers,in
dustrialgateways anddevelopmentboardslike theRaspberry Piand ESP32.
Relyonacommunicationmoduleforresource-constraineddevices
In the IoT scenario, a large number of devices are resource-constrained, with RTOS, or
evenwithout an operating system, using MCU + communication modules to establish their
link tothecloud.
There are many suppliers of cellular modules (NB-IoT/2G/3G/4G) on the market. The
ATcommands of each company are different, which makes developing device-side
applicationsverydifficult.
When we need to connect MCU to an IoT Platform, we should always carefully select
thecellularmodules andcheck whetherthey aresuitable foraspecificIoT platform.
DifferencebetweenDTUandindustrialgateway:
DTU is a wireless terminal device used to convert serial data into IP data or IP
datainto serial data and transmit it through a wireless communication network. It has fast
andflexiblenetworking, a short construction period andlow cost.
The industrial gateway has the functions of collecting data from field devices
throughserialportornetworkport.Datacollection,protocolanalysis,datastandardizationanduploa
ding 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 tomaintain.
250|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
Useacloudgatewayfor private-protocoldeviceswithnetworkcapabilities
Devicesthatdirectlyconnecttothecloudgateway
For some devices, they already have the ability to connect to the internet, but the
protocolsvary according to device manufacturers. We don’t want the IoT platform layer to
handle
theparsingoftheseprotocolsdirectly;anintermediatelayershouldsatisfytheprotocolconversionwo
rk to make the data meet theunifiedformat ofthe IoT platform.
Examples of devices that connect to the internet through private protocol include
vehicleGPS.
Devicesthatconnectto thecloudgatewayindirectly
Using a mature system will bring us higher development efficiency, but it’ll also
introduceanothermidware, whichwill increasecommunication time.
Examplesofdeviceswithmaturesystemsincludecameras/NVRsystems.
251|Page
l O M oA R cP S D | 2 6 8 8 5 7 6 3
252|Page