Embedded System Final
Embedded System Final
Embedded System Final
An embedded system is some combination of computer hardware and software, either fixed in
capability or programmable, that is designed for a specific function or for specific functions within a
larger system. Industrial machines, agricultural and process industry devices, automobiles, medical
equipment, cameras, household appliances, airplanes, vending machines and toys as well as mobile
devices are all possible locations for an embedded system.
Characteristics
• Embedded systems are designed to do some specific task, rather than a general-purpose
computer for multiple tasks
• Embedded systems are typically designed to meet real time constraints
• Embedded system are not always standalone devices. Many embedded systems consist of
small parts within a larger device that serves a more general purpose.
o (Form Gibson robot guitar features an embedded system for tuning the strings, but the
overall purpose of the Robot Guitar is, of course, to play music. Similarly, an
embedded system in an automobile provides a specific function as a subsystem of the
car itself.)
• The program instruction written for embedded systems are referred to as firmware and stored
in read-only memory or flash memory chips
• They run with limited computer hardware resources: little memory, small or non-existent
keyboard or screen.
• User interface of embedded system range from no user interface at all, in systems dedicated
only to one task, to complex graphical user interfaces. Simple embedded devices use buttons,
LEDs or character LCD.
• Some embedded systems provide user interface remotely with the help of serial or network
connection
• Embedded system either uses microprocessor or microcontroller as its processor
• Embedded systems talk with the outside world via peripherals such as Serial communication
interfaces (rs232, rs485), USB, synchronous serial communication interfaces (i2c, spi),
multimedia cards (SD cards), networks (ethernet, LonWorks), Fieldbuses (CAN-Bus), GPIO
and so on
Embedded systems can be classified into different types based on performance, functional
requirements and performance of the microcontroller.
Embedded systems are classified into four categories based on their performance and functional
requirements:
• Stand alone embedded systems
• Real time embedded systems
• Networked embedded systems
• Mobile embedded systems
Embedded Systems are classified into three types based on the performance of
the microcontroller such as
Stand alone embedded systems do not require a host system like a computer, it works by itself. It takes
the input from the input ports either analog or digital and processes, calculates and converts the data
and gives the resulting data through the connected device-Which either controls, drives and displays
the connected devices. Examples for the stand alone embedded systems are mp3 players, digital
cameras, video game consoles, microwave ovens and temperature measurement systems.
A real time embedded system is defined as, a system which gives a required o/p in a particular time.
These types of embedded systems follow the time deadlines for completion of a task. Real time
embedded systems are classified into two types such as soft and hard real time systems.
These types of embedded systems are related to a network to access the resources. The connected
network can be LAN, WAN or the internet. The connection can be any wired or wireless. This type of
embedded system is the fastest growing area in embedded system applications. The embedded web
server is a type of system wherein all embedded devices are connected to a web server and accessed
and controlled by a web browser.Example for the LAN networked embedded system is a home security
system wherein all sensors are connected and run on the protocol TCP/IP
Mobile embedded systems are used in portable embedded devices like cell phones, mobiles, digital
cameras, mp3 players and personal digital assistants, etc.The basic limitation of these devices is the
other resources and limitation of memory.
These types of embedded systems are designed with a single 8 or 16-bit microcontroller, that may
even be activated by a battery. For developing embedded software for small scale embedded systems,
the main programming tools are an editor, assembler, cross assembler and integrated development
environment (IDE).
These types of embedded systems design with a single or 16 or 32 bit microcontroller, RISCs or DSPs.
These types of embedded systems have both hardware and software complexities. For developing
embedded software for medium scale embedded systems, the main programming tools are C, C++,
JAVA, Visual C++, RTOS, debugger, source code engineering tool, simulator and IDE.
Sophisticated Embedded Systems
These types of embedded systems have enormous hardware and software complexities, that may need
ASIPs, IPs, PLAs, scalable or configurable processors. They are used for cutting-edge applications
that need hardware and software Co-design and components which have to assemble in the final
system.
ii) Software: The application software is required to perform the series of tasks.
An embedded system has software designed to keep in view of three constraints:
• Availability of System Memory
• Availability of processor speed
• The need to limit power dissipation when running the system continuously in cycles of
wait for events, run , stop and wake up.
iii) Real Time Operating System: (RTOS) It supervises the application software
and provides a mechanism to let the processor run a process as per scheduling and
do the switching from one process (task) to another process.
Embedded systems are used in different applications like automobiles, telecommunications, smart
cards, missiles, satellites, computer networking and digital consumer electronics.
Applications of Embedded Systems
• Security systems
• Telephone and banking
• Defense and aerospace
• Communication
• Digital Cameras
• Set top Boxes
• High Definition TVs
• DVDs
Skills required for an embedded system designer
For specific situation, some specific knowledge such as control system engineering is needed.
Processor
A processor is an electronic circuit which performs operations on some external data source, usually memory
or some other data stream.
The CU includes the fetch unit for fetching instructions from the memory
The EU has circuits that implement the instruction pertaining to data transfer operations and data conversion
from one form to another. It includes the arithmetic and logical unit (ALU) and also the circuits that execute
instructions for a program control task (halt, interrupt, jump).
1. Microprocessor
A microprocessor is a single VLSI chip that has a CPU and many also have some other units such as caches,
floating point processing arithmetic unit, pipelining and super-scaling units for fast processing of instructions.
2. Microcontroller
A microcontroller is a single chip VLSI unit which, though having limited computational capabilities possesses
enhanced input output capabilities and a number of on-chip functional unit
3. Embedded processor
When a microcontroller or microprocessor are specially designed to have the following capabilities, the term
embedded processor is preferred instead of microcontroller of microprocessor.
A DSP is an essential unit of an embedded system for a large number of applications which needs signal
processing. For example: image processing, multimedia, Video, HDTV, DSP modem and telecommunication
processing systems.
In an embedded system, several processors may be needed to execute an algorithm fast and within a strict
dead line. For example, in real-time video processing, the number of MAC operations needed per second may
not be possible from one DSP unit. An embedded system then may incorporate tow or more processors
running in synchronization.
1. Power source
The embedded system devices operate in one of the following voltage source range
a) 5.0 V ± 0.25 V
b) 3.3 V ± 0.3 V
c) 2.0 V ± 0.2 V
d) 1.5 V ± 0.2 V
The following points have to be taken care of while connecting the supply rails
a) A processor may have more than two pins of VDD and VSS. This distributes the power in all the sections
and reduces interference between the sections.
b) Supply should separately power the (a) external I/O driving port (b) timer (c) clock and (d) reset
circuits.
An embedded system may need to be run continuously without being switched off; the system design,
therefore, is constrained by the need to limit power dissipation while it is running.
The clock controls the various clocking requirements for the CPU of the system timer and CPU machine cycle.
The machine cycles are for
The clock control time for executing an instruction. The clock uses either a crystal (external to the processor)
or a ceramic (internally associated with the processor) or an external oscillator attached to the processor.
• The crystal resonator gives the highest stability in frequency with temp drift in the circuit
• The internal ceramic resonator, if available in a processor, saves the use of the external crystal and
gives a reasonable though not very highly stable frequency
• The external IC based clock oscillator has a significantly higher power dissipation compared to internal
processor-resonator. However, it provides a higher driving capability, which might be needed when
various circuits of embedded system are concurrently driven
3. System clock
A timer circuit suitably configured is the system-clock. It is used by the schedulers and for real-time
programming. More than one timer using the system clock may be needed for various timing and counting
needs in a system
4. Reset circuit and watchdog timer
Reset means that the processor starts the processing of instructions from a starting address. The reset
circuit activates for a fixed period and then deactivates. The processor circuit keeps the reset pin active
and then deactivates to let the program proceed from a default beginning address. Reset can be activated
by one of the followings:
a. An external reset circuit that activates on the power-up, on switching-on reset of the system or
on detection of a low voltage.
b. By a software instruction or time-out by a programmed timer know as watchdog timer or a clock
monitor detecting a slowdown below certain threshold frequencies due to fault.
The watchdog timer is a timing device that resets the system after a predefined timeout. To avoid the
reset the watchdog should be fed before the timeout occurs. The watchdog timer is activated within the
first few clock cycles after power-up. The watchdog timer rescues the system if a fault develops and the
program gets stuck.
5. Memories
The system uses various types of the memory. The types of memories and their functions are tabulated
below:
Memory Function
ROM or EPROM Stores application programs from where the
processor fetches the instruction codes. Stores
codes for system booting, initializing, initial input
data and strings. Codes for RTOS pointers
(addresses) of various service routines.
RAM (internal and External) Stores variables during program run and stores
the stack. Stores input and output buffers, for
example, for speech or image
EEPROM or Flash Store non-volatile results of processing
Caches Stores copies of instructions and data in advance
from external memories and stores temporarily
during fast memory
6. I/O ports
• The system uses input ports to get the inputs from the physical devices such as key-buttons,
sensors and transducer circuit.
• The system uses output ports to send output to various devices such as LED, LCD, modems,
printers, alarms, actuators and so on.
• The system may get inputs from multiple channels or may have to send output to multiple
channels.
• For networking the system there are different types of protocol such as I2C, CAN, USB, SPI and
PCI.
7. Interrupts Handler
An interrupt handling mechanism exits in each system to handle interrupts from various process in the
system.
• There can be a number of interrupt sources and groups of interrupt sources in a processor. An
interrupt may be a hardware signal that indicates the occurrence of an event. A software interrupt
may arise or can be configured in some conditions.
• The system may prioritize the sources, nnh and service them accordingly.
• Certain sources are not maskable and cannot be disabled.
• The processor’s current program diverts to interrupt service routine on the occurrence of the
interrupt.
PWM stands for Pulse Width Modulation and is the method to produce variable voltages using digital
means. PWM is a way of digitally encoding analog signal levels.
Figure 1 shows three different PWM signals. Figure 1a shows a PWM output at a 10% duty cycle. That is,
the signal is on for 10% of the period and off the other 90%. Figures 1b and 1c show PWM outputs at 50%
and 90% duty cycles, respectively. These three PWM outputs encode three different analog signal values,
at 10%, 50%, and 90% of the full strength. If, for example, the supply is 9V and the duty cycle is 10%, a
0.9V analog signal results.
An Analog to Digital Converter (ADC) is a very useful feature that converts an analog voltage on a pin to a
digital number. By converting from the analog world to the digital world, we can begin to use electronics
to interface to the analog world around us.
ADCs can vary greatly between microcontroller. The ADC on some microcontroller is a 10-bit ADC meaning
it has the ability to detect 1,024 (210) discrete analog levels. Some microcontrollers have 8-bit ADCs (28
= 256 discrete levels) and some have 16-bit ADCs (216 = 65,536 discrete levels). There is a conversion time
limit in which the conversion is definite.
The LED is a diode that emits yellow, green or red light on application of forward voltage. The LED is use
to indicate the system status.
10. Keypad/Keyboard
The keypad or keyboard is an important device for getting user inputs. The system must provide the
necessary interfacing and key-debouncing circuit as well as the software for the system to receive input
from the key of keypad or keyboard.
11. Modem/Transceiver
The system provides necessary interface for user for connection through cable or wireless connectivity. A
transceiver is circuit that can transmit as well as receive byte streams.
Embedded Systems Design: A Unified
Hardware/Software Introduction
1
Outline
• Introduction
• Combinational logic
• Sequential logic
• Custom single-purpose processor design
• RT-level custom single-purpose processor design
• Processor
– Digital circuit that performs a
computation tasks
– Controller and datapath CCD
Digital camera chip
• Transistor
– The basic electrical component in digital systems
– Acts as an on/off switch
– Voltage at “gate” controls whether current flows from
source to drain
source
gate Conducts
if gate=1
1 drain
gate
IC package IC oxide
source channel drain
Silicon substrate
x F x F x x y F x x y F x x y F
F y F F
0 0 y 0 0 0 0 0 0 y 0 0 0
1 1 0 1 0 0 1 1 0 1 1
1 0 0 1 0 1 1 0 1
F=x F=xy F=x+y F=x⊕y
1 1 1 1 1 1 1 1 0
Driver AND OR XOR
x F x F x x y F x x y F x x y F
F F F
0 1 y 0 0 1 y 0 0 1 y 0 0 1
1 0 0 1 1 0 1 0 0 1 0
F = x’ F = (x y)’ 1 0 1 F = (x+y)’ 1 0 0 F=x y 1 0 0
Inverter NAND 1 1 0 NOR 1 1 0 XNOR 1 1 1
z = ab + b’c + bc’
I(log n -1) I0 A A B
B A B
I(m-1) I1 I0 n n
… n n n
n …
log n x n n-bit n bit,
S0 n-bit, m x 1 n-bit
Decoder Adder m function S0
… Multiplexor Comparator
ALU …
… n
S(log m) n S(log m)
n
O(n-1) O1 O0 carry sum less equal greater
O O
With enable input e With carry-in input Ci May have status outputs
all O’s are 0 if e=0 carry, zero, etc.
sum = A + B + Ci
I
n
load shift n-bit
n-bit n-bit
Register Shift register Counter
clear I Q
n n
Q Q
Q= Q = lsb Q=
0 if clear=1, - Content shifted 0 if clear=1,
I if load=1 and clock=1, - I stored in msb Q(prev)+1 if count=1 and clock=1.
Q(previous) otherwise.
Design a counter with following binary sequence 1,2,5,7 and repeat. Use
JK flip flop.
• Step 1: Since it is three bit counter, the number of flip-flops required is three
• Step 2: flip-flop used: JK flip flop
• Step 3: Let three flip flop be A, B, C
• Step 4: State diagram and state table
101
1 0 1 1 1 1
1 1 1 0 0 1
A
JA A
CLK
A
KA A’
B
JB B
B
KB B’
C
JC C
C
KC C’
external external
control data controller datapath
inputs inputs
… …
datapath next-state registers
control and
controller inputs datapath control
logic
datapath
control state functional
outputs register units
… …
external external
control data
outputs outputs
… …
GCD
“complex” state machine 3: x = x_i
d_o
– Known as FSMD: finite- 4: y = y_i
state machine with datapath (b) desired functionality
5: !(x!=y)
– Can use templates to 0: int x, y; x!=y
1: while (1) {
perform such conversion 2: while (!go_i);
6:
x<y !(x<y)
3: x = x_i;
y = y -x 8: x = x - y
4: y = y_i; 7:
5: while (x != y) {
6-J:
6: if (x < y)
7: y = y - x;
else 5-J:
8: x = x - y; 9: d_o = x
}
9: d_o = x; 1-J:
}
1 !(!go_i)
declared variable 2:
x_i y_i
!go_i
• Create a functional unit for 2-J:
x_sel
Datapath
x_ld
0: x 0: y
• Connect the ports, registers 4: y = y_i
y_ld
1 !(!go_i)
Controller
0000 1:
!1 • Same structure as FSMD
1
2:
!go_i
0001 2:
!(!go_i)
• Replace complex
!go_i
2-J:
0010 2-J: actions/conditions with
3: x = x_i x_sel = 0
0011 3: x_ld = 1
datapath configurations
4: y = y_i
y_sel = 0 x_i y_i
0100 4: y_ld = 1
!(x!=y)
Datapath
5: !x_neq_y
0101 5: x_sel
x!=y n-bit 2x1 n-bit 2x1
x_neq_y y_sel
6: 0110 6:
x_ld
x<y !(x<y) x_lt_y !x_lt_y 0: x 0: y
y_ld
7: y = y -x 8: x = x - y 7: y_sel = 1 8: x_sel =1
y_ld = 1 x_ld = 1
1010 5-J:
1011 9: d_ld = 1
1100 1-J:
!cond
a=b C: C:
cond c1 !c1*c2 !c1*!c2
next loop-body-
c1 stmts c2 stmts others
statement statements
J: J:
next next
statement statement
2-J: x = x_i
3: y = y_i
merge state 2 and state 2J – no loop operation in
3: x = x_i between them
5:
x!=y
9: d_o = x
6: merge state 5 and state 6 – transitions from state 6 can
x<y !(x<y) be done in state 5
y = y -x 8: x = x - y
7:
eliminate state 5J and 6J – transitions from each state
6-J: can be done from state 7 and state 8, respectively
5-J:
eliminate state 1-J – transition from state 1-J can be
d_o = x done directly from state 9
9:
1-J:
• State encoding
– task of assigning a unique bit pattern to each state in an FSM
– size of state register and combinational logic vary
– can be treated as an ordering problem
• State minimization
– task of merging equivalent states into a single state
• state equivalent if for all possible input combinations the two states
generate the same outputs and transitions to the next same state
1
Introduction
• General-Purpose Processor
– Processor designed for a variety of computation tasks
– Low unit cost, in part because manufacturer spreads NRE
(Non-recurring engineering) over large numbers of units
• Motorola sold half a billion 68HC05 microcontrollers in 1996 alone
– Carefully designed since higher NRE is acceptable
• Can yield good performance, size and power
– Low NRE cost, short time-to-market/prototype, high
flexibility
• User just writes software; no processor design
– a.k.a. “microprocessor” – “micro” used when they were
implemented on one or a few chips rather than entire rooms
Manish Man Shrestha 2
Cosmos College of management and technology
Basic Architecture
• Load Processor
– Read memory location Control unit Datapath
into register ALU
• ALU operation Controller Control
/Status
+1
memory location
I/O
Memory
...
10
11
...
Manish Man Shrestha 5
Cosmos College of management and technology
Control Unit
• Control unit: configures the datapath
operations Processor
– Sequence of desired operations Control unit Datapath
(“instructions”) stored in memory –
ALU
“program”
Controller Control
• Instruction cycle – broken into /Status
several sub-operations, each one
clock cycle, e.g.: Registers
– Fetch: Get next instruction into IR
– Decode: Determine what the
instruction means
– Fetch operands: Move data from PC IR R0 R1
memory to datapath register
– Execute: Move data through the
ALU I/O
– Store results: Write data from 100 load R0, M[500] Memory
...
register to memory 500 10
101 inc R1, R0 501
102 store M[501], R1 ...
Manish Man Shrestha 6
Cosmos College of management and technology
Control Unit Sub-Operations
• Fetch Processor
Control unit Datapath
– Get next instruction
ALU
into IR Controller Control
/Status
– PC: program
counter, always Registers
points to next
instruction PC IR
100 R0 R1
load R0, M[500]
– IR: holds the
fetched instruction I/O
• Decode Processor
Control unit Datapath
– Determine what the
ALU
instruction means Controller Control
/Status
Registers
PC 100 IR R0 R1
load R0, M[500]
I/O
Registers
10
PC 100 IR R0 R1
load R0, M[500]
I/O
• Execute Processor
Control unit Datapath
– Move data through
ALU
the ALU Controller Control
/Status
– This particular
instruction does Registers
I/O
I/O
PC=100 Processor
Registers
10
PC 100 IR R0 R1
load R0, M[500]
I/O
PC=100 Processor
PC=101
Registers
Fetch Decode Fetch Exec. Store
ops results
clk
10 11
PC 101 IR R0 R1
inc R1, R0
I/O
PC=100 Processor
PC=101
Registers
Fetch Decode Fetch Exec. Store
ops results
clk
10 11
PC 102 IR R0 R1
store M[501], R1
PC=102
Fetch Decode Fetch Exec. Store I/O
ops results ...
100 load R0, M[500] Memory
clk 500 10
101 inc R1, R0 501 11
102 store M[501], R1 ...
Manish Man Shrestha 14
Cosmos College of management and technology
Architectural Considerations
register delay in
entire processor PC IR
– Memory access is
often the longest I/O
Memory
Wash 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
Non-pipelined Pipelined
Dry 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
Fetch-instr. 1 2 3 4 5 6 7 8
Decode 1 2 3 4 5 6 7 8
Execute 1 2 3 4 5 6 7 8
Instruction 1
Store res. 1 2 3 4 5 6 7 8
Time
pipelined instruction execution
Processor Processor
• Princeton
– Fewer memory
wires
• Harvard
Program Data memory Memory
– Simultaneous memory (program and data)
Memory
...
• Instruction Set
– Defines the legal set of instructions for that processor
• Data transfer: memory/register, register/register, I/O, etc.
• Arithmetic/logical: move register through ALU and back
• Branches: determine next PC value when not just PC+1
Immediate Data
Register-direct
Register address Data
Register
Register address Memory address Data
indirect
Data
• Development processor
– The processor on which we write and debug our programs
• Usually a PC
• Target processor
– The processor that the program will run on in our embedded
system
• Often different from the development processor
• Compilers
C File C File Asm.
– Cross compiler
File
• Runs on one
Compiler Assemble
processor, but
r generates code for
Binary Binary Binary
File
another
File File
Linker
• Assemblers
Library Debugger
• Linkers
Exec.
File Profiler
• Debuggers
Implementation Phase Verification Phase
• Profilers
Sources: Intel, Motorola, MIPS, ARM, TI, and IBM Website/Datasheet; Embedded Systems Programming, Nov. 1998
down 0001
Mov2 M[dir] = RF[rn]
to Fetch
Chapter 3 Memory
1
Introduction
…
– m x n: m words of n bits each
m words
– k = Log2(m) address input signals …
– or m = 2^k words
– e.g., 4,096 x 8 memory:
n bits per word
• 32,768 bits
• 12 address input signals
memory external view
• 8 input/output data signals
r/w
2k × n read and write
• Memory access enable memory
simultaneously
Qn-1 Q0
permanence
• Traditional ROM/RAM distinctions
Storage
– ROM Mask-programmed ROM Ideal memory
• read only, bits stored without power
OTP ROM
– RAM Life of
product
• read and write, lose stored bits without
power Tens of EPROM EEPROM FLASH
years
• Traditional distinctions blurred Battery Nonvolatile NVRAM
life (10
– Advanced ROMs can be written to years)
• e.g., EEPROM In-system
programmable SRAM/DRAM
– Advanced RAMs can hold bits without
Near
power zero Write
ability
• e.g., NVRAM
During External External External External
• Write ability fabrication programmer, programmer, programmer programmer
In-system, fast
writes,
only one time only 1,000s OR in-system, OR in-system,
unlimited
– Manner and speed a memory can be of cycles 1,000s block-oriented
cycles
of cycles writes, 1,000s
written of cycles
• Storage permanence
– ability of memory to hold stored bits Write ability and storage permanence of memories,
after they are written showing relative degrees along each axis (not to scale).
• Nonvolatile memory
• Can be read from but not written to, by a
processor in an embedded system External view
…
Ak-1
• Uses …
lines Q2 and Q0
• Output is 1010
Manish Man Shrestha 8
Cosmos College of Management and technology
Implementing combinational function
Truth table
Inputs (address) Outputs
a b c y z 8×2 ROM
0 0 word 0
0 0 0 0 0
0 0 1 0 1 0 1 word 1
0 1 0 0 1 0 1
0 1 1 1 0 enable 1 0
1 0 0 1 0 1 0
1 0 1 1 1 c 1 1
1 1 0 1 1 b 1 1
1 1 1 1 1 1 1 word 7
a
y z
logic 0
– (c) (Erase) Shining UV rays on surface of floating-gate causes
negative charges to return to channel from floating gate restoring +15V
the logic 1
source drain
– (d) An EPROM package showing quartz window through which (b)
• Extension of EEPROM
– Same floating gate principle
– Same write ability and storage permanence
• Fast erase
– Large blocks of memory erased at once, rather than one word at a time
– Blocks typically several thousand bytes large
• Writes to single words may be slower
– Entire block must be read, word updated, then entire block written back
• Used with embedded systems storing large data items in
nonvolatile memory
– e.g., digital cameras, TV set-top boxes, cell phones
Ak-1
during execution …
– each input and output data line connects to each 4×4 RAM
cell in its column 2×4
enable
decoder
– rd/wr connected to every cell
A0
– when row is enabled by decoder, each cell has logic A1
Memory
that stores input data bit when rd/wr indicates write cell
rd/wr
or outputs stored bit when rd/wr indicates read To every cell
Q3 Q2 Q1 Q0
TC55V2325F CS3
F-100
data<31…0>
block diagram
timing diagram
memory
– Can be multiple levels of
cache
Manish Man Shrestha 21
Cosmos College of Management and technology
Cache
indicated by index V T D
Tag Offset
Data
V T D V T D V T D
…
Valid
= =
=
Interfacing
Table of Contents
Introduction. ................................................................................................................................................. 3
Bus................................................................................................................................................................. 3
Ports .............................................................................................................................................................. 3
Timing Diagrams ........................................................................................................................................... 3
Basic protocol concepts ................................................................................................................................ 4
Time multiplexing ..................................................................................................................................... 4
Strobe protocol ......................................................................................................................................... 4
Handshake protocol .................................................................................................................................. 5
Microprocessor interfacing: I/O addressing ................................................................................................. 5
Port-based I/O (parallel I/O) ..................................................................................................................... 5
Bus-based I/O............................................................................................................................................ 5
Types of bus-based I/O: ........................................................................................................................ 6
Compromises/extension for I/O addressing ................................................................................................. 6
Parallel I/O peripheral ............................................................................................................................... 6
Extended parallel I/O ................................................................................................................................ 7
ISA bus ........................................................................................................................................................... 7
A basic memory protocol .............................................................................................................................. 7
Microprocessor Interrupts ............................................................................................................................ 8
Fixed interrupt .......................................................................................................................................... 8
Interrupt-driven I/O using fixed ISR location example ............................................................................. 8
Vectored interrupt .................................................................................................................................... 9
Interrupt-driven I/O using vectored interrupt .......................................................................................... 9
Interrupt address table ............................................................................................................................... 10
Maskable vs. non-maskable interrupts ....................................................................................................... 10
Direct memory access ................................................................................................................................. 10
Peripheral to memory transfer with DMA .............................................................................................. 11
Arbitration................................................................................................................................................... 11
Priority arbiter......................................................................................................................................... 11
Types of priority .................................................................................................................................. 12
1
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
Daisy-chain arbitration............................................................................................................................ 12
Pros/cons of Daisy-chain arbitration .................................................................................................. 13
Network-oriented arbitration ................................................................................................................. 13
Multilevel bus architectures ....................................................................................................................... 13
Processor-local bus ................................................................................................................................. 14
Peripheral bus ......................................................................................................................................... 14
Bridge ...................................................................................................................................................... 14
Advanced communication principles .......................................................................................................... 14
Parallel communication .............................................................................................................................. 14
Serial communication ................................................................................................................................. 14
Wireless communication ............................................................................................................................ 15
Error detection and correction ................................................................................................................... 15
Serial protocols: I2C ..................................................................................................................................... 15
Serial protocols: CAN .................................................................................................................................. 16
Serial protocols: FireWire ........................................................................................................................... 17
Serial protocols: USB ................................................................................................................................... 17
Parallel protocols: PCI Bus .......................................................................................................................... 17
Parallel protocols: ARM Bus ........................................................................................................................ 18
Wireless protocols: IrDA ............................................................................................................................. 18
Wireless protocols: Bluetooth .................................................................................................................... 18
Wireless Protocols: IEEE 802.11.................................................................................................................. 18
2
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
Introduction.
The aspects of embedded system functionality are processing, storage and communication. The
communication includes transfer of data between processors, memories and various peripherals. The
are implemented using bused and are called interfacing.
Bus
A bus is a set of wires with a single function (address bus and data bus) or entire collection of wires
(Address, data and control) with associated protocol. It can be uni-directional or bi-directional.
Ports
Ports are the conducting device on periphery. It connects bus to processor of memory. It is often
referred to as a pin. It can be a single wire or set of wires with a single function.
Timing Diagrams
It is a most common method for describing a communication protocol. In timing diagram time proceeds
to the right on x-axis. The diagram has control signal and data signal.
3
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
Time multiplexing
• Share a single set of wires for multiple pieces of data
• Saves wires at expense of time
Strobe protocol
• Master asserts req to receive data
• Servant puts data on bus within time taccess
• Master receives data and deasserts req
• Servant ready for next request
4
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
Handshake protocol
• Master asserts req to receive data
• Servant puts data on bus and asserts ack
• Master receives data and deasserts req
• Servant ready for next request
Bus-based I/O
• Processor has address, data and control ports that form a single bus
5
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
In memory mapped I/O, peripheral registers occupy addresses in same address space as memory. For example, if
Bus as 16-bit address, lower 32k addresses may correspond to memory and upper 32k addresses may correspond
to peripherals.
In standard I/O, Additional pin (M/IO) on bus indicates whether to access memory or peripheral. For example, if
bus has 16-bit address, all 64k address correspond to memory when M/IO set to 0 and all 64 k addresses
correspond to peripheral when M/IO set to 1.
Parallel I/O peripheral is added when processor only support bus-based I/O but parallel I/O is needed for
interfacing. Each port of the peripheral is connected to a register that is read/written by the processor.
6
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
It is used when processor need more port than the available port within the processor.
ISA bus
ISA support standard I/O communication protocol. In this protocol /IOR is used to read data and /IOW is used for
writes.
7
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
Ports P0 and P2 support port-based I/O when 8051 internal memory being used
Those ports serve as data/address buses when external memory is being used
16-bit address and 8-bit data are time multiplexed; low 8-bits of address must therefore be latched with aid of ALE
signal
Microprocessor Interrupts
Fixed interrupt
• Address built into microprocessor, cannot be changed
• Either ISR stored at address or a jump to actual ISR stored if not enough bytes available
8
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
Vectored interrupt
• Peripheral must provide the address
• Common when microprocessor has multiple peripherals connected by a system bus
9
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
Typically reserved for drastic situations, like power failure requiring immediate backup of data to non-volatile
memory
10
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
Arbitration
It is a method of handling request service from multiple peripherals. There are three types of arbiter: Priority
arbiter, Daisy chain arbiter and Network-oriented arbitration.
Priority arbiter
It is single purpose processor. Peripherals make request to arbiter and arbiter make requests to resource. The
arbiter assigns priority to each peripheral connected to it and request service in accordance to the priority of the
peripheral. The arbiter is connected to system bus for configuration only.
11
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
Types of priority
• Fixed priority
Daisy-chain arbitration
In daisy-chain arbitration, arbitration is done by the peripherals. The arbiter is either built into peripheral or
external logic is added in the peripherals. The peripherals are connected to each other in daisy-chain manner. In
this arbitration, closest peripheral has highest priority and only one peripheral connected to resource, all other
connected “upstream”. The peripheral’s req flow “downstream” to resource, resource’s ack flows “upstream” to
requesting peripheral.
12
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
Network-oriented arbitration
In network-oriented arbitration, multiple microprocessors share a bus (network). Th arbitration typically built into
bus protocol. The arbitration as typically used for connecting multiple distant chips.
13
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
Processor-local bus
High speed, wide, most frequent communication
Peripheral bus
Lower speed, narrower, less frequent communication
Bridge
Single-purpose processor converts communication between busses
Parallel communication
• Multiple data, control, and possibly power wires
One bit per wire
• High data throughput with short distances
• Typically used when connecting devices on same IC or same circuit board
Bus must be kept short
long parallel wires result in high capacitance values which requires more time to charge/discharge
Data misalignment between wires increases as length increases
• Higher cost, bulky
Serial communication
• Single data wire, possibly also control and power wires
• Words transmitted one bit at a time
• Higher data throughput with long distances
Less average capacitance, so more bits per unit of time
• Cheaper, less bulky
• More complex interfacing logic and communication protocol
Sender needs to decompose word into bits
Receiver needs to recompose bits into word
14
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
Control signals often sent on same wire as data increasing protocol complexity
Wireless communication
• Infrared (IR)
Electronic wave frequencies just below visible light spectrum
Diode emits infrared light to generate signal
Infrared transistor detects signal, conducts when exposed to infrared light
Cheap to build
Need line of sight, limited range
• Radio frequency (RF)
Electromagnetic wave frequencies in radio spectrum
Analog circuitry and antenna needed on both sides of transmission
Line of sight not needed, transmitter power determines range
• Two-wire serial bus protocol developed by Philips Semiconductors nearly 20 years ago
• Enables peripheral ICs to communicate using simple communication hardware
• Data transfer rates up to 100 kbits/s and 7-bit addressing possible in normal mode
• 3.4 Mbits/s and 10-bit addressing in fast-mode
• Common devices capable of interfacing to I2C bus:
• EPROMS, Flash, and some RAM memory, real-time clocks, watchdog timers, and microcontrollers
15
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
16
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
– Standard adopted by industry and administered by PCISIG (PCI Special Interest Group)
17
Manish Man Shrestha
Cosmos College of Management and Technology
Manish Man Shrestha
Chapter 4 Cosmos College of Management and Technology
– 32-bit addressing
– IrDA hardware deployed in notebook computers, printers, PDAs, digital cameras, public phones,
cell phones
– No line-of-sight required
• PHY layer
– physical layer
• MAC layer
– collision avoidance/detection
19
Manish Man Shrestha
Cosmos College of Management and Technology
2018
Benefits of RTOS
• Priority Based Scheduling: The ability to separate critical processing from non-
critical is a powerful tool.
• Abstracting Timing Information: The RTOS is responsible for timing and provides
API functions. This allows for cleaner (and smaller) application code.
• Maintainability/Extensibility: Abstracting timing dependencies and task-based
design results in fewer interdependencies between modules. This makes for easier
maintenance.
• Modularity: The task-based API naturally encourages modular development as a task
will typically have a clearly defined role.
• Promotes Team Development: The task-based system allows separate
designers/teams to work independently on their parts of the project.
• Easier Testing: Modular task-based development allows for modular task based
testing.
• Code Reuse: Another benefit of modularity is that similar applications on similar
platforms will inevitably lead to the development of a library of standard tasks.
• Improved Efficiency: An RTOS can be entirely event driven; no processing time is
wasted polling for events that have not occurred.
• Idle Processing: Background or idle processing is performed in the idle task. This
ensures that things such as CPU load measurement, background CRC checking etc will
not affect the main processing.
Features of RTOS
The design of an RTOS is essentially a balance between providing a reasonably rich feature set for
application development and deployment and, not sacrificing predictability and timeliness. A basic
RTOS will be equipped with the following features:
• Multitasking and Preemptibility: An RTOS must be multi-tasked and preemptible to
support multiple tasks in real-time applications. The scheduler should be able to
preempt any task in the system and allocate the resource to the task that needs it most
even at peak load.
• Task Priority: Preemption defines the capability to identify the task that needs a
resource the most and allocates it the control to obtain the resource. In RTOS, such
RTOS Architecture
The architecture of an RTOS is dependent on the complexity of its deployment. Good RTOSs are
scalable to meet different sets of requirements for different applications. For simple applications,
an RTOS usually comprises only a kernel. For more complex embedded systems, an RTOS can be
a combination of various modules, including the kernel, networking protocol stacks, and other
components as illustrated in Figure 1.
Kernel
An operating system generally consists of two parts: kernel space (kernel mode) and user space
(user mode). Kernel is the smallest and central component of an operating system. Its services
include managing memory and devices and also to provide an interface for software applications
to use the resources. Additional services such as managing protection of programs and
multitasking may be included depending on architecture of operating system. The kernel is a bridge
between applications and the actual data processing done at the hardware level. It is the heart of
an operating system.
Microkernel
It runs only basic process communication (messaging) and I/O control. The other system services
(file system, networking, etc) reside in user space in the form of daemons/servers. Thus, micro
kernels provide a smaller set of simple hardware abstractions. It is more stable than monolithic as
the kernel is unaffected even if the servers failed (i.e. File System). Examples are AmigaOS and
QNX.
Exokernel
The concept is orthogonal to that of micro- vs. monolithic kernels by giving an application efficient
control over hardware. It runs only services protecting the resources (i.e. tracking the ownership,
guarding the usage, revoking access to resources, etc) by providing low-level interface for library
operating systems (libOSes) and leaving the management to the application.
Scheduling
Scheduling is the method by which work is assigned to resources that complete the work. The
work may be virtual computation elements such as threads, processes or data flows, which are in
turn scheduled onto hardware resources such as processors, network links
These operating systems are generally preemptive and have deterministic guarantees with regard
to response times.
Round-robin scheduling
Round-robin (RR) is one of the algorithms employed by RTOS. As the term is generally used,
time slices (also known as time quanta) are assigned to each process in equal portions and in
circular order, handling all processes without priority (also known as cyclic executive). Round-
robin scheduling is simple, easy to implement, and starvation-free.
Process
A process is an instance of a computer program that is being executed. It contains the program
code and its current activity. Depending on the operating system (OS), a process may be made up
of multiple threads of execution that execute instructions concurrently. While a computer program
is a passive collection of instructions, a process is the actual execution of those instructions.
Thread
A thread of execution is the smallest sequence of programmed instructions that can be managed
independently by a scheduler, which is typically a part of the operating system.
Task
Task consists of executable program, state of which is controlled by OS. It runs when it is
scheduled to run by the OS kernel, which gives the control of the CPU on a task request or message.
Task is that executing unit of computations which is controlled by some process at the OS
scheduling mechanism, which lets it execute on the CPU and by some process at OS for a resource-
• On interrupt of a task, the RTOS first gets itself the hardware source call and initiates the
corresponding ISR after saving the present processor status.
• Then the ISR during execution can post one or more outputs for the events and messages into
the mailboxes or queues.
Task characteristics
• Each task is independent and takes control of the CPU when scheduled by a scheduler at
an OS. The scheduler controls and runs the tasks.
• No task can call another task.
• Each task is recognized by a TCB.
• Each task has an ID.
• Each task may have priority parameter.
• A task is an independent process. The OS will only block a running task and let another
task again access of CPU to run the servicing codes.
Instruction Register :
This register decodes the op-code of an instruction to be executed and gives information to the
timing and control unit to generate necessary signals for the execution of the instruction
ALU :
The arithmetic and logic unit performs 8 bit arithmetic and logical operations over the operands
held by the temporary registers TMPI and TMP2 .Users cannot access these temporary registers .
Timer Register :
These two 16 bit register can be accessed as their lower and upper bytes. For example TL0
represents the lower byte of the timing register 0, while TH0 represents higher bytes of the timing
register 0. Similarly TL1 and TH1 represents lower and higher bytes of timing register 1. All these
registers can be accessed using the 4 addresses allotted to them which lies in the special function
registers. SFR address range, ie 80H to FFH .
Control Registers :
The special function registers IP, IE, TMOD, TCON, SCON and PCON contain control and status
information for interrupt timer/ counters and serial port.These register have been allotted address in
the SFR bank of 8051 .
Addressing Modes
The CPU can access data in various ways, which are called addressing modes
1 Immediate Addressing
Immediate addressing is so-named because the value to be stored in memory immediately follows
the operation code in memory. That is to say, the instruction itself dictates what value will be stored in
memory. The immediate data must be preceded by the pound sign, “#” .For example, the instruction:
MOV A,#20h This instruction uses Immediate Addressing because the Accumulator will be loaded with
the value that immediately follows; in this case 20 (hexadecimal). Immediate addressing is very fast since
the value to be loaded is included in the instruction. Can load information into any registers, including 16-
bit DPTR register However, since the value to be loaded is fixed at compile-time it is not very flexible.We
can also use immediate addressing mode to send data to 8051 ports
2 Register Addressing
This mode is uses registers to hold the data to be manipulated .The source and destination registers must
match in size. For example MOV DPTR,A will give an error because of their different size .The movement
of data between Rn registers is not allowed. That is Mov R1,R2 is not possible .
3 Direct Addressing
Direct addressing is so-named because the value to be stored in memory is obtained by directly
retrieving it from another memory location. For example: MOV A,30h
This instruction will read the data out of Internal RAM address 30 (hexadecimal) and store it in the
Accumulator. Direct addressing is generally fast since, although the value to be loaded isn’t included in
the instruction, it is quickly accessible since it is stored in the 8051’s Internal RAM. It is also much more
flexible than Immediate Addressing since the value to be loaded is whatever is found at the given address
which may be variable.
Also, it is important to note that when using direct addressing any instruction which refers to an address
between 00h and 7Fh is referring to Internal Memory. Any instruction which refers to an address between
80h and FFh is referring to the SFR control registers that control the 8051 microcontroller itself.
Indirect addressing is a very powerful addressing mode which in many cases provides an exceptional
level of flexibility. Indirect addressing is also the only way to access the extra 128 bytes of Internal RAM
found on an 8052. Indirect addressing appears as : MOV A,@R0
This instruction causes the 8051 to analyze the value of the R0 register. The 8051 will then load the
accumulator with the value from Internal RAM which is found at the address indicated by R0.
A register is used as a pointer to the data. Only register R0 and R1 are used for this purpose .R2 – R7 cannot be used
to hold the address of an operand located in RAM .When R0 and R1 hold the addresses of RAM locations, they must
be preceded by the “@” sign .
R0 and R1 are the only registers that can be used for pointers in register indirect addressing mode . Since R0 and R1
are 8 bits wide, their use is limited to access any information in the internal RAM. Whether accessing externally
connected RAM or on-chip ROM, we need 16-bit pointer in such case, the DPTR register is used.
Indexed addressing mode is widely used in accessing data elements of look-up table entries located in
the program ROM .The instruction used for this purpose is MOVC A,@A+DPTR .In instruction MOVC, “C”
means code. The contents of A are added to the 16-bit register DPTR to form the 16-bit address of the
needed data.
In many applications, the size of program code does not leave any room to share the 64K-byte code
space with data . The 8051 has another 64K bytes of memory space set aside exclusively for data
storage. This data memory space is referred to as external memory and it is accessed only by the MOVX
instruction
MOVX is a widely used instruction allowing access to external data memory space . To bring externally
stored data into the CPU, we use the instruction MOVX A,@DPTR
Example :
In this program, assume that the word “USA” is burned into ROM locations starting at 200H. And that the
program is burned into ROM locations starting at 0. Analyze how the program works and state where
“USA” is stored after this program is run.
Solution:
Example
An external ROM uses the 8051 data space to store the look-up table (starting at 1000H) for DAC
data. Write a program to read 30 Bytes of these data and send it to P1.
Solution:
MYXDATA EQU 1000H
COUNT EQU 30
MOV DPTR,#MYXDATA
MOV R2,#COUNT
AGAIN: MOVX A,@DPTR
MOV P1,A
INC DPTR
DJNZ R2,AGAIN
ORG 1000H
23H,42H,67H,89H,56H ...... ; 30 bytes Data for the table will be here
END
Internal Memory
The 8051’s on-chip memory consists of 256 memory bytes organized as follows:
The first 128 bytes of internal memory is organized as shown in figure, and is referred to as Internal RAM,
or IRAM.
Note since R2 happens to be memory location 02h in the Internal RAM the following instruction has the
same effect as the above instruction.
ADD A, 02h
These two instructions have the same effect as the direct instruction above.
SFR Registers
The SFR registers are located within the Internal Memory in the address range 80h to FFh, as shown in
figure 1.7. Not all locations within this range are defined. Each SFR has a very specific function. Each
SFR has an address (within the range 80h to FFh) and a name which reflects the purpose of the SFR.
Although 128 byes of the SFR address space is defined only 21 SFR registers are defined in the standard
8051. Undefined SFR addresses should not be accessed as this might lead to some unpredictable
results. Note some of the SFR registers are bit addressable. SFRs are accessed just like normal Internal
RAM locations.
We will discuss a few specific SFR registers here to help explain the SFR concept. Other specific SFR will
be explained later.
The operand P0.7 uses the dot operator and refers to bit 7 of SFR P0. The same bit could be addressed
by accessing bit location 87h. Thus the following two instructions have the same meaning:
CLR P0.7
CLR 87h
PSW, the Program Status Word is at address D0h and is a bit-addressable register. The status bits are
listed in table
Carry flag. C
This is a conventional carry, or borrow, flag used in arithmetic operations. The carry flag is also used as
the ‘Boolean accumulator’ for Boolean instruction operating at the bit level. This flag is sometimes
referenced as the CY flag.
Flag 0. F0
This is a general-purpose flag for user programming.
These bits define the active register bank (bank 0 is the default register bank).
Overflow flag. OV
This is a conventional overflow bit for signed arithmetic to determine if the result of a signed arithmetic
operation is out of range.
Stack Pointer
The Stack Pointer, SP, is an 8-bit SFR register at address 81h. The small address field (8 bits) and the
limited space available in the Internal RAM confines the stack size and this is sometimes a limitation for
8051 programmers. The SP contains the address of the data byte currently on the top of the stack. The
SP pointer in initialised to a defined address. A new data item is ‘pushed’ on to the stack using a PUSH
instruction which will cause the data item to be written to address SP + 1. Typical instructions, which
cause modification to the stack are: PUSH, POP, LCALL, RET, RETI etc.. The SP SFR, on start-up, is
initialised to 07h so this means the stack will start at 08h and expand upwards in Internal RAM. If register
banks 1 to 3 are to be used the SP SFR should be initialised to start higher up in Internal RAM. The
following instruction is often used to initialise the stack:
MOV SP, #2Fh
Data Pointer
The Data Pointer, DPTR, is a special 16-bit register used to address the external code or external data
memory. Since the SFR registers are just 8-bits wide the DPTR is stored in two SFR registers, where
DPL (82h) holds the low byte of the DPTR and DPH (83h) holds the high byte of the DPTR. For example,
if you wanted to write the value 46h to external data memory location 2500h, you might use the following
instructions:
Accumulator
This is the conventional accumulator that one expects to find in any computer, which is used to the hold
result of various arithmetic and logic operations. Since the 8051 microcontroller is just an 8-bit device, the
accumulator is, as expected, an 8 bit register. The accumulator, referred to as ACC or A, is usually
accessed explicitly using instructions such as:
However, the accumulator is defined as an SFR register at address E0h. So the following two instructions
have the same effect:
MOV E0h, #52h ; Move immediate the value 52h to Internal RAM location E0h, which is, in fact, the
accumulator SFR register.
Usually the first method, MOV A, #52h, is used as this is the most conventional (and happens to use less
space, 2 bytes as oppose to 3 bytes!)
B Register
The B register is an SFR register at addresses F0h which is bit-addressable. The B register is used in
two instructions only: i.e. MUL (multiply) and DIV (divide). The B register can also be used as a general-
purpose register.
Program Counter
The PC (Program Counter) is a 2 byte (16 bit) register which always contains the memory address of the
next instruction to be executed. When the 8051 is reset the PC is always initialised to 0000h. If a 2 byte
instruction is executed the PC is incremented by 2 and if a 3 byte instruction is executed the PC is
incremented by three so as to correctly point to the next instruction to be executed. A jump instruction
(e.g. LJMP) has the effect of causing the program to branch to a newly specified location, so the jump
instruction causes the PC contents to change to the new address value. Jump instructions cause the
program to flow in a non-sequential fashion.
TMOD, the Timer Mode register is an SFR at address 89h and is used to define the operational modes
for the timers, as will be described later.
TL0 (Timer 0 Low) and TH0 (Timer 0 High) are two SFR registers addressed at 8Ah and 8Bh
respectively. The two registers are associated with Timer 0.
TL1 (Timer 1 Low) and TH1 (Timer 1 High) are two SFR registers addressed at 8Ch and 8Dh
respectively. These two registers are associated with Timer 1.
The SCON (Serial Control) is an SFR register located at addresses 98h, and it is bit- addressable. SCON
configures the behaviour of the on-chip serial port, setting up parameters such as the baud rate of the
serial port, activating send and/or receive data, and setting up some specific control flags.
The SBUF (Serial Buffer) is an SFR register located at address 99h. SBUF is just a single byte deep
buffer used for sending and receiving data via the on-chip serial port
Interrupt Registers
Interrupts will be discussed in more detail later. The associated SFR registers are:
IE (Interrupt Enable) is an SFR register at addresses A8h and is used to enable and disable specific
interrupts. The MSB bit (bit 7) is used to disable all interrupts.
IP (Interrupt Priority) is an SFR register at addresses B8h and it is bit addressable. The IP register
specifies the relative priority (high or low priority) of each interrupt. On the 8051, an interrupt may either
be of low (0) priority or high (1) priority. .
ORG OriGinate, defines the starting address for the program in program (code) memory
EQU EQUate, assigns a numeric value to a symbol identifier so as to make the program more readable.
DB Define a Byte, puts a byte (8-bit number) number constant at this memory location
DW Define a Word, puts a word (16-bit number) number constant at this memory location
DBIT Define a Bit, defines a bit constant, which is stored in the bit addressable section if the Internal
RAM.
END This is the last statement in the source file to advise the assembler to stop the assembly process.
Types of Instructions
The assembly level instructions include: data transfer instructions, arithmetic
instructions, logical instructions, program control instructions, and some special
instructions such as the rotate instructions.
Data Transfer
Many computer operations are concerned with moving data from one location to another. The 8051 uses
five different types of instruction to move data:
MOV
In the 8051 the MOV instruction is concerned with moving data internally, i.e. between Internal RAM, SFR
registers, general registers etc. MOVX and MOVC are used in accessing external memory data. The
MOV instruction has the following format:
The instruction copies (copy is a more accurate word than move) data from a defined source location to a
destination location. Example MOV instructions are:
MOVX
The 8051 the external memory can be addressed using indirect addressing only. The DPTR register is
used to hold the address of the external data (since DPTR is a 16-bit register it can address 64KByte
locations: 216 = 64K). The 8 bit registers R0 or R1 can also be used for indirect addressing of external
memory but the address range is limited to the lower 256 bytes of memory (28 = 256 bytes).
The MOVX instruction is used to access the external memory (X indicates eXternal memory access). All
external moves must work through the A register (accumulator).
MOVC
MOVX instructions operate on RAM, which is (normally) a volatile memory. Program tables often need to
be stored in ROM since ROM is non volatile memory. The MOVC instruction is used to read data from the
external code memory (ROM). Like the MOVX instruction the DPTR register is used as the indirect
address register. The indirect addressing is enhanced to realise an indexed addressing mode where
register A can be used to provide an offset in the address specification. Like the MOVX instruction all
moves must be done through register A. The following sequence of instructions provides an example:
MOV DPTR, # 2000h ; Copy the data value 2000h to the DPTR register
MOV A, #80h ; Copy the data value 80h to register A
MOVC A, @A+DPTR ; Copy the contents of the address 2080h (2000h + 80h)
; to register A
Note, for the MOVC the program counter, PC, can also be used to form the address.
PUSH 4Ch ; Contents of RAM location 4Ch is saved to the stack. SP is incremented.
PUSH 00h ; The content of R0 (which is at 00h in RAM) is saved to the stack and SP is incremented.
POP 80h ; The data from current SP address is copied to 80h and SP is decremented.
XCH
The above move instructions copy data from a source location to a destination location, leaving the
source data unaffected. A special XCH (eXCHange) instruction will actually swap the data between
source and destination, effectively changing the source data. Immediate addressing may not be used with
XCH. XCH instructions must use register A. XCHD is a special case of the exchange instruction where
just the lower nibbles are exchanged. Examples using the XCH instruction are:
Arithmetic
Some key flags within the PSW, i.e. C, AC, OV, P, are utilised in many of the arithmetic instructions. The
arithmetic instructions can be grouped as follows:
Addition
Subtraction
Increment/decrement
Multiply/divide
Decimal adjust
Addition
Register A (the accumulator) is used to hold the result of any addition operation. Some simple addition
examples are:
The C (carry) flag is set to 1 if the addition resulted in a carry out of the accumulator’s MSB bit, otherwise
it is cleared. The AC (auxiliary) flag is set to 1 if there is a carry out of bit position 3 of the accumulator,
otherwise it is cleared.For signed numbers the OV flag is set to 1 if there is an arithmetic overflow .Simple
addition is done within the 8051 based on 8 bit numbers, but it is often required to add 16 bit numbers, or
24 bit numbers etc. This leads to the use of multiple byte (multi-precision) arithmetic. The least significant
bytes are first added, and if a carry results, this carry is carried over in the addition of the next significant
byte etc. This addition process is done at 8-bit precision steps to achieve multiprecision arithmetic. The
ADDC instruction is used to include the carry bit in the addition process.
SUBB A, #55d ; Subtract the number 55 (decimal) and the C flag from A; and put the result in A.
SUBB A, R6 ; Subtract R6 the C flag from A; and put the result in A.
SUBB A, 58h ; Subtract the number in RAM location 58h and the C flag From A; and put the result in A.
Increment/Decrement
The increment (INC) instruction has the effect of simply adding a binary 1 to a number while a decrement
(DEC) instruction has the effect of subtracting a binary 1 from a number. The increment and decrement
instructions can use the addressing modes: direct, indirect and register. The flags C, AC, and OV are not
affected by the increment or decrement instructions. If a value of FFh is increment it overflows to 00h. If a
value of 00h is decrement it underflows to FFh. The DPTR can overflow from FFFFh to 0000h. The DPTR
register cannot be decremented using a DEC instruction (unfortunately!). Some example INC and DEC
instructions are as follows:
Multiply / Divide
The 8051 supports 8-bit multiplication and division. This is low precision (8 bit) arithmetic but is useful for
many simple control applications. The arithmetic is relatively fast since multiplication and division are
implemented as single instructions. If better precision, or indeed, if floating point arithmetic is required
then special software routines need to be written. For the MUL or DIV instructions the A and B registers
must be used and only unsigned numbers are supported.
Multiplication
The MUL instruction is used as follows (note absence of a comma between the A and B operands):
MUL AB ; Multiply A by B.
The resulting product resides in registers A and B, the low-order byte is in A and the high order byte is in
B.
Division
The DIV instruction is used as follows:
DIV AB ; A is divided by B.
The remainder is put in register B and the integer part of the quotient is put in register A.
BRANCHING
The 8051 has a rich set of jumps that can operate at the bit and byte levels.
These jump opcodes are one reason the 8051 in such a powerful microcontroller.
Bit Jumps
Bit jumps all operate according to the status of the carry lag in the PSW or the status of any bit
addressable location.
All bit jumps are relative to the program counter.
JC radd jump relative if the carry flag is set to 1
JNC radd jump relative if the carry flag is reset to 0
JB b,radd jump relative if addressable bit is set to 1
JNB b,radd jump relative if addressable bit is reset to 0
JBC b,radd jump relative if addressable bit is set, and clear the addressable bit to 0
Byte Jumps
All byte jumps are relative to the program counter
• CJNE A, add, radd
compare the contents of the A register with the contents of the direct address; if they are not
equal, then jump to the relative address; set the carry flag to 1 if a is less than the contents of the
direct address; otherwise, set the carry flag to 0.
• CJNE A, #n, radd
compare the contents of the A register with the immediate number n ; if they are not equal, then
jump to the relative address; set the carry flag to 1 if A is less than the number; otherwise, set the
carry flag to 0.
JZ radd
Jump to the relative address if A is 0; the flags and the A register are not changed
JNZ radd
Jump to the relative address if A is not 0; the flags and the A register are not changed
UNCONDITIONAL JUMPS
The diagram above shows the 8051 pinout. The chip is a 40-pin package.
The four 8-bit I/O ports P0, P1, P2 and P3 each use 8 pins. All the ports upon RESET are configured as input,
ready to be used as input ports . When the first 0 is written to a port, it becomes an output . To reconfigure
it as an input, a 1 must be sent to the port . To use any of these ports as an input port, it must be
programmed.
Port 0 - pins 32 to 39 make up the 8-bit I/O port 0. However, if external memory is used, these lines are
used as a multiplexed address and data bus. However, if external memory is used, these lines are used as a
multiplexed address and data bus. It can be used for input or output, each pin must be connected
externally to a 10K ohm pull-up resistor .This is due to the fact that P0 is an open drain, unlike P1, P2, and
P3 .In order to make port 0 an input, the port must be programmed by writing 1 to all the bits Port 0 is also
designated as AD0-AD7, allowing it to be used for both address and data. When connecting an 8051/31 to
an external memory, port 0 provides both address and data
Port 1 - pins 1 to 8 make up the 8-bit I/O port 1. Port 1 can be used as input or output . In contrast to port
0, this port does not need any pull-up resistors since it already has pull-up resistors internally. Upon reset,
port 1 is configured as an input port
Port 2 - pins 21 to 28 make up the 8-bit I/O port 2. However, if external memory is used, these lines make
up the high-byte of the external address (A8 to A15). Port 2 can be used as input or output. Just like P1,
port 2 does not need any pull-up resistors since it already has pull-up resistors internally. Upon reset, port
2 is configured as an input port
Port 3 - pins 10 to 17 make up the 8-bit I/O port 3. Port 3 can be used as input or output. Port 3 does not
need any pull-up resistors. Port 3 is configured as an input port upon reset; this is not the way it is most
commonly used because each of these eight pins also has an alternate function, as detailed in the table
below.
RST - the reset input is on pin 9. This pin is used for resetting the 8051 (ie; loading the PC with the correct
startup value).
EA-bar - the external access, on pin 31, is used for enabling or disabling the on-chip ROM. When tied high
(5V), the 8051 executes instructions in internal ROM when executing in the lower 4K (8K for the 8052) of
memory. If tied low the 8051 will always execute instructions in external memory. The 8031 and 8032
should always have pin 31 tied low as there is no internal code memory.
ALE - the address latch enable is on pin 30. The ALE is used for latching the low byte of the address into an
external register.
PSEN-bar - the program store enable is an output signal on pin 29. This signal is used for fetching
instructions from external code memory.
Sometimes we need to access only 1 or 2 bits of the port. Instructions that are used for signal-bit
operations are as following
The JNB and JB instructions are widely used single-bit operations. They allow you to monitor a bit and
make a decision depending on whether it’s 0 or 1.These two instructions can be used for any bits of I/O
ports 0, 1, 2, and 3. Port 3 is typically not used for any I/O, either single-bit or byte-wise.
In reading a port :
Some instructions read the status of port pins. Others read the status of an internal port latch .Therefore,
when reading ports there are two possibilities:
� Read the status of the input pin
� Read the internal latch of the output port
Confusion between them is a major source of errors in 8051 programming . Especially where external
hardware is concerned .Some instructions read the contents of an internal port latch instead of reading
the status of an external pin .
For example, look at the ANL P1,A instruction
and the sequence of actions is executed as follow
1. It reads the internal latch of the port and brings that data into the CPU
2. This data is ANDed with the contents of register A
3. The result is rewritten back to the port latch
4. The port pin data is changed and now has the same value as port latch
Read-Modify-Write
The instructions read the port latch normally read a value, perform an operation then rewrite it back to the
port latch. The ports in 8051 can be accessed by the Read-modify-write technique .This feature saves
many lines of code by combining in a single instruction all three actions
SOME PROGRAMS
Port 0 is configured first as an input port by writing 1s to it, and then data is received from
that port and sent to P1
$MOD51
MOV A,#0FFH ;A=FF hex
MOV P0,A ;make P0 an i/p port by writing it all 1s
BACK: MOV A,P0 ;get data from P0
MOV P1,A ;send it to port 1
SJMP BACK ;keep doing it
END
The following code will continuously send out to port 1 the alternating value 55H and
AAH
$mod51
MOV P1,#00H
BACK: MOV A,#55H
MOV P1,A
ACALL DELAY
MOV A,#0AAH
MOV P1,A
ACALL DELAY
SJMP BACK
DELAY: MOV R2,#200
AGAIN: MOV R3,#250
HERE:
DJNZ R3,HERE
DJNZ R2,AGAIN
RET
END
Port 1 is configured first as an input port by writing 1s to it, then data is received from that
port and saved in R7 and R5
$MOD51
ORG 0H
MOV A,#0FFH ;A=FF hex
MOV P1,A ;make P1 an input port by writing it all 1s
MOV A,P1 ;get data from P1
MOV R7,A ;save it to in reg R7
ACALL DELAY ;wait
MOV A,P1 ;another data from P1
MOV R5,A ;save it to in reg R5
DELAY: MOV R2,#200
AGAIN: MOV R3,#250
HERE:
DJNZ R3,HERE
DJNZ R2,AGAIN
RET
END
Solution:
$MOD51
ORG 0H
SETB P1.2 ;make P1.2 an input
MOV A,#45H ;A=45H
AGAIN: JNB P1.2,AGAIN ; get out when P1.2=1
MOV P0,A ;issue A to P0
SETB P2.3 ;make P2.3 high
CLR P2.3 ;make P2.3 low for H-to-L
END
A switch is connected to pin P1.7. Write a program to check the status of SW and perform the
following:
(a) If SW=0, send letter ‘N’ to P2
(b) If SW=1, send letter ‘Y’ to P2
Solution:
$MOD51
ORG 0H
SETB P1.7 ;make P1.7 an input
AGAIN: JB P1.7,OVER ;jump if P1.7=1
MOV P2,#’N’ ;SW=0, issue ‘N’ to P2
SJMP AGAIN ;keep monitoring
OVER: MOV P2,#’Y’ ;SW=1, issue ‘Y’ to P2
SJMP AGAIN ;keep monitoring
END
8051 UART
Manish Man Shrestha
SMOD : Double baud rate bit. If Timer 1 is used to generate baud rate and SMOD = 1, the
baud rate is doubled when the serial port is used in modes 1, 2, or 3.
GF1 : General-purpose flag bit.
GF0 : General-purpose flag bit.
PD : Power Down bit. Setting this bit activates the Power Down operation in the 8051BH.
(Available only in CHMOS).
IDL : Idle Mode bit. Setting this bit activates Idle Mode operation in the 8051BH.
(Available only in CHMOS).
void timerDelay()
{
TH0 = 0X4B; //Load the timer value
TL0 = 0XFD;
TR0 = 1; //turn ON Timer zero
while(TF0 == 0); // Wait for Timer Overflow
TF0 = 0; //clear the timer Over flow flag
TR0 = 0;
}
void main()
{
TMOD = 0x01; //Timer0 mode 1
while(1)
{
LED = 1;
timerDelay();
LED = 0;
timerDelay();
}
}
void main()
{
TMOD = 0x01; //Timer0 mode 1
TH0 = 0X4B; //Load the timer value
TL0 = 0XFD;
TR0 = 1; //turn ON Timer zero
ET0 = 1; //Enable TImer0 Interrupt
EA = 1; //Enable Global Interrupt bit
while(1)
{
// Do nothing
}
}
Fosc = 11.0592Mhz
Delay = 250µs
RegValue = TimerMax-((Delay/1.085) * 10^6)
RegValue = 256 - (250µs/1.085)*10^6 = 256 - 230 = 26 = 0x1A
Physical
Integer A physical type contains values that represents
An integer type defines a type whose set of measurement of some physical quantity, like time,
values fall within a specified integer range. length, voltage or current
type INDEX is range 0 to 15; type Current is range 0 to 1000000000000
type WORD_LENGTH is range 31 downto 0; units
nA;
uA = 1000nA;
mA = 1000uA;
end units;
This result type for all relational operations is always the predefined type
BOOLEAN