Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
32 views23 pages

ES&IoT - Unit 2

Uploaded by

Stephy Bless
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views23 pages

ES&IoT - Unit 2

Uploaded by

Stephy Bless
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT II

EMBEDDED C PROGRAMMING 2.1 - 2.39

2.1. Memory andI/O Device Interfacing.. ...2.1

2.1.1. Memory Interfacing ....2.1

2.1.2. Input and output device interfacing .2.5


2.2. Programming Embedded System in C. ..2.16
2.2.1. Memory constitution, constants, variables and Data types..... ...2.16
2.2.2. Static, Extern, Register and Auto Storage Classes .....2.18
2.2.3. Array structures and union... 2.19

2.2.4. Loops and Decisions. .2.21

2.2.5. Functions and Library Functions .2.23


2.3. RTOS -Real time Operating System... ..)2,25

2.3.1. Types of RTOS 2.26


2.3.2. Functionsof RTOS ...2.26
2.3.3. Applications of RTOS... ..2.27
2.4. Multiple tasks and Processes. .. 2.27

2.5. Context Switching ... 2.30

2.5.1. Process Control Block (PCB) ....2.30

2.5.2. Preemption.. ..2.31


Contents C.3

2.5.3. Context Switching. 2.31


2.6. Priority Based Scheduling ... 2.31

Two MarksQuestions with Answers. 2.36

Review Questions... 2.39

UNIT III
IOT AND ARDUINOPROGRAMMING 3.1 -3.34

3.1. Introduction to Concepts of IoT Devices.... .....3.1


3.2. Definition and characteristics of IoT. 3.1

3.2.1. Definition. 3.1

3.2.2. Characteristics. ....3.2


3.2
3.2.3. Challenges of loT.
3.2.4. IoT Devices Versus Computers .....3.3
3.3
3.3. IoT Configurations.
3.3.1. Configuration versions... 3.3

3.3
3.3.2. MQTT Bridging.
3.3.3. HTTP Bridge... 3.5

3.3.4. COAP Bridge. 3.6


3.6
3.4. IoT components.
.3.8
3.5. Introduction to Arduino
3.8
3.6. Different types of Arduino Boards
3.10
3.6.1. Fastest ArduinoBoard
3.7. Arduino Toolchain 3.10

3.11
3.8. Arduino Programming structure....
3.8.1. Sketch.. ...3.11
The system contains orderA15) external
EMBEDDED
C
PROGRAMMING purpose.
memory.
(A8- 8051.
lower
contain RAM
from of
of reading givesaddress
memory
types memory. signal signal
which EPROM
Address It
twofor ROM/ Lines ROM/Program
order ALE
lines.
onlyEEPROM enable lines.
are volatile
UNIT
II Thereavailable -DO
D7 -A0
A7
A8
-A15 higher and
address A8).
address
INTERFACING a OE latch(A15-
output
is - and
and
EPROM,It programs.
microcontroller. interfacing and
is data. (RAM): cycle external
address
the
data
It LATCH data
(ROM):system T
multiplexed activate multiplexed
DEVICE
software
PROM, Memory memory initial usingorder
INTERFACING INTERFACING
permanent
2.1.1.
MEMORY
INTERFACING
of Memory in latched
higher
part are and ExternalA7) to
/O Access PO EA ALEP2 PSEN as
is providesROM/EPROM.
data bus. sed as
integraltypes
and
used used
AND Only (A0dataaddress
ROM
temporary P3 2.1. is RAM
EXTERNAL
(B)
Random
software P1 is address is
MEMORY an Readvarious Fig. 0 as 2 PSEN Port0
is EXTERNAL Port used bit Port
Memory 8
) (ii) & &
2.1. (A)
Anbedded Sstems and lor
22 EmbeddedC Programming 2.3
ALE signal from 80SI
decoded using externallateh and
Address lines are From address decoding we know that starting address of memory is 0000H and
(A7-A0) address lincs.
to provide lower onder ending address is 3FFFH.
Port 2 gives higher onder address lines. write PO.7 D7- DO
selects the read or operations
RD and WR Signals tom S051 PO.0 74LS373
respectively. A7 -A0 16 Kx 8
ALE RAM
DO- D7-data/lines
PO 8051 P2.0
A8 -A13
RAM P2.5
A0 -A7 P2.6
ALE
LATCH Address
Vss P2.7
Clock Lines
RD EA P3.6 WR
P2
WR WR OE PSEN P3.7 RD

Fig.2.3. Interfucing diagram for example 2.1


Fig. 2.2. E°ernal RAMData memory Interfacing
Example 2.1|Design a 8051 microcontroller system to interface the external Example 2.2 Design a microcontroller to interface the external ROM of size
RAM of size 16 KBx& 4 Kx8.
OSolution:
OSolution:
Memory size = 16 KB Given: 4K memory
The memory size is denoted in terms of 2n. 2n = 4 KB
2n = 16 KB n= 12; A0to A11 address lines required.
n ’ is the number of address lines
required Remaining port lines and PSEN are connected to CS and RD through OR
n=14 [A0 to A13 address line required].
gate.
P2.6 and P2.7 are connected through OR gate to CS pin of
external RAM. A12 - A15 =0, to select external ROM.
A14 and A15 equal to 0 to select external data
memory. Address decoding

Address A1S A14 A13 A12 All Al0 A9 A8 A7 A6 AS


Address A1S A14 A13 A12 AlI A10 A9 AS A7 A6 AS A4 A3 A2 Al A0 HEX
A4 A3 A2 Al address
Start 0 0 '0 0 0 0 0 0 0 0
End 0 1 1 1 Start 0 0 0 0 0 0 0 0000

End 0 0 1 1 1 1 OFFF
3 F
F
Embedded Systems and Io
Embedded CProgramming 2.5
2.4
Vss D7 - DO
For RAM selection
PO.0
EA
PO.7
PSEN is used as chip select pin
74LS373 AZ-A0 4 Kx8
ROM RD is P3.6 for Read control signal
ALE
G 0C
A0 -A11 WR is P3.7 for write control signal.
P2.0
8051 P2.5 WR Vss
P2.6 EA PO.0 D7 - DO D7 -DO
P2.7 Cs P0.7
PSEN
P3.6 RD |74LS373 A7-AO A7 -AO
P3.7 ALE 16 kx 8 32 k x 8
ROM RAM
P2.0 A8-A13 A8-A13
8051
Fig. 2.4. Interfacing diagram for example 2.2
P2.5

Example 2.3 Design a 8051 microcontroller to interface 16 K bytes of ROM


P2.6
CS TO d cs
P2.7
P2.7
and 32 K bytes of RAM. The starting address of ROMis 0000H and RAM is 8000H. P3.6 RD TO A14
PSEN P2.6
P3.7
OSolution: ROM: Memory size 16 K RD WR

2n = 16K

3n=14; A0 toAB address line required. Fig. 2.5. 1nterfacing diagram for example 2.3
A14, A15, PSEN are kept low when ROM is selected 2.1.2. INPUT AND OUTPUT DEVICE INTERFACING
RAM: Memory size 32 K (a) Keyboard Interfacing
2n = 32 K
Keys in a keyboard are arranged in a matrix of rows and columns. The controller
n=15; A0 to A15 address line required. access both rows and columns through ports using two ports, 8 x 8 and 4 x 4
A15 is kept high when RAM is selected (NOT Gate). keyboard can be connected to the controllers.
ROM Address decoding 4x 4 Keyboard
Address A15 A14 A13 A12 All A10 A9 A8 AT A6 AS A4 A3 A2 Al AO HEX As shown in figure, 4 x 4matrix keyboard connected to 2ports.
address
Start 0 0 0 0 0 0
0 0000
The rows are connected to output port (port l)
0 0 0
End 00 1
1
3FFF The columns are connected to input port (port 2)
RAM Address decoding
If no key has been pressed, reading the input port will yield 1's for all
Address Al5 A14 A13 A12 A1 A10 A9 AS
A7 A6 AS A4 A3 A2 A1 A0 HEX columns since they are connected to Vcc (high)
address Since all the rows are grounded, when a key is pressed, one of the columns
Start 0 0
0 0
0 0 0 0 0
8000 willhave 0(i.e.,) provides path to ground.
End 1 1 1
FFFF
1 1
Embedded. Systems and
2.4 EnbeddedC Programming 2.5

Vss D7 - DO For RAM selcction


PO.0
EA PSEN is used as chip select pin
P0.7
74LS373 A7-A0 4 Kx 8
ROM RD is P3.6for Read control signal
ALE
A0 -A11
P2.0 WR is P3.7 for write control signal.
8051 P2.5 WR
Vss
P2.6
P2.7 EA P0.0
PO.7
D7 -DO D7 -DO
PSEN
P3.6 RD 74LS373 A7-AO
A7 -A0
P3.7 32 k x 8
ALE G Oc 16 kx8
ROM RAM
P2.0 A8-A13 A8 -A13
Fig. 2.4. Interfacing diagram forexample 2.2
8051
P2.5

Example 2.3]Design a805l microcontroler to interface l6 Kbytes of ROM P2.6


P2.7 TO dcs
and 32 Kbytes of RAM. The starting address of ROMis 0000H and RAM is 8000H. P2.7
P3.6 RD TO A14
PSEN P2.6
OSolution: ROM: Memory size 16 K P3.7
RD WR
2n = 16K
n=14; A0 to AB address line required. Fig. 2.5. Interfacing diagram for example 2.3
$ A14, A15, PSEN are kept low when ROM is selected
2.1.2. INPUT AND OUTPUT DEVICE INTERFACING
RAM: Memory size 32 K
(a) Keyboard Interfacing
2n = 32K
n=15; A0 to A15 address line required. Keys in a keyboard are arranged in a matrix of rows and columns. The controller
3 A1S is kept high when RAM is access both rows and columns through ports using two ports, 8 x 8 and 4 x 4
selected (NOT Gate). keyboard can be connected to the controllers.
ROM Address decoding
Address A15 A14
4x4 Keyboard
A13 A12 Al1 A10 A9 A8 A7 A6 AS A4 A3 A2 HEX
Start
Al A0 As shown in figure, 4 x 4 matrix keyboard connected to 2 ports.
0 0 address
0
End 0 1
0 0
0 0 0
- 0000 The rows are connected to output port (port 1)
1
RAM Address decoding 3FFF
3 The columns are connected to input port (port 2)
Address A1s A14 AI3 A12 AII A10 A9 A8
If no key has been pressed, reading the input port will yield 1's for all
A7 A6 AS A4 A3
A2 A A0 HEX columns since they are connected to Vcc (high)
Start address
0
0
Since all the rows are grounded, when a key is pressed, one of the columns
End 0
0 8000 will have 0 (i.e.) provides path to ground.
1
FFFF
Embedded.Systems
and ot
2.6|
EmbcddedC Programming 2.7
keyboard
It is the function of
microcontroller toscanthe continuously t Start
pressed.
detect and identify the key
Vcc Ground all rows Ground next row
4,7k

4.7k
Read all columns
Do W Read all columns
y
D.
By W
No
Key
D2 press in
W Al this row?
D3 No
keys
Port 1 open? Yes
(Out)
2
|Dg D, D, Do Port
(In)
Yes
Find which key
is pressed

Fig. 2.6. 4 x4 Keyboard


Read all columns Get scan code
Key scan from table

To find the key pressed, the microcontroller continuously scans the keyboard by No Any Return
rows and columns separately. key down?>
Beginning with row 0', the microcontroller grounds it by providing a low to D
(portl) only. It then reads the columns (port 2). If the data read is all ls, then no key Yes

in that row is pressed. Now microcontroller makes next row 0°, and reads the Wait for debounce
columns and checks for any zero. This process continues until a row and column
with a zero is identified. After identification of a row in
which the key has beet Read all columns
pressed, the column to which the pressed key belongs is identified as
discussed
above by looking for a zero in the input values read. Al
Example No
keys
open?
(a) D3 - D0 - 1101 for the row, D3
- D0 - 1011 for the
1and column 3 are column indicate row Yes
selected. This indicates that key6 is
(6) D3 - D0 - 1011 for the row, D3 - pressed.
D0 -0111 for the indicate roW
selected. Then key Bis pressed. column,
2 and column 3 are
Fig, 2.7. flowchart for keyscan
Embedded Systemns and lo
|2.8
Embedded C Progran1ming 2.9
Program ANL A, #0000111|B
Keyboard Routine CJNE A, #00001111B, Row 2
pressed key to PO.l.
1nis program sends the ASCII code for MOV Pl, #11110111B
P1.0- P1.3 ’ connected to keypad rows MOV A, P2
P2.0 - P2.3 ’ connected to keypad column. ANL A, #00001111B
MOV P2, #0FFH ;Make P2an input port
CJNE A, #00001111B, Row 3
K1: MOV Pl, #0
:Ground all rows
LJMP K2
MOV A, P2 ; read all columns
Row 0: MOV DPTR, #KCODEO ; Set DPTR = start of row 0
ANL A, 00001111B :masked unused bits
SJMP FIND ; find columns, keys
CJNE A, #00001111B, Ki ; tillall keys release
K2: Row 1: MOV DPTR, # KCODE1 ; Set DPTR to start of row 1.
ACALL DELAY ; calldelay
MOV ;check if any key pressed SJMP FIND
A, P2
ANL A, 00001111B ; Mask unused bits Row 2: MOV DPTR, # KCODE2
CJNE A, #00001111B, OVER; ; Key pressed, find row SJMP FIND
SJMP K2 ;check till key pressed Row 3: MOV DPTR, #KCODE3
OVER: ACALL DELAY FIND: RRC
;call delay A ;see if any cy bit low.
MOV A, P2 ;check if any key pressed JNC MATCH ; if zero get ASCII code
ANL A, 00001111B ;Mask unused bits INC DPTR ; point to next column address
CJNE A, #00001111B, OVER1 ;key pressed, find row SJMP FIND ; keeps searching
SJMP K2 ; if none keep MATCH: CLR
OVERl:MOV P1, #11l11110B
pooling A ;clear if match found
; Ground row 0 MOVC ;get ASCII code
A, @A + DPTR
MOV A, P2 ; Read columns MOV P0, A ; display pressed key
ANL A, #00001111B ; Mask unused bit LJMP K1
CJNE A, #00001111B, Row 0 ; Key row 0, find
MOV P1, #11111101 B column ASCII Lookup table
ANL A, #00001111B
;Ground row 1 ORG 300H
CJNE A. #00001111B, Row_1 KCODE1: DB 0', 1',2", '3 Row 0
MOV P1, #11111011B
;Row 1 find column KCODE2: DB 'A, S', 6', 7 ; Row 1
MOV A, P2 :Ground row 2 KCODE3: DB '8, 9', A', B' ;Row 2
KCODE4: DB 'C', D', E,F ; Row 3
Enbedded Systems and Ior
2.10 EmbeddedC Programming 2.11|
with 8051
(b) LCD - Liquid Crystal | Display:Interfacing
graphics. LCD Commands
LCD can display numbers, characters and
LCD pin description The LOCD controller can accept several commands and modify the display
accordingly. These commands will make LCD as per the application.
Vss After writing to LCD, it takes some time for it to complete its internal operations.
LCD
VoD
VEE During this period, LCD will not accept any new commands
3
Vo
|6|6|7|8|9|1o/ 112|13|14 Code (HEX) Commands
RS RWE
DO - D7 1 Clear display screen
2 Return home
Fig. 2.8. LCD pin description
LCD has 14 pins which is used to interface with microcontroller. 4 Decrement cursor position
VSS, VDD provide +5V and Ground. VEE/vO is used for controlling LCD 6 Increment cursor position
contrast.
5 Shift display right
$ RS-Register select signal.
If RS = 0; Instruction command, register is selected, allowing the user to Shift display left
send a command such as clear display, cursor at home etc. If RS = 1, data 8 Display off cursor off
register is selected allowing the user to.send data to be displayed on the A Display off cursor ON
LCD.
RIW- Read or writeselect signal
C Display on cursor off
R/W allows the user to Read/write the information to the LCD. E Display on cursor blinking
E-nable pin 10 Shift cursor to left
It is used by the LCD to latch information
presented to its data pins. 14 Shift cursor to right
DBO - DB8: Bidirectional three state data bus lines Cursor to 1 line
80
It is used to send data or commands to LCD.
CO Cursor to 2d line
P10-P1.7 Do -D, Program to Display Character on LCD
P20 RS
To send any commands to LCD, make pin RS =0 and for data make RS = 1. Then
LCD VeE
P21 RW send a high to low pulse to the E pin to enable the internal latch of the LCD.
8051
P2.2 Vss ;P1.0 - P1.7 connected to LCD pins D0 - D7
;P2.0- connected to RS pin
Fig. 2.9. LCD
Interfacing
2.12
SETB WRT:
CLR SETB MOV DATA RET CLR SETB CLR CLRCMDWRT:
MOV SJMPLl:L1 CALL
A A MOV CALL CALL
A A MOVACALL MOVACALLACALL MØVACALLACALL MOV
CALL

P2.2 P2.1 P2.0 P1,A DELAY


P2.2 ; P2.1 ;
P2.2 P2.2 P2.1 P2.0 P1,A DATAWRTA,#'N' A,DELAY
#'0 A,#84HDELAY A,#OEHDELAY
CMDWRT CMDWRT #38H A.
DELA Y DATAVWRT
- -
connected
connected

R/W=0 ; ; ;
; ; RAW =0 ; ; ; subroutine
commd ; ;
: ; to to
subroutine
command
RS
0Copy / NDisplay 0'
=1
RS E=0 E=1
initialize
display Command
subroutine ER/W
pin
should should pin
subroutine on
datafor command
writefor for Acc. be cursor LCD
for pulse
highfor be
H displayed displayed 5
to contents on x7
L matrix
pulse
to
P1 Embedded

Systems

and
Ior

Interfacing commonly (c) Programming


Embedded C
LED L3: L2: DELAY: RET CLR
INTERFACING

delay
smallconnected is
A To LED's Diagram used
turn a
RET DJNZ DJNZ MOV MOV P2,2
are LED light
on LED
to
particularconnected emitting
are
WITH
ation common 8051 red
Fig.
2.11. and 8051 R3,L2 R4,L3
R4,#255R3,#50
to 2.10.
Fig. diode.
P0.7 P0.6 P0.5 P0.4 P0.3 P0.2 P0.1 P0.0 available
isLED,ground ports
uted LED
* These
connection. of 4 4 4 4 Symbol
LED
will interfacing in
8051,
to be many are
LED
i.e,
makewriten
diagran colours. the
that anode
to sermiconductor
LED
particular to
ports
light
isible.ports. and
cathodesare light

sources
2.13
tocether (d)sEVEN
SEGMENT
DISPLAY Program 2.14
In There L2: L1: L3: DELAY
common (i) ()
and END RET DJNZ DJNZ DJNZ MOV MOV MØV CALL CALL MØV CALL MOV START ORG
Common
cathode
Common (CC) are
common two
cathode
types
anode
anode of
has
Fig. (CA) LED
has all R0,L3 R2,LI R1,L2 R2,#0FFH
R1,#0FFH R0,#0FH STARTDELAYPO.#FFHDELAYP0,#00H 0000H
2.12. INTERFACING
8051
ofWITH
all the segment
the
cathodes
segment 7 a
anodes
display
pin of of
iagram the the
7 7
segments
segments
Embedded
connected
connected
Systems
together.
directly and
lor

Common
Program
Anode writtenProgramming
EmbeddedC
In
common
to
MOVDELAY: CALL CALL MOV CALL MOV CALL MOVSTART: MØV CALL MOV ORG make
LEDanode,
glow, 0
Fig. is
written
R0,#OFH STARTDELAY P0,#COH P0,#FFHDELAYP1,#01H 0000H 2.13.
P0,#A4HDELAY P0,#F9DELAY 8051
segment 7 to
make
P0.7 P0.6 P0.5 P0.4 P0.3 P0.2 P0.1 P0.0 P1.0 P1.1 P12 P1.3
display LED
Display2 I! Display 1I Il Il Il
Display0 make enable glow.
interfacing
part P1.0 In
0 common
as pin
dege
dcha output
A
4 cathode
port

(o3 D 1001 1
S
|2.15
Memory
types
constitution standard
Memory (0)2.2.1.library Why 22.
(ii) () () ANSI C
MEMORY
functions, instead FROGRANAING
idata data Code for C-codes SoftwareFacilitates Eas
RET
C
pvgrmming C Us
memory programming. of
6B memory American are functions relopment in
CONSTITUTION, data design ALP?
notrruability data
’ alignment
used
128 ’0 National from type ot of ENEEDDED
x is pogramlengthy
B Many and
independent dlarations
’O000 is the
ctly inappropriate feasible.
directly CONSTANTS,memory, Standard
compilers library and
to0x low
complex SYSTEM
dressableFFFF’ of ontrol
able size Institute
microcontroller
are conmpiler
VARIABLES of program
strueture. INC
64 ANSI
data
kB ANSIC is
types. C used. ìn
AND standard short
standard when
DATA time.
and inline
TYPES provide C99
isassembly
new latest

Boolean types
Data () (1)
use use Boolean A Constant
variable Varlables
of of () (iv) () (ii) () (i) () (vi)Const.
(")) (v)) () (i)
typedef
ifiers exclusive not
equivalence disjunction
Conjunction data LocalGlobal far xdata bdata
Pdata.
NOT (string) char or ’ ’ memory
’ type constant contalns
’ contains
’ Memory far memorymemory
define values valucs
SOme or (- ORsupports
EQV(-,
-cquivalence I) AND bits 64
(, 2.14.
DataFg. (8) byte canchangeable varlable fixed 64
datatype
egers +) (& changeable 64
-’ kR kl 18hits
the be value pagcd kB
) OR bits (32) loat
one Extended
nnemory
following Unsignedint value Extended
memory
have using ) Types
Data
bita(32)
of within external addressablebit hit -
the in
XOR, Clasifeation
ypes two addressable
no the Unaigned
double
bits (64)
short data
sign,prefix operations. one or data
NEQV type function more
bits (32) int
memory
typedet. permissible funetions
(^, bits (16)

Dits (64) long of


256
bila (16)short
by bytes,
a
compiler.
2.2.2. Example: Sfr Example: |2.18
0xB0sfrP30x90sfrP1
The
3 * *
STATIC, typesfr
auto Example:function. auto Example:Register Extern countsStatic segment bit SFR. Example: Sbit sfr
x FloatstatusFlags: bdata
dataCharx1 Char
data RegisterRegister ’ 16’
x ’ EXTERN, ’ defines
SFR idata
data count ’ are ’ defines Sbit SFR
default ’ It 'static 128
data data Itaccessible
is
variables sfrl6defines p,
count bits have
= defines a REGISTER 4
0x10C1B0: TCON= r7 global int a T2 16
storage =0xB0 in bit the registers.
counts' 8051. may 0xCC bit
a outside or bits,
byte.
variable AND flag not special
clasSs 0x10 which
All tdirects
he It
AUTO variable. be SFR is
for variables andfunction declared are
the
declared
local is STORAGE bit declared
initialized
compiler AI
inside
addressable.
variables, are block outside
bit
stored outside
in also CLASSES variables a
to function. Embedded
another assemble
from function a
It in It function a
is a defines
register. its are
used source Systems
address. such stored body.
inside a body.
module. bit
that and
in within
the the bit Iot

cach Struct Array Array, 2.2.3.context transferthe toThe memory, program allocates Programming Stack
EpbeddedC
structurc memory.
The It
String
Multidimensional
Hash Table array When The Stack The
ember has Multidimensional array(ii) ()There program C calling
structure struct, ARRAY switching compiler total
has 1 table - One clement. Listfunction.
other Pipe interrupt space the
and has
Two-dimensional are function
of a - union,STRUCTURES function.
The can
stack stack
memory
the variable3 a 2D dimensional two stores ’ provides
is
dimensional insertion is assigns counter.
ucture. used array types list, thoccurs,
at bememory space
an copies used
cqual to size with item stack, ease the a is
includes
table array of fixed for 256
join of array array ishandling ANDinterrupt the called the immediatcly
to arrays
characters key in donequeue, savíng bytes
or
together UNION
interrupt argument memory
or an functíon
grealer for pointer from pipe. functíon in
element of function 8051.
the data function location
stored onc following
thanseveral strings, then to
for when uses the parameters It
indata along function uses is
the location for compiler
variables long Array. called. all
sum using different paraneters
fromthe each
with variables
of and and or
data and
An parameter
the or
characters. the deletion register arguments, dependent.
constants efficient then
memory pointer structures. in
banks. program of the
is
to done way the internal internal The
required or location.
array. the Example: function. compier
for control
at data 2.19
next the fast data
by A
Pointers only Union |2.20|
ple: 2nd 1’ Example: First
memype
ThirdSecond Example:
It
’ int Char one is
byte xdata ’ similar
points
Functionhigher Memory-Specific ’ generic Example:Pointers0x0000.
(void ) a member
data pointer Lower pointers
Generic&&Port * Port Unsigned
#define Null
ddr address higher char Port last
order numtick * * to
the prjnamedeclaration. elementpointers at the
order pointer
* P1 Pl Pl to
start order
projectName =90H Port
pointer byte(lower ’ ’ long a
time.struct.
data
=
address offset will any of
(void of offset in (address) P1 * -
- compiler It
Address address. or pointers
Memory value
pass value (unsigned data function or list a A
null has
") of higher) value declard
reference of
ame the between pointer members
using byte items,
function of is
includes
one as is
the 3 to 0 *) is of
or standard
bytes. the to Ox90 declared
function two 255.
declared different
Codes. a port
memory
bytes. C P1. in
as data
is pointers, several
stored type NULL,
types. Embedded
specification class.
in Memory eg: It
data can Syste:S
#define A
pointer holof
d
memory.
saves data and
in NUII when
Ior
the a

while
(1) induction
Example: While
loop LoopsFor block.
code 2.2.4.
LoopsProgramming
Embedded C
ginning. TestRepeatuntil Condition For An
loop induction LOOPS
a Values
At Loop
certain variable continues and WhileStatements initial initial loop.
afterthe The
This followsa the
for again loop AND
do value values end has
wil
condition enabling to variable
within starts be set DECISIONS
until structured of
repeat the if within
of loop, used of
the the certain the the of again statements variable isa
execution condition
as at brackets condition looping
the variable values are
long endan condition loop approach initialized
if
is condition are in which
as' and and of induction curly
certain is
loop tested, changed.
if condition true. is with before
true at induces
endlessly: is brackets.
ifstart variable. the
condition then true true condition
following changed
is then or
execute again
never 1 flows
is which block
test.
true. tested. executes conditions. status
the to
of
means the
block statement or
the next condition
again true.
program. statement
It executes 2.21|
from has ina
the no It
(iii) (i) Decision
Blocks 2.22
(iv) ) program of
(vi)
statement
executes, ofA
block
then..elseif...then.. then
else elseif then If elseIf-then If-then
rN:; r2:;{rl:; then..elseif...
then..elseif..
(exp)
Case then..elseif... elseifIf. then then 0<then(exp)>0
If Statement flow
0=
dependsstatements

onThe
branchingN-way branchingN-way 3-way 2-way 2-way whether exccutes
2-way branching
Branching
Table progran
branching branching branching a if
2.1.
condition flowcertain a
Decision

branch if= resulting Find


if=2, false ifif<0 if=branch
if False True False Traddress.
ue address Testaddress Test tcontrol
estcondition
Blocks
true exp-value
0
rN, test - - is
an then then - - condition condition
or
out then then branch to branchbranch testbranch satisfied
or false instruction
when execute
value exp another addressaddressaddress
another is
rN >0 to to false true Enbedded
= to to no is Explanation
a r1, or another another
third
true true or
condition
another or
break 3 2 1 condition branch effect. not.
then
r2, variable branch branch executes clse
address.
is execute address address Systems
address
(continues) another
executed to to to these.
values.
another
another another and
rl block
or The lo
11 if

Functlonvalues. registers. or
Maln CPUand contains
Before functlon PC. 2.2.5.
Programming
Embedded C
Paasing methods. parameter
Passingthe
When A The anRoutine-
It callingFunction
asses arguments 1. 2. 1. PUNCTIONS
2. 1. 2.usingroutine this
program
a interrupt
valuepassingpassingarguments using Eg: Standard not main
alues
<>return
_type<> function, C
preprocessor another
needs function
name
(<> have program Sct
void 1s
to global source servicecalled of
thout an the the input timeSet return
C
are has function instructions. AND
reference value
argument variables arguments,].) characteristics
used values. functions.
declarationvalues. directives file routine. LIBRARY
routine.
'& (int
of starts reenters
or in
to a
variable The numticks) The
hich a a Reentrant Main FUNCTIONS
function Each isfrom
variable. inputs consists on starting
included. is
is function the the also
not are function
return
to main address
a passed of a
inter. pass Main
has
preprocessor function functíon
to
the by name, function the isa yalue
two function
same
parameter. in is
arguments, by
methods. acquired
C.
does void state
directives, which
Interrupt
There not main of
may the on and
return
macros, () variables
interrupt
functionsaved
are or (--. 2.23
two maY any
in
Aunctions
as argument
Passing reference
Passingthe 2.24
soon When The
Calling 1.a
as the output
of valueCalledpassed functionuse
a bythe
functionusing parameter a RoutineA
variable
parameters paramneters C function A Local
function may
function is
internal available function
be Memory
space A
is
called onto in
assignment
instruction register Fig.
cannot pointer amay
data Fig. returns without
a using in
land stack 2.15.
be2.16. register It
allocated kAM. pass modiliedto or th e pass
argumentsusingValue
orthat Passingvariables Global
a
changingpassesnassing
arguments pointer
ref. pointer.
parameter
Local register by addresspassing bank
the variable by
the
parameter value
the
variable orthe Memorspacey B
register, bank certain reference internal to
space Memory to value
is argument
passed
or the to
operations. assignmentusing Same
on are theyinternal returnusing calling RAM. called a and
return.
allocated Routine B
through purpose.
function B Name Local Embedded
are variableb
data Using function. function. Distinctly
passed
in the
RAM The
register argument. & SystenS
between sign The
parameters The
bank in return called and
2 an lo

and with 2.3. statements. Macros(b) program (a) builtprograms


Modulesand Programming
Eubedded C
A Example: It Header IncludeInclude A
curity hard
real-time RTOS executes by
source
from including
or file file files
atures soft - file
REAL #define other with
operating a with.h
real named
andcontaining
function
oftime TIME source .C
Header
any portLed extensionextension
system L' BlockCode
nstraints. statement to from (c) (b) J (a)
ernel OPERATING a Fig.
build files Onto Passing Onto
off(S1) has collection 2.7.
several called POP BiockCode
(RTOS) slack Push a
of several a is stack
block. preprocessornew Passing and
onto
OS It S1 and
source Stack stack Stack and POP
provides
when SYSTEM =0 source of in Push
is use calling
It files function the use
a in and
ultitasking
ing does file. Parameter calling in
built file. function use Stack
same
otection
ectness,
rfection, directive
not in
in is function function BlockCode funtion
it. K
module. M
have
ltiple OS to
functions include
for A,
tasks. the Module
the
pplications
within
contents,
can
|2.25
its be
2.3.2. 2.3.1. 2.26|

FUNCTIONS TYPES
RTOS
onerationsInterrupts
eventcomputer Resource
are system.
certain The
requirements, has different
Scheduling states. which
is Task Example: Very to deadlines.
Example:
database.
Hard online
(b) deterministic,
(a) possible.The RTOSSoft
performance
used to the meet OF
scheduling real
functions that Non-Priority
Priority be management
process takes important, timereal RTOS
resources
for When
or allocation- know. OF deadline time
causedwhichhandling
resource Flight
from in execution RTOS
based better
execution of RTOS oflate
and an algorithm TheRTOS if
for control
deadline is the
the it a application based managing -
tasks. program.is allocation.
- information
it schedulingscheduling
fatal,
interrupt. doing An It - time In compl -
to
scheduling time In real system The Systemetion
be
interrupt
is are is In
The
and necessary order tasks and time not hard tasks
able is classified and soft
ISR
execute his l algorithms
is of to occupies degrades of
running,
to based applications
through
met real have real
tasks
deadlines. schedule
should causes is run. is the time job
a for based to
the signal oninto are system as
istime
In it any can memory. be
have code the
RTOS, Greedy/list
on its system tasks
from requires
application Based the the the
performed undesimorerable
processor first be life
higher number task, performance
that devised. meeting and are Enbedded
a
scheduling come on cycle. process
The
will device the information
the on
priorities of task pertormed
more
but
respond to OS to and Task is Systens
attached be
system, task, the time not
suspend managementcalled will
torun first deadline and
over algorithm resource will job fatal.
as
as
allocate on serve. as fail. and
to if about failure fast
the the th to the it have task misses
is The or
a it is

application.
engines
printers
(ii) Multirate program.
systems(iü) the some functionality can (i) 2.3.3.
Programming
Embedded C
Two ProcessesTiming Multirate processes A Many Tasks 2.4.
process make
(6) (a) OS, MULTIPLE
important APPLICATIONS
Release embedded and
period.
periodicprocess process,
Deadline after aperiodic requirements the changes Network Strategic
Satellite
A embedded run is
teleconmmunication
systems systems
Modern
scheduling can memory but Processes
the and a
Figure deadline time havecellphones. in single
application-oriented TASKS
process specities start itrequirements the in switching and
process,
may computing
of is several comnputing space
sameexecution a military OF
2.18 on system. AND
the be the policy RTOS
generally is time process address is
ready
llustratesmeasured whenperiod. release control
on types must separate systemPROCESSES applications
at systems of These
a at processes:
which of space
occur the time a systems
the computation
definetiming functíonality
program.
from for different do
different beginning is the are which more
at the each
some the process requirements
initiated very
timing is Each
process
release tasks than
must common called is
way time of
the bybecomes
requirements. process reflected are one
of
other time. be asbut thing
process period an imposed threads. in the
finished. including has
than The event. ready light inpart (i.
rements. (or) its the e.,)
the
deadline on of
set For to weight own
environment
In them automobile structure the
end execute.
aperiodic periodicat state.
of for a by RTOS system
the time 2.27
In the In of
a
process
pipelined is |2.28
period. inverse
In The
multirate
the period
execution of
initiation its
systemsperiod. of
a
Fig. process
th e
interval
2.18. each
process (c)
CPU4 CPU3 CPU2
isFig. (b)
(tt) processes the Periodic Release
(a) time
CPU1P1i is 2.18. time
Periodic Release
ipeline A Deadline
timne Release
time Dead
line periodic
allows equal Deadline
by periodofPeriod
() event
processPeriod p1
P1i+5
i+1| P1 betweenTiming p1 process
startat
process P1 executesto process
P1i+7
P1i+3 i+2 P1i+4 | th e the
released
cution initiationperiod successive requirements
P1 at
+6| i its
inown Time Time Time
with common
interval
execution.
distinct Embedded
CPU
to
case.
be rate. The
Howwever,
less Systems
For process
than periodic
and
the for rate lor

Metrics
CPU(iv) set.
dependencies
directed automative
acceptable.
result is What
initiation case,Programming
Embedded C
A The Figure
(d) (c) (b) (a) set happens initiation
acyclic of
timing rate
Utilization
the expended CPU.the
The Completion Initiation 2.18
CPU
processes control
total total define less
Time graph, violation when interval (ii)
system, thanillustrates
available CPU by time a Fig.
- partial
A with a the
Ratio the The -time process is
time - component 2.19. depend period equal
process - The the
CPU of is basic The ordering data Data the
the given time result misses to
time. time dependencies p4 p3 inpipeline
which
measure dependencies on single one
-=U CPU T,=
T by at of can
at which task on the a fourth
bedeadline?
time lsisn process CPU. process
is which application.
catastrophic
of
graph of
Total that denoted a
CPU the process is
among the
work execution
is execution
is known period.
available time being process task p6 p
as is process
of Ci, the actually and where For
total used as But
where finishes and example, with
CPU amotnt complete task as it
process for starts denoted is
four
time graph. in possible
computations process.the is of
its multimedia
work. executing graph CPU.
inThe in
CPU case
form to m
is
time task data have us |2.29
to on of the of
Embedded Systems and lor
|2.30
EmbeddedC Programming 2.31|

(v) Process states and scheduling Programcounter - The counter field indicate the address of the next instrucion
ready, executing. to be executed for this process.
There are three basic scheduling states: waiting,
Executing
CPU registers - The registers vary in number and type depending on compuler
architecture.
Gets data
Choosen needs CPU ready CPU-scheduling information - Thís information includes a process priority,
data
to un pointers to scheduling queue and any other scheduling parameters.
Preempted
waiting Memory management information It includes value of base and limit
Ready Received data registers, the page tables or segment tables depending on memory system used by
needs data
OS.
Fig. 2.20. Process states Accounting information - It include amount of CPU and real time used, time
when it needs data or when it hae
A process goes into waiting state limits, account number, job or process numbers and so on.
finished all its work for current periods. I/O status information - It includes the list of VO devices allocated to this
receives its required data and
A process goes into ready state. When it process, a list of open files and so on.
when it enters new period.
2.5.2. PREEMPTION
A process goes into executing state only when it has all its data is ready to
run and scheduler selects the process to run. Kernel is a part of the operating systemn that determines what process is running.
Preemption is an alternate way to control execution of the task.
2.5. CONTEXT SWITCHING 2.5.3. CONTEXT SWITCHING

2.5.1. PROCESS CONTROL BLOCK (PCB) Switching the CPU to another process requires saving the state of old process and
knoWn as context switch.
loading the saved state for the new process. This task is
Each process is represented in the operating system by a process control block
process. It includes the
(also called as a task control block). It contains many piece of information associated The context of a process is represented in the PCB of a
management information.
with a specific process including these value of CPUregistersthe process state and memory
the old process in its.
When context switch occurs, the kernel saves the context of
Process state scheduled to run. It speed varies
PCB and loads the saved context of the new process
number of registers that must
Program counter
from machine to machine depending on memory speed,
instruction.
CPUregister be copied and existence of special
CPU scheduling information SCHEDULING
2.6. PRIORITY BASED
Memory management information
there are two ways
3 Accounting information To assign priorities to process
change during execution.
IO status information (a) Static priorities that do not
change during execution.
Process state- The state may be new, ready, (b) Dynamic priorities that
running, waiting, halted..and so on.
|2.32 Embedded Systems and lor
Enbedded CProgramming
Rate monotonic scheduling (RMS) 2.33

KMS 1s the first scheduling nolicv for real time system and has static scheduling Process Execution time Period
policy. PI 4
The rate monotonic analvsis (RMA) is summarized by P2 2 6
(a) allprocesses run periodically P3 3 12
The priority is selected based on the execution
(6) Nocontext switching time
(c) No data dependencies
Applying RMA, the priorities are given for P1, P2, time. Smallest gets high prior1ty.
P3. The total time length is equal
to hyper period (.e.,) LCM of period (4,
(d) The execution time is constant 6, 12) = 12.
Allthe three periods start at
zero.
(e) dead lines are the end of periods The process occurs at the interval
according to period.
) highest priorities are selected for execution (i.e.) shortest period is 3 According to priority Pl starts executing for 1 time unit (i.e.,)
assigned highest priority. time and moves to ready state and next occurance at 4.
execution
Response time is defined as time at which the process finishes. At time 1, P2 starts executing for 2 time unit and next
occurance at 6.
Critical instant for a process is defined as instant during execution at which the At time 3, P3 starts executing for 1time unit since Pl occurance at time
task has largest response time. slot 4', based on priority. P1 is given 1 time slot and then the process P3
The critical instant for any process P under RMS model occurs when it is ready continue its execution. This follows for other time slots.
and higher priorities are also read, if any change in priority of process then P's P1 P2 P3 P1 P3 P2 P1 P3
response time can go down. 01 2 3 4 5 6 7 8 10 11 12
P1
Although RMS is the optimal static priority schedule, it does not allow the system P2
to use 100% of the available CPU time. The total CPU
utilization for n task is given P31
by
n
T
CPU utilization =
i=1
When there are m tasks with fixed priorities the
maximum processor utilization is Example 2: Following the RMA scheduling policy for give task set.
given by Execution Time Period
Process
U= m(21/m-1) 2 4
P1
When there are two tasks, the CPUutilization U will
not be greater than 2 (212 - P2 3 6
1) =0.83. CPU will be idle for atleast 17% of
the time. If there 12
of the period, then CPUutilization can be 100% 1S proper arrangement P3

Examplel: Consider the below example with set of


characteristics schedule with RMS algorithm. process and their
Embedded Systemns and Jor Embedded c Programming
2.34 |2.35

P1 P2 P1 P2 P2 P1 P2
Second, it is assumed that all the
0 1 2 3 4 5 6 7 8
10 11 12
e Since the P2 has highest process starts at zero timeline.
P1 priority it
The next priority is taken by Pl and starts executing and takes time period.
P2 takes the 3 time slot.
At time slot 5, P2 occurs and P3 is in ready state.
P3 Comparing P2 & P3, Pz
has the highest priority but comparing the deadline P3 has
that satisties scheduling.
In this case, there is no feasible assignment of process P2 has deadline in time slot deadline 8 and
*9 as it occurs at 5. So P3
not be able to schedule in the given timeline. (i.e.,) 12 time unit utilizes time slot
Ihe process P3 is and then proceeded by P2.
interval. The total CPU unit time (6 +6+3 = 15) is more than hyper peri0d, clearly
P2 P1 P3
exceeding CPU capacity. 2 3 4 5 6
P2 P2 P3 P2
7 8 9 10 11 12 13 14 15 16 17 18 19 20
Earliest Deadline First (EDF) scheduling P2

It is dynamic priority scheme. It changes the process priorities during execution P1

based on initiation time which may achieve higher CPU utilization. P3

EDF assign priorities based on deadline. The highest priority is for deadline
nearest in time. Lowest priority is for deadline farthest away. The final step is similar Utilization time is given by RMS,
to RMS. The priority is selected at completion of a process.
The EDF algorithm can achieve 100% utilization. The feasible scheduling exists if
the CPU utilization is s 1. 15
U= 20
x 100 =75%
The implementation of EDF is more complex than RMS. The problem is keeping
the process sorted by time to deadline. Since, it changes during execution, it Example 4: Schedule the given task set using EDF algorithm.
cannot
presort the process in an array.
To avoid the above disadvantage. Binary tree is built to Process Execution'time Period Deadline
keep the sorted records
and incrementally update the sort. The list can be P 2 4
modified, deleted or added using
the tree manipulation technique. Dynamic sorting adds 1 6
complexity to the entire P2
scheduling process. P3 3 8
Example 3:Consider the following process and schedule
through EDF algorithm. The priority is set with shortest deadline first. So, the order of process is P1, P3.
Process Execution time Period Deadline P2.
P1 P1 P3 P2 P1
3 20 12 34 5 6 7 8
P2 2
4 P1
P3 2
10 8 P2
First, the processes are
deadline has high priorities.ass1gned based on priorities. In EDE.
So the process are shortest
sorted as P2.Pl. P3.
Embedded Systems and Io
Embedded CProgramming
2.36 2.37
occurance. When PI
deadline at the
second 0ccurs Define CPU Scheduling.
In this case, the Pl misses the but it extends to 8. So the
within time slot
at time slot 4. it should end the process CPU scheduling is the process of
CPUscheduling is the basis of switching the CPUamong various processes
5. What is preemptive and non multiprogrammed operating systems.
scheduling is not feasible.
RMS Vs EDF
EDF preemptive scheduling?
RMS
Under Nonpreemptive scheduling once the CPU has been allocated to a
Achieves higher utilization
Achieves lower CPU process, the process keeps CPU until it releases the CPU either by terminating
out of CPU. or switching to the waiting state preemptive
utilization scheduling can preempt" a process
Easier to ensure that
all .which is utilizing
the CPUin between its execution and give the CPUto another
Difficult to diagonize the
deadlines will be satisfied process.
possibility of overload
6. What is advantages of Programming in C.
Ways to solve unschedulability
() Enable development of length and complex program in short
without changing the time.
(a) Get a faster CPU This will reduce execution time (ii) Ease to design program flow structure
periods.
(iii)Uses functions from library
(6) Redesign the processes to take less execution time.
(iv) Facilitates data types declaration.
(c) Rewrite the specification to change the deadlines.
7. Write need for RTOS in enbedded design.
TWOMARKS QUESTIONS WITH ANSWERS () Predictability:t It ensures tasks are executed with in certain deadline
regardless of system load.
1. Define RTOS.
(ii) Efficiency: It optimize the use of resources by scheduling task according
A real time operating system is multitasking operating system for the to their priority, deadline etc.
applications with real time constraints. The task should be completed within
(iii)Flexibility: It support different types of taskS and communication
specified time delay.
methods. This can simplify development and testing processes.
2. Define task and process.
8. Difference between Embedded C and Standard Clanguage.
In operating system context, a task is defined as the
program in execution. Embedded C Standard C
The term task and process refer to same
entity. A process or taskrequire various
system resources like CPU for executing the It is extension for Cand it i_ used to Cis a general purpose programming
and I/O devices for information exchange etc. process, memory for storing coa® develop microcontroller based language that allows structures
3. What is a thread? applications. programming
Athread otherwise called Hardware dependent Hardware independent
lightweight
utilization, comprises of athread Id, a process is a basic unit of CPU
program Require specific compiler that are Standard compiler helps to compile
It shares with otherthreads counter, register
a set and stack.
resources. belonging to the same process its capable of generating microcontroller and execute the program.
section and OS Section, data
code based outputs.
Enbeied S)stems and loT Shedded C Programmng
238 239

9. Wräe parpase of compäer, Linker and locatot. file so that it can REVIEW QUESTIONS
programming into objects 1
Compiler: hrslate high evd Explain how 3051 is interfaced with extermal memory ia
2 detail. (NoviDee z010)
Explain how to interface ADC ard DAC with 8051 in detail
Ex: GNU os SDcC. KeiiC with neat dsagram
another object
Linker: h ks be relcatahie biet ñle nd generats Nov/Dec 2017), (Dec 2013)
1 Explain in detai! the prOcedure to irÁerface stepper motor with 8051
ALP to run the stepper motor in both forward and reverse
and write 2n
by eocation the direction with detay.
Locztorr Pregae a fnal binan eetehle codes iles
eses (May 2015%Apr/May 2018)
4. Design a Trafic Light Controller using 851 as tte Microcontroller. Each lane
10. #a is memors mppdl0.
has a Go (Green). Listen (Yellow) and Stop Red)LEDs. The working of the
Iis is cne of the ecinigues for interfaing IO devices with microcontroller.
dIo device. memors elated instruction and system should be specified.
To r a e daa between C
There should be timers for Specifving the time for each signal. The connections
ory comtrol sigmas are sei
11. # a s resolution tüme in ADC? to the lights (from the port lines of the 8051) should be shown The progran for
the working of the system should also be writen.
kisefrei as a ratio of canze in value of ingut voltage (Vi), needed to
change the igal output by ILSB. 5. In acertain application, 256K bytes of NV-RAMM are needed to store data
collected by an 8051 microcontroller. Show the connection of an 8051 to a
12 #kati muttiple interrupt processing capabüiy? single 256K x 8 NV-RAM chip
Wheever a mmber of devices interTupt a CPU at a time and the processor is 6. Explain Multitasking, Mutiple Process in embedded platform.
bie to hardle them properiy. it is said to have muliple interrupt handling
(Apr/May-2018) (Apr/May-2016).(Nov/Dec-2016)
capability.
13. #hat is context, contat swúchng and record? 7. Enumerate the context switch mechanism for moving the CPU from one
The set of rezisters that defines a process is krown as its context and executing process to another executing process.
saitching fom ore process's register set to another is known as context
swirchinz The data structure that bolis the state of process known as record.
14. Defnecritical instant for a process.
The critical instant for a process is defined as the
instant during execution at
ahich the task has the largest response time.
15. State the equation for CPU utilization for a set of n
task.
CPU utilization at n task

wtere T. -CPU time for useful work ; t,-


available time

You might also like