MPMC Unit 1
MPMC Unit 1
examples, Microprocessor Unit versus Microcontroller Unit, CISC and RISC architectures.
8086 Architecture: Main features, pin diagram/description, 8086 microprocessor family, internal
architecture, bus interfacing unit, execution unit, interrupts and interrupt response, 8086 system timing,
minimum mode and maximum mode configuration.
***
Concept-1: Basic Microprocessor architecture, Harvard and Von Neumann architectures with examples
Concept-2: Microprocessor Unit versus Microcontroller Unit
Concept-3: CISC and RISC architectures
Concept-4: Main features of 8086mp
Concept-5: 8086 microprocessor family
Concept-6: Internal architecture
Concept-7: Pin diagram/description
Concept-8: Physical Memory Organization
Concept-9: Interrupts and interrupt response
Concept-10: 8086 system timing
Concept-11: Minimum mode and Maximum mode configuration
***
Concept-1: Basic Microprocessor architecture, Harvard and Von Neumann architectures with
examples
Introduction: A Microprocessor is a Digital Electronic Device used to perform several operations like data
transfer operations, arithmetic and logical operations and fabricated on a single Silicon integrated Circuit
(IC) Chip. It is used to fetch, decode and execute a given instruction.
Basics of Microprocessor –
A Microprocessor takes a bunch of instructions in machine language and executes them, telling the
processor what it has to do. Microprocessor performs three basic things while executing the instruction:
It performs some basic operations like addition, subtraction, multiplication, division, and some
logical operations using its Arithmetic and Logical Unit (ALU). New Microprocessors also perform
operations on floating-point numbers also.
Data in microprocessors can move from one location to another.
It has a Program Counter (PC) register that stores the address of the next instruction based on the
value of the PC, Microprocessor jumps from one location to another and takes decisions.
Page 1
Fig: A typical Microprocessor structure
Fixed Program Computers – Their function is very specific and they couldn’t be reprogrammed, e.g.
Calculators.
Stored Program Computers – These can be programmed to carry out many different tasks, applications are
stored on them, hence the name.
Modern computers are based on a stored-program concept introduced by John Von Neumann.
In this stored-program concept, programs and data are stored in a separate storage unit called
memories and are treated the same.
This novel idea meant that a computer built with this architecture would be much easier to
reprogram.
Page 2
It is also known as ISA (Instruction set architecture) computer and is having three basic units:
Page 3
PC (Program Counter) – This register contains the address of the next instruction to be executed.
CIR (Current Instruction Register) – This register contains the current instruction during
processing.
Buses – Data is transmitted from one part of a computer to another, connecting all major internal
components to the CPU and memory, by the means of Buses. Types:
Data Bus: It carries data among the memory unit, the I/O devices, and the processor.
Address Bus: It carries the address of data (not the actual data) between memory and processor.
Control Bus: It carries control commands from the CPU (and status signals from other devices) in
order to control and coordinate all the activities within the computer.
Von Neumann bottleneck –
Whatever we do to enhance performance, we cannot get away from the fact that instructions can only
be done one at a time and can only be carried out sequentially.
Both of these factors hold back the competence of the CPU.
This is commonly referred to as the ‘Von Neumann bottleneck’.
We can provide a Von Neumann processor with more cache, more RAM, or faster components but if
original gains are to be made in CPU performance then an influential inspection needs to take place
of CPU configuration.
This architecture is very important and is used in our PCs and even in Super Computers.
Harvard Architecture
In a normal computer that follows von Neumann architecture, instructions and data both are stored in the
same memory. So same buses are used to fetch instructions and data.
This means the CPU cannot do both things together (read the instruction and read/write data).
Harvard Architecture is the computer architecture that contains separate storage and separate buses
(signal path) for instruction and data.
It was basically developed to overcome the bottleneck of Von Neumann Architecture.
The main advantage of having separate buses for instruction and data is that the CPU can access
instructions and read/write data at the same time.
Structure of Harvard Architecture:
Page 4
Buses
Buses are used as signal pathways. In Harvard architecture, there are separate buses for both
instruction and data. Types of Buses:
Data Bus: It carries data among the main memory system, processor, and I/O devices.
Data Address Bus: It carries the address of data from the processor to the main memory
system.
Instruction Bus: It carries instructions among the main memory system, processor, and I/O
devices.
Instruction Address Bus: It carries the address of instructions from the processor to the
main memory system.
Operational Registers
There are different types of registers involved in it which are used for storing addresses of different
types of instructions.
For example, the Memory Address Register and Memory Data Register are operational registers.
Program Counter
It has the location of the next instruction to be executed. The program counter then passes this next
address to the memory address register.
Arithmetic and Logic Unit
The arithmetic logic unit is that part of the CPU that operates all the calculations needed. It performs
addition, subtraction, comparison, logical Operations, bit Shifting Operations, and various arithmetic
operations.
Control Unit
The Control Unit is the part of the CPU that operates all processor control signals. It controls the
input and output devices and also controls the movement of instructions and data within the system.
Input/Output System
Input devices are used to read data into main memory with the help of CPU input instruction. The
information from a computer as output is given through Output devices. The computer gives the
results of computation with the help of output devices.
In practice, Modified Harvard Architecture is used where we have two separate caches (data
and instruction). This is common and used in X86 and ARM processors.
Page 5
Buses (Signal One common signal path (bus) It uses separate buses for the transfer of
Paths) helps in the transfer of both both data and instructions.
instruction and data.
Number of It requires two clock cycles for It executes any instruction using only
Cycles executing a single instruction. one single cycle.
Cost It is comparatively cheaper in cost It is comparatively more expensive than
than Harvard Architecture. the Von Neumann Architecture.
Access to CPU The CPU is not able to read/write The CPU can easily read/write data as
data and access instructions at the well as access the instructions at any
same time. given time.
Uses This method comes to play in the This architecture is best for signal
case of small computers and processing as well as microcontrollers.
personal computers.
Requirement As compared to Harvard This one requires more hardware. It is
of Hardware Architecture, Von Neumann because it requires separate sets of data
Architecture requires lesser as well as address buses for individual
architecture. It is because it only memory.
needs to reach one common
memory.
Requirement This architecture basically requires This architecture comparatively requires
of Space less space. more space.
Usage of This architecture does not waste This type of architecture can result in
Space any space. It is because the space wastage. It is because the
instruction memory can utilize the instruction memory cannot utilize the
left space of the data memory. It leftover space in the data memory. It
can also happen vice-versa. also cannot happen vice-versa.
Execution The speed of execution of the Von The overall speed of execution of
Speed Neumann Architecture is Harvard Architecture is comparatively
comparatively slower. It is because faster. It is because the processor, in this
it is not capable of fetching the case, is capable of fetching both
instructions and data both at the instructions and data at the very same
same time. time.
Controlling The process of controlling becomes The process of controlling becomes
comparatively simpler with this comparatively complex with this
architecture. It is because it fetches architecture. It is because it basically
either instructions or data at any fetches both instructions and data
given time. simultaneously at the very same time.
Page 6
Integrated circuits or ICs are the electronic circuits used to construct the circuits which are smaller,
compact, quicker, and cheaper. The microprocessor and microcontroller are integrated circuits.
Microprocessor Microcontroller
Heart of the system. Heart of the embedded system.
Externally connected with input-output Input - output components are embedded.
components.
The circuit may be large depending upon usage. The circuit is very small.
Not cost-effective. Cost-effective.
The total consumption of power is high. Total consumption of power is less.
Power saving mode is not generally available. Power saving mode is generally offered.
Used in PC. Used in MP3 players, washing machines, etc.
Memories like RAM and ROM are absent. Carries RAM, ROM, etc.
Runs at a very high speed. Runs at a relatively lower speed.
It is complex and costly. Simple and cheap.
Example: DEC Alpha 21164, IBM RS6000, etc Example: Intel 8031/8051, PIC1x, etc.
Page 7
The fundamental goal of CISC is that a single instruction will handle all evaluating, loading, and storing
operations, similar to how a multiplication command will handle evaluating, loading, and storing data,
which is why it’s complicated.
Characteristics of CISC:
1. Instructions are complex, and thus it has complex instruction decoding.
2. The instructions may take more than one clock cycle in order to get executed.
3. The instruction is larger than one-word size.
4. Lesser general-purpose registers since the operations get performed only in the memory.
5. More data types.
6. Complex addressing modes.
Both CISC and RISC approaches primarily try to increase the performance of a CPU. Here is how both of
these work:
1. CISC: This kind of approach tries to minimize the total number of instructions per program, and it does
so at the cost of increasing the total number of cycles per instruction.
2. RISC: It reduces the cycles per instruction and does so at the cost of the total number of instructions per
program.
When programming was done in assembly language earlier, there was a desire to make the instructions
perform more tasks. It is because assembly programming was arduous and error-prone and led to the
evolution of CISC architecture. But as the dependency of high-level language on assembly language
decreased, RISC architecture prevailed.
Example
Suppose we need to add two different 8-bit numbers:
1. CISC approach: There would be a single instruction or command for this, such as ADD, that would
perform the task.
2. RISC approach: In this case, the programmer would write the very first load command in order to load
data in the registers. Then it would use a suitable operator and store the obtained result in the location that is
desired.
The add operation here is divided into parts, namely, operate, load, and store. Due to this, RISC programs
are much longer, and they require more memory to get stored, even though they require fewer transistors
because the commands are less complex.
Practice Problems in RISC and CISC Architecture
1. Both the RISC and CISC architectures have primarily been developed to reduce _____________.
a. Time delay
Page 8
b. Semantic gap
c. Cost
d. All of the above
Answer – (b) Semantic gap
2. Pipe-lining is the special feature of ____________.
a. IANA
b. ISA
c. CISC
d. RISC
Answer – (d) RISC
3. Which of these architectures is power efficient?
a. IANA
b. ISA
c. CISC
d. RISC
Answer – (d) RISC
Sample Questions From Concept-3:
1. Differentiate between RISC and CISC architectures.
2. Explain about RISC architecture.
3. Explain about CISC architecture
Page 10
2.93GHz – 3.33GHz
Generations of microprocessors:
First-generation –
From 1971 to 1972 the era of the first generation came which brought microprocessors like INTEL 4004
Rockwell international PPS-4 INTEL 8008 etc.
Second generation –
The second generation marked the development of 8-bit microprocessors from 1973 to 1978. Processors like
INTEL 8085 Motorola 6800 and 6801 etc came into existence.
Third generation –
The third generation brought forward the 16-bit processors like INTEL 8086/80186/80286 Motorola 68000
68010 etc. From 1979 to 1980 this generation used the HMOS technology.
Fourth generation –
The fourth-generation came into existence from 1981 to 1995. The 32-bit processors using HMOS
fabrication came into existence. INTEL 80386 and Motorola 68020 are some of the popular processors of
this generation.
Fifth-generation –
From 1995 till now we are in the fifth generation. 64-bit processors like PENTIUM, Celeron, dual, quad,
and octa-core processors came into existence.
Types of microprocessors :
Superscalar microprocessor –
These processors can perform many tasks at a time. They can be used for ALUs and multiplier-like arrays.
They have multiple operation units and perform tasks by executing multiple commands.
Page 11
Advantages of the microprocessor –
Disadvantages of microprocessors –
Intel 8086
o Intel 8086 microprocessor is the enhanced version of Intel 8085 microprocessor. It was designed by
Intel in 1976.
o The 8086 microprocessor is a16-bit, N-channel, HMOS microprocessor. Where the HMOS is used
for "High-speed Metal Oxide Semiconductor".
o Intel 8086 is built on a single semiconductor chip and packaged in a 40-pin IC package. The type of
package is DIP (Dual Inline Package).
o Intel 8086 uses 20 address lines and 16 data- lines. It can directly address up to 220 = 1 Mbyte of
memory.
o It consists of a powerful instruction set, which provides operation like division and multiplication
very quickly.
o 8086 is designed to operate in two modes, i.e., Minimum and Maximum mode.
Sample Questions From Concept-5:
3. Explain 8086 family
Page 12
8086 Microprocessor is divided into two functional units, i.e., EU (Execution Unit) and BIU (Bus Interface
Unit). It has the following functional parts −
EU (Execution Unit)
Execution unit gives instructions to BIU stating from where to fetch the data and then decode and execute
those instructions. Its function is to control operations on data using the instruction decoder & ALU. EU
has no direct connection with system buses as shown in the above figure, it performs operations over data
through BIU.
ALU
It handles all arithmetic and logical operations, like +, −, ×, /, OR, AND, NOT operations.
Flag Register
It is a 16-bit register that behaves like a flip-flop, i.e. it changes its status according to the result stored in
the accumulator. It has 9 flags and they are divided into 2 groups − Conditional Flags and Control Flags.
Conditional Flags:
It represents the result of the last arithmetic or logical instruction executed. Following is the list of
conditional flags −
Carry flag − This flag indicates an overflow condition for arithmetic operations.
Page 13
Auxiliary flag − When an operation is performed at ALU, it results in a carry/barrow from lower
nibble (i.e. D0 – D3) to upper nibble (i.e. D4 – D7), then this flag is set, i.e. carry given by D3 bit to
D4 is AF flag. The processor uses this flag to perform binary to BCD conversion.
Parity flag − This flag is used to indicate the parity of the result, i.e. when the lower order 8-bits of
the result contains even number of 1’s, then the Parity Flag is set. For odd number of 1’s, the Parity
Flag is reset.
Zero flag − This flag is set to 1 when the result of arithmetic or logical operation is zero else it is set
to 0.
Sign flag − This flag holds the sign of the result, i.e. when the result of the operation is negative,
then the sign flag is set to 1 else set to 0.
Overflow flag − This flag represents the result when the system capacity is exceeded.
Control Flags:
Control flags controls the operations of the execution unit. Following is the list of control flags −
Trap flag − It is used for single step control and allows the user to execute one instruction at a time
for debugging. If it is set, then the program can be run in a single step mode.
Interrupt flag − It is an interrupt enable/disable flag, i.e. used to allow/prohibit the interruption of a
program. It is set to 1 for interrupt enabled condition and set to 0 for interrupt disabled condition.
Direction flag − It is used in string operation. As the name suggests when it is set then string bytes
are accessed from the higher memory address to the lower memory address and vice-a-versa.
Register Organization of 8086 :
General purpose register:
There are 8 general purpose registers, i.e., AH, AL, BH, BL, CH, CL, DH, and DL. These registers can be
used individually to store 8-bit data and can be used in pairs to store 16bit data. The valid register pairs are
AH and AL, BH and BL, CH and CL, and DH and DL. It is referred to the AX, BX, CX, and DX
respectively.
AX register − It is also known as accumulator register. It is used to store operands for arithmetic
operations.
BX register − It is used as a base register. It is used to store the starting base address of the memory
area within the data segment.
CX register − It is referred to as counter. It is used in loop instruction to store the loop counter.
DX register − This register is used to hold I/O port address for I/O instruction.
Stack pointer register:
It is a 16-bit register, which holds the address from the start of the segment to the memory location, where a
word was most recently stored on the stack.
BIU (Bus Interface Unit)
BIU takes care of all data and addresses transfers on the buses for the EU like sending addresses, fetching
instructions from the memory, reading data from the ports and the memory as well as writing data to the
ports and the memory.
EU (Execution Unit)
EU has no direction connection with System Buses so this is possible with the BIU. EU and BIU are
connected with the Internal Bus.
It has the following functional parts −
Instruction queue − BIU contains the instruction queue. BIU gets upto 6 bytes of next instructions
and stores them in the instruction queue. When EU executes instructions and is ready for its next
instruction, then it simply reads the instruction from this instruction queue resulting in increased
execution speed.
Fetching the next instruction while the current instruction executes is called pipelining.
Segment register − BIU has 4 segment buses, i.e. CS, DS, SS& ES. It holds the addresses of
instructions and data in memory, which are used by the processor to access memory locations. It
also contains 1 pointer register IP, which holds the address of the next instruction to executed by the
EU.
o CS − It stands for Code Segment. It is used for addressing a memory location in the code
segment of the memory, where the executable program is stored.
Page 14
oDS − It stands for Data Segment. It consists of data used by the program andis accessed in
the data segment by an offset address or the content of other register that holds the offset
address.
o SS − It stands for Stack Segment. It handles memory to store data and addresses during
execution.
o ES − It stands for Extra Segment. ES is additional data segment, which is used by the string
to hold the extra destination data.
Instruction pointer − It is a 16-bit register used to hold the address of the next instruction to be
executed.
Page 15
RESET
It is available at pin 21 and is used to restart the execution. It causes the processor to immediately terminate
its present activity. This signal is active high for the first 4 clock cycles to RESET the microprocessor.
INTR
It is available at pin 18. It is an interrupt request signal, which is sampled during the last clock cycle of each
instruction to determine if the processor considered this as an interrupt or not.
NMI
It stands for non-maskable interrupt and is available at pin 17. It is an edge triggered input, which causes an
interrupt request to the microprocessor.
$\overline{TEST}$
This signal is like wait state and is available at pin 23. When this signal is high, then the processor has to
wait for IDLE state, else the execution continues.
MN/$\overline{MX}$
It stands for Minimum/Maximum and is available at pin 33. It indicates what mode the processor is to
operate in; when it is high, it works in the minimum mode and vice-aversa.
INTA
It is an interrupt acknowledgement signal and id available at pin 24. When the microprocessor receives this
signal, it acknowledges the interrupt.
ALE
It stands for address enable latch and is available at pin 25. A positive pulse is generated each time the
processor begins any operation. This signal indicates the availability of a valid address on the address/data
lines.
DEN
It stands for Data Enable and is available at pin 26. It is used to enable Transreceiver 8286. The
transreceiver is a device used to separate data from the address/data bus.
DT/R
It stands for Data Transmit/Receive signal and is available at pin 27. It decides the direction of data flow
through the transreceiver. When it is high, data is transmitted out and vice-a-versa.
M/IO
This signal is used to distinguish between memory and I/O operations. When it is high, it indicates I/O
operation and when it is low indicates the memory operation. It is available at pin 28.
WR
It stands for write signal and is available at pin 29. It is used to write the data into the memory or the output
device depending on the status of M/IO signal.
HLDA
It stands for Hold Acknowledgement signal and is available at pin 30. This signal acknowledges the HOLD
signal.
HOLD
This signal indicates to the processor that external devices are requesting to access the address/data buses.
It is available at pin 31.
QS1 and QS0
These are queue status signals and are available at pin 24 and 25. These signals provide the status of
instruction queue. Their conditions are shown in the following table −
S0, S1, S2
Page 16
These are the status signals that provide the status of operation, which is used by the Bus Controller 8288 to
generate memory & I/O control signals. These are available at pin 26, 27, and 28. Following is the table
showing their status −
LOCK
When this signal is active, it indicates to the other processors not to ask the CPU to leave the system bus. It
is activated using the LOCK prefix on any instruction and is available at pin 29.
RQ/GT1 and RQ/GT0
These are the Request/Grant signals used by the other processors requesting the CPU to release the system
bus. When the signal is received by CPU, then it sends acknowledgment. RQ/GT 0 has a higher priority than
RQ/GT1.
Page 17
Ex: Segment address-------→ 1005H
Offset address ----------→ 5555H
Segment address -------→ 1005H-------0001 0000 0000 0101
Shifted left by 4 Positions ------0001 0000 0000 0101 0000
+
Offset address --- 5555H ------ 0101 0101 0101 0101
Page 18
0 0 16 bits of data will be read or written into the memory
1 1 No operation is performed
Page 19
and are addressed in parallel by the
processor.
https://www.studocu.com/in/document/apj-abdul-kalam-technological-university/computer-
networks/microprocessor-notes/21669451
0Hardware Interrupts
Hardware interrupt is caused by any peripheral device by sending a signal through a specified pin to
the microprocessor. The 8086 has two hardware interrupt pins, i.e. NMI and INTR. NMI is a non-maskable
interrupt and INTR is a maskable interrupt having lower priority. One more interrupt pin associated is
INTA called interrupt acknowledge.
NMI
It is a single non-maskable interrupt pin (NMI) having higher priority than the maskable interrupt
request pin (INTR)and it is of type 2 interrupt.
When this interrupt is activated, these actions take place −
Completes the current instruction that is in progress.
Pushes the Flag register values on to the stack.
Pushes the CS (code segment) value and IP (instruction pointer) value of the return address on to the
stack.
IP is loaded from the contents of the word location 00008H.
CS is loaded from the contents of the next word location 0000AH.
Interrupt flag and trap flag are reset to 0.
INTR
The INTR is a maskable interrupt because the microprocessor will be interrupted only if interrupts
are enabled using set interrupt flag instruction. It should not be enabled using clear interrupt Flag
instruction. The INTR interrupt is activated by an I/O port. If the interrupt is enabled and NMI is disabled,
then the microprocessor first completes the current execution and sends ‘0’ on INTA pin twice. The first
‘0’ means INTA informs the external device to get ready and during the second ‘0’ the microprocessor
receives the 8 bit, say X, from the programmable interrupt controller.
Page 20
These actions are taken by the microprocessor −
First completes the current instruction.
Activates INTA output and receives the interrupt type, say X.
Flag register value, CS value of the return address and IP value of the return address are pushed on
to the stack.
IP value is loaded from the contents of word location X × 4
CS is loaded from the contents of the next word location.
Interrupt flag and trap flag is reset to 0
Software Interrupts
Some instructions are inserted at the desired position into the program to create interrupts. These
interrupt instructions can be used to test the working of various interrupt handlers. It includes −
INT- Interrupt instruction with type number
It is 2-byte instruction. First byte provides the op-code and the second byte provides the interrupt type
number. There are 256 interrupt types under this group.
Its execution includes the following steps −
Flag register value is pushed on to the stack.
CS value of the return address and IP value of the return address are pushed on to the stack.
IP is loaded from the contents of the word location ‘type number’ × 4
CS is loaded from the contents of the next word location.
Interrupt Flag and Trap Flag are reset to 0
The starting address for type0 interrupt is 000000H, for type1 interrupt is 00004H similarly for type2 is
00008H and ……so on. The first five pointers are dedicated interrupt pointers. i.e. −
TYPE 0 interrupt represents division by zero situation.
TYPE 1 interrupt represents single-step execution during the debugging of a program.
TYPE 2 interrupt represents non-maskable NMI interrupt.
TYPE 3 interrupt represents break-point interrupt.
TYPE 4 interrupt represents overflow interrupt.
The interrupts from Type 5 to Type 31 are reserved for other advanced microprocessors, and interrupts
from 32 to Type 255 are available for hardware and software interrupts.
INT 3-Break Point Interrupt Instruction. It is a 1-byte instruction having op-code is CCH. These
instructions are inserted into the program so that when the processor reaches there, then it stops the normal
execution of program and follows the break-point procedure.
Its execution includes the following steps −
Flag register value is pushed on to the stack.
CS value of the return address and IP value of the return address are pushed on to the stack.
IP is loaded from the contents of the word location 3×4 = 0000CH
CS is loaded from the contents of the next word location.
Interrupt Flag and Trap Flag are reset to 0
INTO - Interrupt on overflow instruction
It is a 1-byte instruction and their mnemonic INTO. The op-code for this instruction is CEH. As the name
suggests it is a conditional interrupt instruction, i.e. it is active only when the overflow flag is set to 1 and
branches to the interrupt handler whose interrupt type number is 4. If the overflow flag is reset then, the
execution continues to the next instruction.
Its execution includes the following steps −
Flag register values are pushed on to the stack.
CS value of the return address and IP value of the return address are pushed on to the stack.
IP is loaded from the contents of word location 4×4 = 00010H
CS is loaded from the contents of the next word location.
Interrupt flag and Trap flag are reset to 0
For every interrupt, there must be an interrupt service routine (ISR), or interrupt handler. When an
interrupt is invoked, the microprocessor runs the interrupt service routine. For every interrupt, there is a
fixed location in memory that holds the address of its ISR. The group of memory locations set aside to hold
the addresses of ISRs is called the interrupt vector table.
Page 21
When an interrupt is occurred, the microprocessor stops execution of current instruction. It transfers the
content of program counter into stack. It also stores the current status of the interrupts internally but not on
stack. After this, it jumps to the memory location specified by Interrupt Vector Table (IVT). After that the
code written on that memory area will execute.
Page 22
Concept-10: 8086 system timing
The bus cycle is also named as machine cycle. Bus cycle of 8086 is used to access memory, peripheral
devices (Input/Output devices), and Interrupt controller. Bus cycle corresponds to a sequence of events that
starts with an address being output on system address bus followed by a write or read data transfer. During
these operations, a series of control signals are also produced by microprocessor to control direction and
timing of bus.
There are at least four clock periods in a bus cycle of 8086 microprocessor. These four clock periods are
called T1, T2, T3 and T4 states.
These four clock states gives bus cycle duration T of 200 ns *4 = 800 ns in 5-MHz 8086 system.
Read Cycle :
When a read cycle is to be performed, during T1 microprocessor puts an address on address bus, and then
bus is put in high impedance state during T2 state. Data to be read must be out on bus during T3 and T4.
During T3 bus is made “reserved for data in” and finally data is read during T4.
Page 23
Write Cycle :
In case of write memory cycle, during T1 state microprocessor puts an address on address bus. Data is put
on data bus by CPU during T2 state and maintained during T3 and T4 states, that is written out to memory
or I/O devices.
Page 24
The microprocessor 8086 is operated in minimum mode by strapping its MN/MX pin to logic 1.
In this mode, all the control signals are given out by the microprocessor chip itself.
There is a single microprocessor in the minimum mode system.
The remaining components in the system are latches, transceivers, clock generator, memory and I/O
devices.
Latches are generally buffered output D-type flip-flops like 8282. They are used for separating the
valid address from the multiplexed address/data signals and are controlled by the ALE signal
generated by 8086.
Transceivers are the bidirectional buffers and some times they are called as data amplifiers. They are
required to separate the valid data from the time multiplexed address/data signals. They are
controlled by two signals namely, DEN and DT/R.
The DEN signal indicates the direction of data, i.e. from or to the processor.
The system contains memory for the monitor and users program storage. Usually, EPROM are used
for monitor storage, while RAM for users program storage. A system may contain I/O devices.
The opcode fetch and read cycles are similar. Hence the timing diagram can be categorized in two
parts, the first is the timing diagram for read cycle and the second is the timing diagram for write
cycle.
Read & Write Cycles:
The read cycle begins in T1 with the assertion of address latch enable (ALE) signal and also M / IO
signal. During the negative going edge of this signal, the valid address is latched on the local bus.
The BHE and A0 signals address low, high or both bytes. From T1 to T4 , the M/IO signal indicates
a memory or I/O operation.
At T2, the address is removed from the local bus and is sent to the output. The bus is then tristated.
The read (RD) control signal is also activated in T2.
The read (RD) signal causes the address device to enable its data bus drivers. After RD goes low, the
valid data is available on the data bus.
The addressed device will drive the READY line high. When the processor returns the read signal to
high level, the addressed device will again tristate its bus drivers. A write cycle also begins with the
assertion of ALE and the emission of the address.
Page 25
The M/IO signal is again asserted to indicate a memory or I/O operation. In T2, after sending the
address in T1, the processor sends the data to be written to the addressed location.
The data remains on the bus until middle of T4 state. The WR becomes active at the beginning of T2
(unlike RD is somewhat delayed in T2 to provide time for floating).
The BHE and A0 signals are used to select the proper byte or bytes of memory or I/O word to be
read or write.
Page 26
In the maximum mode, the 8086 is operated by strapping the MN/MX pin to ground.
In this mode, the processor derives the status signal S2, S1, S0. Another chip called bus controller
derives the control signal using this status information.
In the maximum mode, there may be more than one microprocessor in the system configuration. The
components in the system are same as in the minimum mode system.
The basic function of the bus controller chip IC8288, is to derive control signals like RD and WR
( for memory and I/O devices), DEN, DT/R, ALE etc. using the information by the processor on the
status lines.
The bus controller chip has input lines S2, S1, S0 and CLK. These inputs to 8288 are driven by CPU.
It derives the outputs ALE, DEN, DT/R, MRDC, MWTC, AMWC, IORC, IOWC and AIOWC. The
AEN, IOB and CEN pins are specially useful for multiprocessor systems.
AEN and IOB are generally grounded. CEN pin is usually tied to +5V. The significance of the
MCE/PDEN output depends upon the status of the IOB pin.
INTA pin used to issue two interrupt acknowledge pulses to the interrupt controller or to an
interrupting device.
IORC, IOWC are I/O read command and I/O write command signals respectively . These signals
enable an IO interface to read or write the data from or to the address port.
The MRDC, MWTC are memory read command and memory write command signals respectively
and may be used as memory read or write signals.
All these command signals instructs the memory to accept or send data from or to the bus.
Here the only difference between in timing diagram between minimum mode and maximum mode is
the status signals used and the available control and advanced command signals.
Read & Write Cycles:
S0, S1, S2 are set at the beginning of bus cycle.8288 bus controller will output a pulse as on the ALE
and apply a required signal to its DT / R pin during T1.
In T2, 8288 will set DEN=1 thus enabling transceivers, and for an input it will activate MRDC or
IORC. These signals are activated until T4.
For an output, the AMWC or AIOWC is activated from T2 to T4 and MWTC or IOWC is activated
from T3 to T4.
The status bit S0 to S2 remains active until T3 and become passive during T3 and T4.
If reader input is not activated before T3, wait state will be inserted between T3 and T4.
Page 27
Fig: Maximum mode Read Cycle
Page 28
The registers AX, BX, CX, and DX are the general 16-bit registers.
AX Register: Accumulator register consists of two 8-bit registers AL and AH, which
can be combined together and used as a 16- bit register AX. AL in this case contains the low-order byte of
the word, and AH contains the high-order byte. Accumulator can be used for I/O operations, rotate and
string manipulation.
BX Register: This register is mainly used as a base register. It holds the starting base location of a memory
region within a data segment. It is used as offset storage for forming physical address in case of certain
addressing mode.
CX Register: It is used as default counter or count register in case of string and loop
instructions.
DX Register: Data register can be used as a port number in I/O operations and implicit operand or
destination in case of few instructions. In integer 32-bit multiply and divide instruction the DX register
contains high-order word of the initial or resulting number.
Segment registers:
To complete 1Mbyte memory is divided into 16 logical segments. Each segment contains 64Kbyte of
memory. There are four segment registers.
Code segment (CS) is a 16-bit register containing address of 64 KB segment with
processor instructions. The processor uses CS segment for all accesses to instructions referenced by
instruction pointer (IP) register. CS register cannot be changed directly.
The CS register is automatically updated during far jump, far call and far return
instructions. It is used for addressing a memory location in the code segment of the
memory, where the executable program is stored.
Stack segment (SS) is a 16-bit register containing address of 64KB segment with
program stack. By default, the processor assumes that all data referenced by the stack pointer (SP) and base
pointer (BP) registers is located in the stack segment. SS register can be changed directly using POP
instruction. It is used for addressing stack segment of memory. The stack segment is that segment of
memory, which is used to store stack data.
Data segment (DS) is a 16-bit register containing address of 64KB segment with
program data. By default, the processor assumes that all data referenced by general registers (AX, BX, CX,
DX) and index register (SI, DI) is located in the data segment. DS register can be changed directly using
POP and LDS instructions. It points to the data segment memory where the data is resided.
Extra segment (ES) is a 16-bit register containing address of 64KB segment, usually with program data. By
default, the processor assumes that the DI register references the ES segment in string manipulation
instructions. ES register can be changed directly using POP and LES instructions. It also refers to segment
which essentially is another data segment of the memory. It also contains data.
Pointers and index registers.
The pointers contain within the particular segments. The pointers IP, BP, SP
usually contain offsets within the code, data and stack segments respectively
Stack Pointer (SP) is a 16-bit register pointing to program stack in stack segment.
Base Pointer (BP) is a 16-bit register pointing to data in stack segment. BP register is usually used for based,
based indexed or register indirect addressing.
Source Index (SI) is a 16-bit register. SI is used for indexed, based indexed and register indirect addressing,
as well as a source data addresses in string manipulation instructions.
Destination Index (DI) is a 16-bit register. DI is used for indexed, based indexed and register indirect
addressing, as well as a destination data address in string manipulation instructions.
Conditional Flags
Page 29
Conditional flags are as follows:
Carry Flag (CY): This flag indicates an overflow condition for unsigned integer
arithmetic. It is also used in multiple-precision arithmetic.
Auxiliary Flag (AC): If an operation performed in ALU generates a carry/barrow from lower nibble (i.e. D0
– D3) to upper nibble (i.e. D4 – D7), the AC flag is set i.e. carry given by D3 bit to D4 is AC flag. This is
not a general-purpose flag, it is used internally by the Processor to perform Binary to BCD conversion.
Parity Flag (PF): This flag is used to indicate the parity of result. If lower order 8-bits of the result contains
even number of 1’s, the Parity Flag is set and for odd number of 1’s, the Parity flag is reset.
Zero Flag (ZF): It is set; if the result of arithmetic or logical operation is zero else it is reset.
Sign Flag (SF): In sign magnitude format the sign of number is indicated by MSB bit. If the result of
operation is negative, sign flag is set.
Control Flags:
Control flags are set or reset deliberately to control the operations of the execution unit.
Control flags are as follows:
Trap Flag (TF): It is used for single step control. It allows user to execute one
instruction of a program at a time for debugging. When trap flag is set, program can be run in single step
mode.
Interrupt Flag (IF): It is an interrupt enable/disable flag. If it is set, the maskable
interrupt of 8086 is enabled and if it is reset, the interrupt is disabled. It can be set by executing instruction
sit and can be cleared by executing CLI instruction.
Direction Flag (DF): It is used in string operation. If it is set, string bytes are accessed from higher memory
address to lower memory address. When it is reset, the string bytes are accessed from lower memory address
to higher memory address.
6. Draw the minimum mode pin diagram and explain the function of each pin in detail.
Page 30
Clock signal is provided through Pin-19. It provides timing to the processor for operations. Its frequency is
different for different versions, i.e. 5MHz, 8MHz and 10MHz.
Address/data bus
AD0-AD15. These are 16 address/data bus. AD0-AD7 carries low order byte data and AD8AD15 carries
higher order byte data. During the first clock cycle, it carries 16-bit address and after that it carries 16-bit
data.
Address/status bus
A16-A19/S3-S6. These are the 4 address/status buses. During the first clock cycle, it carries 4-bit address
and later it carries status signals.
S7/BHE
BHE stands for Bus High Enable. It is available at pin 34 and used to indicate the transfer of data using data
bus D8-D15. This signal is low during the first clock cycle, thereafter it is active.
Read($\overline{RD}$)
It is available at pin 32 and is used to read signal for Read operation.
Ready
It is available at pin 22. It is an acknowledgement signal from I/O devices that data is transferred. It is an
active high signal. When it is high, it indicates that the device is ready to transfer data. When it is low, it
indicates wait state.
RESET
It is available at pin 21 and is used to restart the execution. It causes the processor to immediately terminate
its present activity. This signal is active high for the first 4 clock cycles to RESET the microprocessor.
INTR
It is available at pin 18. It is an interrupt request signal, which is sampled during the last clock cycle of each
instruction to determine if the processor considered this as an interrupt or not.
NMI
It stands for non-maskable interrupt and is available at pin 17. It is an edge triggered input, which causes an
interrupt request to the microprocessor.
$\overline{TEST}$
This signal is like wait state and is available at pin 23. When this signal is high, then the processor has to
wait for IDLE state, else the execution continues.
MN/$\overline{MX}$
It stands for Minimum/Maximum and is available at pin 33. It indicates what mode the processor is to
operate in; when it is high, it works in the minimum mode and vice-aversa.
INTA
It is an interrupt acknowledgement signal and id available at pin 24. When the microprocessor receives this
signal, it acknowledges the interrupt.
ALE
It stands for address enable latch and is available at pin 25. A positive pulse is generated each time the
processor begins any operation. This signal indicates the availability of a valid address on the address/data
lines.
DEN
It stands for Data Enable and is available at pin 26. It is used to enable Transreceiver 8286. The
transreceiver is a device used to separate data from the address/data bus.
DT/R
It stands for Data Transmit/Receive signal and is available at pin 27. It decides the direction of data flow
through the transreceiver. When it is high, data is transmitted out and vice-a-versa.
M/IO
This signal is used to distinguish between memory and I/O operations. When it is high, it indicates I/O
operation and when it is low indicates the memory operation. It is available at pin 28.
WR
It stands for write signal and is available at pin 29. It is used to write the data into the memory or the output
device depending on the status of M/IO signal.
HLDA
Page 31
It stands for Hold Acknowledgement signal and is available at pin 30. This signal acknowledges the HOLD
signal.
HOLD
This signal indicates to the processor that external devices are requesting to access the address/data buses.
It is available at pin 31.
7. Draw the flag register of 8086 microprocessor and explain the function of each flag.
Conditional Flags
Conditional flags are as follows:
Carry Flag (CY): This flag indicates an overflow condition for unsigned integer
arithmetic. It is also used in multiple-precision arithmetic.
Auxiliary Flag (AC): If an operation performed in ALU generates a carry/barrow from lower nibble (i.e. D0
– D3) to upper nibble (i.e. D4 – D7), the AC flag is set i.e. carry given by D3 bit to D4 is AC flag. This is
not a general-purpose flag, it is used internally by the Processor to perform Binary to BCD conversion.
Parity Flag (PF): This flag is used to indicate the parity of result. If lower order 8-bits of the result contains
even number of 1’s, the Parity Flag is set and for odd number of 1’s, the Parity flag is reset.
Zero Flag (ZF): It is set; if the result of arithmetic or logical operation is zero else it is reset.
Sign Flag (SF): In sign magnitude format the sign of number is indicated by MSB bit. If the result of
operation is negative, sign flag is set.
Control Flags:
Control flags are set or reset deliberately to control the operations of the execution unit.
Control flags are as follows:
Trap Flag (TF): It is used for single step control. It allows user to execute one
instruction of a program at a time for debugging. When trap flag is set, program can be run in single step
mode.
Interrupt Flag (IF): It is an interrupt enable/disable flag. If it is set, the maskable
interrupt of 8086 is enabled and if it is reset, the interrupt is disabled. It can be set by executing instruction
sit and can be cleared by executing CLI instruction.
Direction Flag (DF): It is used in string operation. If it is set, string bytes are accessed from higher memory
address to lower memory address. When it is reset, the string bytes are accessed from lower memory address
to higher memory address.
8. Define interrupt and explain the interrupt service routine in 8086 microprocessor.
PART-A Q&A
1. Differentiate between minimum and maximum mode operations of 8086 microprocessor.
Page 32
Minimum mode Maximum mode
In minimum mode there can be only one In maximum mode there can be multiple processors
processor i.e. 8086. with 8086, like 8087 and 8089.
ALE for the latch is given by 8086 as it is the ALE for the latch is given by 8288 bus controller as
only processor in the circuit. there can be multiple processors in the circuit.
DEN and DT/R for the trans-receivers are given DEN and DT/R for the trans-receivers are given by
by 8086 itself. 8288 bus controller.
Direct control signals M/IO, RD and WR are Instead of control signals, each processor generates
given by 8086. status signals called S2, S1 &S0.
Control signals M/IO, RD and WR are decoded Status signals S2, S1 &S0 are decoded by a bus
by a 3:8 decoder like 74138. controller like 8288 to produce control signals.
INTA is given by 8086 in response to an interrupt INTA is given by 8288 bus controller in response to
on INTR line. an interrupt on INTR line.
HOLD and HLDA signals are used for bus RQ /GT lines are used for bus requests by other
request with a DMA controller like 8237. processors like 8087 or 8089.
Multiprocessing cannot be performed hence As multiprocessing can be performed, it can give very
performance is lower. high performance.
2. What is the use of memory segmentation in 8086 microprocessor?
Segmentation is the process in which the main memory of the computer is divided into different segments
and each segment has its own base address. It is basically used to enhance the speed of execution of the
computer system, so that processor is able to fetch and execute the data from the memory easily and fast.
Need for Segmentation –
The Bus Interface Unit (BIU) contains four 16 bit special purpose registers (mentioned below) called as
Segment Registers.
Code segment register (CS): is used for addressing memory location in the code segment of the memory,
where the executable program is stored.
Data segment register (DS): points to the data segment of the memory where the data is stored.
Extra Segment Register (ES): also refers to a segment in the memory which is another data segment in
the memory.
Stack Segment Register (SS): is used for addressing stack segment of the memory. The stack segment is
that segment of memory which is used to store stack data.
The number of address lines in 8086 is 20, 8086 BIU will send 20bit address, so as to access one of the 1MB
memory locations. The four segment registers actually contain the upper 16 bits of the starting addresses of
the four memory segments of 64 KB each with which the 8086 is working at that instant of time. A segment
is a logical unit of memory that may be up to 64 kilobytes long. Each segment is made up of contiguous
memory locations. It is independent, separately addressable unit. Starting address will always be changing. It
will not be fixed. Note that the 8086 does not work the whole 1MB memory at any given time. However it
works only with four 64KB segments within the whole 1MB memory.
Bellow is the one way of positioning four 64 kilobyte segments within the 1M byte memory space of an
8086.
Page 33
Types of Segmentation –
1. Overlapping Segment – A segment starts at a particular address and its maximum size can go up to
64kilobytes. But if another segment starts along this 64kilobytes location of the first segment, then the two
are said to be Overlapping Segment.
2. Non-Overlapped Segment – A segment starts at a particular address and its maximum size can go up to
64kilobytes. But if another segment starts before this 64kilobytes location of the first segment, then the two
segments are said to be Non-Overlapped Segment.
Advantages of the Segmentation The main advantages of segmentation are as follows:
It provides a powerful memory management mechanism.
Data related or stack related operations can be performed in different segments.
Code related operation can be done in separate code segments.
It allows to processes to easily share data.
It allows to extend the address ability of the processor, i.e. segmentation allows the use of 16 bit
registers to give an addressing capability of 1 Megabytes. Without segmentation, it would require 20
bit registers.
It is possible to enhance the memory size of code data or stack segments beyond 64 KB by allotting
more than one segment for each area.
3. List and explain the machine control flags of 8086 microprocessor.
In 8086 there are 3 different flags which are used to enable or disable some basic operations of the
microprocessor. These flags and their functions are listed below.
Flag Bit Function
D This is directional flag. This is used in string related operations. D = 1, then the string will be
accessed from higher memory address to lower memory address, and if D = 0, it will do the
reverse.
I This is interrupt flag. If I = 1, then MPU will recognize the interrupts from peripherals. For I = 0,
the interrupts will be ignored
T This trap flag is used for on-chip debugging. When T = 1, it will work in a single step mode.
Page 34
Flag Bit Function
After each instruction, one internal interrupt is generated. It helps to execute some program
instruction by instruction.
4. Explain the functions of ALE, READY, HOLD, and BHE pins of 8086 microprocessor.
ALE
It stands for address enable latch and is available at pin 25. A positive pulse is generated each time the
processor begins any operation. This signal indicates the availability of a valid address on the address/data
lines.
Ready
It is available at pin 22. It is an acknowledgement signal from I/O devices that data is transferred. It is an
active high signal. When it is high, it indicates that the device is ready to transfer data. When it is low, it
indicates wait state.
HOLD
This signal indicates to the processor that external devices are requesting to access the address/data buses.
It is available at pin 31.
BHE
BHE stands for Bus High Enable. It is available at pin 34 and used to indicate the transfer of data using data
bus D8-D15. This signal is low during the first clock cycle, thereafter it is active.
A microprocessor is a Digital electronic device used to perform several operations like data transfer
operations, arithmetic and logical operations developed on a single chip. It is used for fetching, decoding
and execution of given instruction.
Importance:
A device that uses a microprocessor is normally capable of many functions, such as word processing,
calculation, and communication via Internet or telephone. However, for the device to work properly, the
microprocessor itself has to communicate with other parts of the device. For example, a microprocessor
would need to communicate with the video display to control the output data that a program may produce.
Therefore, a microprocessor would act as device's "brain" in that it transmits, receives and interprets the data
needed to operate a device.
Page 35
UNIT-II: 8086 PROGRAMMING: Program development steps, instructions, addressing modes, assembler
directives, writing simple programs with an assembler, assembly language program development tools.
Unit Outcomes:
At the end of this unit you will learn:
1. Write a task list, flow chart or pseudo code for simple programming problem.
2. Write code, assemble and run a very simple assembly language program.
3. Describe the use of program development tools such as editors, assemblers, linkers, locators,
debuggers and emulators.
4. Properly document assembly language programs
Introduction:
What is Assembly Language?
An assembly language is a low-level programming language for microprocessors and other
programmable devices.
Each personal computer has a microprocessor that manages the computer's arithmetical, logical, and
control activities.
Each family of processors has its own set of instructions for handling various operations such as
getting input from keyboard, displaying information on screen and performing various other jobs.
These set of instructions are called 'machine language instructions'.
A processor understands only machine language instructions, which are strings of 1's and 0's.
An assembly language implements a symbolic representation of the machine code needed to
program a given CPU architecture.
Why you should learn Assembly Language?
The learning of assembly language is still important for programmers.
It helps in taking complete control over the system and its resources.
By learning assembly language, the programmer is able to write the code to access registers and able
to retrieve the memory address of pointers and values.
It mainly helps in speed optimization that increases efficiency and performance.
Advantages of Assembly Language:
Page 36
1. It allows complex jobs to run in a simpler way.
2. It is memory efficient, as it requires less memory.
3. It is faster in speed, as its execution time is less.
4. It is mainly hardware oriented.
5. It requires less instruction to get the result.
6. It is used for critical jobs.
7. It is not required to keep track of memory locations.
8. It is a low-level embedded system.
Disadvantages of Assembly Language:
1. It takes a lot of time and effort to write the code for the same.
2. It is very complex and difficult to understand.
3. The syntax is difficult to remember.
4. It has a lack of portability of program between different computer architectures.
Concept-1
Program development steps:
Identify the problem that you want to solve. Just ask yourself question that “What do I really want this
program to do?” for solution you would have to follow the things.
I. Representing program operations
II. Finding the right instructions
III. Writing a program
I. Representing program operations:
Formula or sequence of operations used to solve a programming problem is called as the algorithm.
There are two ways of representing algorithms:
a) Flowchart
b) Structured programming and pseudo code
a) Flow Chart:
It uses graphical shapes to represent different types of programming operations.
Flow chart symbols
Page 37
• Bit manipulation Instruction
• String Instruction
• Program execution transfer Instruction
• Processor control Instruction
Concept-2
ADDRESSING MODES OF 8086
What is an Addressing mode?
The term addressing modes refers to the way in which the operand of an instruction is specified.
The addressing mode specifies a rule for explain or modifying the address field of the instruction
before the operand is actually executed.
Example:
ADDRESSING MODES
The different ways in which a source operand is denoted in an instruction is known as addressing modes.
There are 9 different addressing modes in 8086 programming −
Instruction
Data Operand
2. REGISTER ADDRESSING MODE
It means that the register is the source of an operand for an instruction.
Example:
MOV CX, AX ; ADD BX, AX
Instruction
Register Operand (source & destination)
3. DIRECT ADDRESSING MODE
The addressing mode in which the effective address of the memory location is written directly in the
instruction.
Example: MOV AX, [1592H] ; MOV AL, [0300H]
Instruction
Direct Address
4. REGISTER INDIRECT ADDRESSING MODE
This addressing mode allows data to be addressed at any memory location through an offset address
held in any of the following registers: BP, BX, DI & SI.
Instruction
Indirectly specifying the address which is
Stored in the register
Explanation:
Suppose the register BX contains 4895H, then the contents 4895H are moved to AX reg.
5. BASED ADDRESSING MODE
In this addressing mode, the offset address of the operand is given by the sum of contents of the
BX/BP registers and 8-bit/16-bit displacement.
Example : MOV DX, [BX+04] ; ADD CL, [BX+08]
Displacement
Instruction
Explanation:
Page 39
Suppose the register BX contains 4895H, the displacement value is 08h added with the content of
BX register. i.e 4895H+08H = 489D h. Hence the offset address is 489D h.
6. INDEXED ADDRESSING MODE
In this addressing mode, the operands offset address is found by adding the contents of SI or DI
register and 8-bit/16-bit displacements.
Instruction
7. BASED-INDEX ADDRESSING MODE
In this addressing mode, the offset address of the operand is computed by summing the base register
to the contents of an Index register.
Example: ADD CX, [AX+SI] ; MOV AX, [AX+DI]
Operand
Instruction
8. RELATIVE BASED INDEXED MODE
In this addressing mode, the operands offset is computed by adding the base register contents. An
Index registers contents and 8 or 16-bit displacement.
Example MOV AX, [BX+DI+08], ADD CX, [BX+SI+16]
9. IMPLIED ADDRESSING
Instructions using this mode have no operands. The instruction itself will specify the data to be
operated by the instruction.
Example: CLC; This clears the carry flag to zero.
10. STRING ADDRESSING
Employed in string operations to operate on string data.The effective address (EA) of source data is
stored in SI register and the EA of destination is stored in DI register.
Segment register for calculating base address of source data is DS and that of the destination data is
ES
Example: MOVS BYTE
Operations:
Calculation of source memory location:
EA = (SI) BA = (DS) x 1610 MA = BA + EA
Calculation of destination memory location:
EAE = (DI) BAE = (ES) x 1610 MAE = BAE + EAE
(MAE) ¬ (MA)
If DF = 1, then (SI) ¬ (SI) – 1 and (DI) = (DI) - 1
If DF = 0, then (SI) ¬ (SI) +1 and (DI) = (DI) + 1
Page 40
Concept-3
INSTRUCTION SET
What is an Instruction?
An instruction is a binary pattern designed inside a microprocessor to perform a specific function or
task.
The entire group of instructions supported by microprocessor is called instruction set. Instructions
are classified on the basis of functions they perform.
The 8086 microprocessor supports 8 types of instructions −
Data Transfer Instructions
Arithmetic Instructions
Bit Manipulation Instructions
String Instructions
Program Execution Transfer Instructions (Branch & Loop Instructions)
Processor Control Instructions
Iteration Control Instructions
Interrupt Instructions
DATA TRANSFER INSTRUCTIONS
These instructions are used to transfer the data from the source operand to the destination operand.
Following are the list of instructions under this group −
Instruction to transfer a word
MOV − Used to copy the byte or word from the provided source to the provided destination.
Ex: MOV AX,BX; After Execution
Before Execution
MOV AX,[BX];
MOV AX,[5000H];
MOV [2000],CX; AX = XXXX AX = 3421h
MOV BX,1234H AH = XXAL= XX AH = 34h AL=21h
From the first example AX=XXXX,
BX=3421H.
PUSH − Used to put a word at theBXtop of the stack.
= 3421h BX = 3421h
Ex: PUSH AX BH = 34h BL= 21h
(SP) ¬ (SP) – 2 BH = 34h BL= 21h
AXß1234H MA S = (SS) x 10 + SP
(MA S ; MA S + 1) ¬ (reg16)
(SP) ¬ (SP) – 2
PUSH [8000H] MA S = (SS) x 1010 + SP
8000Hß 7234H (MA S ; MA S + 1) ¬ (mem)
POP − Used to get a word from the top of the stack to the provided location.
Ex:
POP AX MA S = (SS) x 1610 + SP
(AX) ¬ (MA S ; MA S + 1)
(SP) ¬ (SP) + 2
POP [2000H] MA S = (SS) x 1610 + SP
([2000H]) ¬ (MA S ; MA S + 1)
(SP) ¬ (SP) + 2
Page 41
XCHG − Used to exchange the data from two locations.
Ex: XCHG AX,BX; Before Execution After Execution
XCHG AX,[5000H]
AX = ABCDh AX = 3421h
AH = ABh AL= CDh AH = 34h AL=21h
Arithmetic Instructions
These instructions are used to perform arithmetic operations like addition, subtraction,
multiplication, division, etc. Following is the list of instructions under this group –
AX =0024 AX = 006Ch
AH = 00hAL= 24h AH = 00h AL=6Ch
BX = 0003h DX = 0000h
BH = 00h BL=03h Page
DH = 00h DL= 00h 43
IMUL − Used to multiply signed byte by byte/word by word.
EX: IMUL BX
AAM − Used to adjust ASCII codes after multiplication.
AX =0024H AX = 000Ch
AH = 00hAL= 24h AH = 00h AL=0Ch
BX = 0003h DX = 0000h
BH = 00h BL=03h DH = 00h DL= 00h
IDIV − Used to divide the signed word by byte or signed double word by word.
EX:IDIV BL
AAD − Used to adjust ASCII codes after division.
CBW − Used to fill the upper byte of the word with the copies of sign bit of the lower byte.
CWD − Used to fill the upper word of the double word with the sign bit of the lower word.
Bit Manipulation
a) Logical Instructions
These instructions are used to perform operations where data bits are involved, i.e. operations like logical,
shift, etc.
Following is the list of instructions under this group −
Instructions to perform logical operation
NOT − Used to invert each bit of a byte or word.
EX:NOT AX
AND − Used for adding each bit in a byte/word with the corresponding bit in another byte/word.
EX: AND AX,BX
Before Execution After Execution
Assume
AX=5346H; BX=2673H
AX AX & BX 0101 0011 0100 0110
AX =5342H AX = 0242h
0010 0110 0111 0011 AH = 53hAL= 42h AH = 02h AL=42h
0000 0010 0100 0010
0 2 4 2
BX =2673h BX =2673h
BH = 26h BL=73h BH = 26h BL=73h
OR − Used to multiply each bit in a byte/word with the corresponding bit in another byte/word.
EX: OR AL,BL
XOR − Used to perform Exclusive-OR operation over each bit in a byte/word with the
corresponding bit in another byte/word.
EX: XOR AX,BX
TEST − Used to add operands to update flags, without affecting operands.
Page 44
EX: TEST AX
b) Shift and Rotate Instructions
Instructions to perform shift operations
SHL/SAL − Used to shift bits of a byte/word towards left and put zero(S) in LSBs.
EX: SHL AL,01H;
SAL AX,CX
SHR − Used to shift bits of a byte/word towards the right and put zero(S) in MSBs.
EX: SHR AL,01H
SAR − Used to shift bits of a byte/word towards the right and copy the old MSB into the new MSB.
EX: SAR AL,CL
ROR − Used to rotate bits of byte/word towards the right, i.e. LSB to MSB and to Carry Flag
[CF].EX: ROL AX,04H
RCR − Used to rotate bits of byte/word towards the right, i.e. LSB to CF and CF to MSB. EX: RCR
AX,04H
RCL − Used to rotate bits of byte/word towards the left, i.e. MSB to CF and CF to LSB.
EX: RCL AX,CX
Page 45
String Instructions
String is a group of bytes/words and their memory is always allocated in a sequential order.
Following is the list of instructions under this group −
REP − Used to repeat the given instruction till CX ≠ 0.
REPE/REPZ − Used to repeat the given instruction until CX = 0 or zero flag ZF = 1.
REPNE/REPNZ − Used to repeat the given instruction until CX = 0 or zero flag ZF = 1.
MOVS/MOVSB/MOVSW − Used to move the byte/word from one string to another.
COMS/COMPSB/COMPSW − Used to compare two string bytes/words.
INS/INSB/INSW − Used as an input string/byte/word from the I/O port to the provided memory
location.
OUTS/OUTSB/OUTSW − Used as an output string/byte/word from the provided memory location
to the I/O port.
SCAS/SCASB/SCASW − Used to scan a string and compare its byte with a byte in AL or string
word with a word in AX.
LODS/LODSB/LODSW − Used to store the string byte into AL or string word into AX.
Program Execution Transfer Instructions (Branch and Loop Instructions)
These instructions are used to transfer/branch the instructions during an execution. It includes the following
instructions −
Instructions to transfer the instruction during an execution without any condition −
CALL − Used to call a procedure and save their return address to the stack.
RET − Used to return from the procedure to the main program.
JMP − Used to jump to the provided address to proceed to the next instruction.
P
aJ Con
rt
c ditio
P
1c nal
Ski
X a
Y XA Jum
ppr
E XA pt
ed
P par
Next
S X
a t instr
2
r ucti
NO t on
3
AA
XX
XX
Instructions to transfer the instruction during an execution with some conditions –
Page 46
JA/JNBE − Used to jump if above/not below/equal instruction satisfies.
JAE/JNB − Used to jump if above/not below instruction satisfies.
JBE/JNA − Used to jump if below/equal/ not above instruction satisfies.
JC − Used to jump if carry flag CF = 1
JE/JZ − Used to jump if equal/zero flag ZF = 1
JG/JNLE − Used to jump if greater/not less than/equal instruction satisfies.
JGE/JNL − Used to jump if greater than/equal/not less than instruction satisfies.
JL/JNGE − Used to jump if less than/not greater than/equal instruction satisfies.
JLE/JNG − Used to jump if less than/equal/if not greater than instruction satisfies.
JNC − Used to jump if no carry flag (CF = 0)
JNE/JNZ − Used to jump if not equal/zero flag ZF = 0
JNO − Used to jump if no overflow flag OF = 0
JNP/JPO − Used to jump if not parity/parity odd PF = 0
JNS − Used to jump if not sign SF = 0
JO − Used to jump if overflow flag OF = 1
JP/JPE − Used to jump if parity/parity even PF = 1
JS − Used to jump if sign flag SF = 1
Processor Control or Flag Manipulation Instructions
These instructions are used to control the processor action by setting/resetting the flag values.
Following are the instructions under this group −
STC − Used to set carry flag CF to 1
CLC − Used to clear/reset carry flag CF to 0
CMC − Used to put complement at the state of carry flag CF.
STD − Used to set the direction flag DF to 1
CLD − Used to clear/reset the direction flag DF to 0
STI − Used to set the interrupt enable flag to 1, i.e., enable INTR input.
CLI − Used to clear the interrupt enable flag to 0, i.e., disable INTR input.
Iteration Control Instructions
These instructions are used to execute the given instructions for number of times. Following is the list of
instructions under this group −
LOOP − Used to loop a group of instructions until the condition satisfies, i.e., CX = 0
LOOPE/LOOPZ − Used to loop a group of instructions till it satisfies ZF = 1 & CX = 0
LOOPNE/LOOPNZ − Used to loop a group of instructions till it satisfies ZF = 0 & CX = 0
JCXZ − Used to jump to the provided address if CX = 0
Interrupt Instructions
These instructions are used to call the interrupt during program execution.
INT − Used to interrupt the program during execution and calling service specified.
INTO − Used to interrupt the program during execution if OF = 1
IRET − Used to return from interrupt service to the main program
Page 47
Concept-4
8086 Instruction Format:
The 8086 Instruction 8086 Instruction Format varies from 1 to 6 bytes in length.
The displacements and operands may be either 8-bits or 16-bits long depending on the instruction.
The opcode and the addressing mode is specified using first two bytes of an instruction.
Page 48
extension. The S-bit along with the W-bit indicate: :
V-bit : V-bit decides the number of shifts for rotate and shift instructions. If V = 0, then count = 1; if V = 1,
the count is in CL register. For example, if V = 1 and CL = 2 then shift or rotate instruction shifts or rotates
2-bits
Z-bit : It is used for string primitives such as REP for comparison with ZF Flag. (Refer Appendix A for
instruction formats)
As seen from the Fig. if an instruction has two opcode/addressing mode bytes, then the second byte is of one
of the following two forms .
where Mod, Reg and R/M fields specify operand as described in the following tables.
Page 49
Field Assignment
Page 50
(a) The DB directive
(b) The DW directive
(c) The DD directive
(d) The STRUCT (or STRUC) and ENDS directives (counted as one)
(e)The EQU Directive
(f)The COMMENT directive
(g)ASSUME
(h) EXTERN
(i) GLOBAL
(j) SEGMENT
(k)OFFSET
(l) PROC
(m)GROUP
(n) INCLUDE
(o) LENGTH
Data declaration directives:
(1) DB – The DB directive is used to declare a BYTE -2-BYTE variable – A BYTE is made up of 8 bits.
Declaration examples:
Byte1 DB 10h
Byte2 DB 255 ; 0FFh, the max. possible for a BYTE
(2) DW – The DW directive is used to declare a WORD type variable – A WORD occupies 16 bits or (2
BYTE).
Declaration examples:
Word DW 1234h
Word2 DW 65535; 0FFFFh, (the max. possible for a WORD)
(3) DD – The DD directive is used to declare a DWORD – A DWORD double word is made up of 32 bits
=2 Word’s or 4 BYTE.
Declaration examples:
Dword1 DW 12345678h
Dword2 DW 4294967295 ;0FFFFFFFFh. the max. possible for a DW.
(4) STRUCT and ENDS directives to define a structure template for grouping data items.
(1) The STRUCT directive tells the assembler that a user defined uninitialized data structure follows.
The uninitialized data structure consists of a combination of the three supported data types. DB,
DW, and DD.
(2) A Structure ends by using the ENDS directive meaning END of Structure.
(5) The EQU Directive
Page 51
The EQU directive is used to give name to some value or symbol. Each time the assembler
finds the given names in the program, it will replace the name with the value or a symbol. The value
can be in the range 0 through 65535 and it can be another Equate declared anywhere above or below.
The following operators can also be used to declare an Equate:
THIS BYTE
THIS WORD
THIS DWORD
A variable – declared with a DB, DW, or DD directive – has an address and has space
reserved at that address for it in the .COM file. But an Equate does not have an address or space
reserved for it in the .COM file.
Example:
A – Byte EQU THIS BYTE DB 10
A_ word EQU THIS WORD DW 1000
A_ dword EQU THIS DWORD DD 4294967295
Buffer Size EQU 1024
Buffer DB 1024 DUP (0)
Buffed_ ptr EQU $ ; actually points to the next byte after the; 1024th byte in buffer.
(6) Extern:
It is used to tell the assembler that the name or label following the directive are I some other
assembly module.
Example:
PROCEDURE -HERE SEGMENT
EXTERN SMART-DIVIDE: FAR ; found in the segment;
PROCEDURES-HERE
PROCEDURES-HERE ENDS
(7) GLOBAL:
The GLOBAL directive can be used in place of PUBLIC directive .for a name defined in the
current assembly module; the GLOBAL directive is used to make the symbol available to the
other modules. Example:
GLOBAL DIVISOR:
WORD tells the assembler that DIVISOR is a variable of type of word which is in another
assembly module or EXTERN.
(8) SEGMENT:
It is used to indicate the start of a logical segment. It is the name given to the the segment.
Example: the code segment is used to indicate to the assembler the start of logical segment.
Page 52
(9) PROC: (PROCEDURE)
It is used to identify the start of a procedure. It follows a name we give the procedure.
(10) NAME:
It is used to give a specific name to each assembly module when program consists of several
modules.
Example: PC-BOARD used to name an assembly module which contains the instructions for controlling a
printed circuit board.
(11) INCLUDE:
It is used to tell the assembler to insert a block of source code from the named file into the
current source module. This shortens the source module. An alternative is use of editor block
command to cop the file into the current source module.
(12) OFFSET:
It is an operator which tells the assembler to determine the offset or displacement of a named
data item from the start of the segment which contains it. It is used to load the offset of a variable
into a register so that variable can be accessed with one of the addressed modes. Example: when the
assembler read MOV BX.OFFSET PRICES, it will determine the offset of the prices.
(13) GROUP:
It can be used to tell the assembler to group the logical segments named after the directive
into one logical group. This allows the contents of all he segments to be accessed from the same
group. Example: SMALL-SYSTEM GROUP CODE, DATA, STACK-SEG.
(14) LENGTH:
LENGTH is an operator, which tells the assembler to determine the number of elements in
some named data item, such as a string or an array. When the assembler reads the statement MOV
CX, LENGTH STRING1, for example, will determine the number of elements in STRING1 and load
it into CX. If the string was declared as a string of bytes, LENGTH will produce the number of bytes
in the string. If the string was declared as a word string, LENGTH will produce the number of words
in the string.
Concept-6
Program Development tools and Execution:
Page 53
The first step in the development process is to write an assembly language program.
Editor:
The assembly language program can be written with an ordinary text editor such as word star, edit
and so on.
As you type in your program, the editor stores the ASCII codes for the letters and numbers in
successive RAM locations.
When you have typed in your entire program, you then save the file on the hard disk. This file is
called source file and the extension is .asm.
The assembly language program text is an input to the assembler.
Assembler:
The assembler translates assembly language statements to their binary equivalents, usually known
as object code.
The assembler generates 2 files on the hard disk.
Object File (.obj)
List File (.lst)
Time required to translating assembly code to object code is called Assemble Time.
During assembling, process assembler checks for syntax errors and displays them before giving
object code module.
The object code module contains the information about where the program or module to be loaded
in memory.
If the object code module is to be linked with other separately assembled modules then it contains
additional linkage information.
Linker:
A linker is a program used to join several object files into one large object file.
The linker produces a link file which contains the binary codes for all the combined modules. The
linker also produces a link map file which contains the address information about the linked files
(.exe).
Locator
A locator is a program used to assign the specific address of where the segments of object code are
to be loaded into memory.
Page 54
A locator program called EXE2BIN comes with the IBM PC Disk Operating System (DOS).
EXE2BIN converts a .exe file to a .bin file which has physical addresses.
Debugger
A debugger is a program which allows you to load your object code program into system memory,
execute the program and troubleshoot or debug it.
The debugger allows you to look at the contents of registers and memory locations after your
program runs.
It allows you to change the contents of registers and memory locations and re-run the program.
Some debuggers allow you to stop execution after each instruction so that you can check or alter
after each register contents.
A debugger also allows you to set a breakpoint at any point in your program. If you insert a
breakpoint at any point in your program, the debugger will run the program up to the instruction
where you put the breakpoint and then stop the execution.
Emulator
An emulator is a mixture of hardware and software.
It is used to test and debug the hardware and software of an external system, such as the prototype
of a microprocessor based instrument.
Part of the hardware of an emulator is a multi-wire cable which connects the host system to the
system being developed.
Concept-7
The assembly level programming 8086 code must be written in upper case letters
The labels must be followed by a colon, for example: label:
All labels and symbols must begin with a letter
All comments are typed in lower case
The last line of the program must be ended with the END directive
ALGORITHM
1. Initialize the addresses for input and result as 5000h, 6000h respectively.
2. Load AX register with the data 0001h, Initialize DX register.
3. Load SI, DI registers with input, result addresses respectively.
4. Load the input at SI location into CX register.
5. Check whether the input is zero.
Page 55
6. If input is zero, go to step 8. Otherwise calculate the factorial using recursive formula until input
becomes 1.
7. Store the content of AX register into the memory location pointed by DI.
8. End of the program
PROGRAMME: FLOWCHART:
MOV SI, 5000H
MOV DI, 6000H
MOV AX, 0001H
MOV DX, 0000H
MOV CX, [SI]
CMP CX, 00H
JZ XX
AGAIN: MUL CX
DEC CX
JNZ AGAIN
XX: MOV [DI], AX
MOV [DI+2], DX
INT 03H
Page 56
CODE SEGMENT
ORG 1000H
START: MOV AX, DATA
MOV DS, AX
LEA SI, LIST
MOV CX, 0005H
MOV DX, 0000H
BACK: MOV AL, [SI]
ROL AL, 01H
JC NEGATIVE
INC DL
INC SI
LOOP BACK
JMP EXIT
NEGATIVE: INC DH
INC SI
LOOP BACK
EXIT: MOV [RESULT], DX
MOV AH, 4CH
INT 21H
CODE ENDS
END START
Page 57
Start
FLOW CHART
YES
YES
2 JMP
3 4
1
Page 58
Program-3: Find the largest number of an array 8-bitCX
Decrement array
Algorithm – If CX=0 NO
Load data from offset 5000H to register CL and set register CH to 00 (for count).
Load first number (value) from next offset (i.e 5001H) to register AL and decrease count by 1.
Now compare value of register AL from data(value) at next offset, if that data is greater than value
of register AL then update value of register AL to that data else no change, and increase offset
value for next comparison and decrease count by 1 and continue this till count (value of register
CX) becomes 0. YES
Store the result (value of register AL ) to memory address 6000H
Program – Move the result to the memory location
MOV SI, 5000 : set the value of SI to 5000
MOV CL, [SI] : load data from offset SI to register CL
MOV CH, 00 : set value of register CH to 00
INC SI : increase value of SI by 1.
Stop
MOV AL, [SI] : load value from offset SI to register AL
DEC CL : decrease value of register CL by 1
BACK: INC SI : increase value of SI by 1
CMP AL, [SI] : compares value of register AL and [SI] (AL-[SI])
JNC BACK1 : jump to address LABLE BACK1 if carry not generated
MOV AL, [SI] : transfer data at offset SI to register AL
BACK1: INC SI : increase value of SI by 1
LOOP BACK : decrease value of register CX by 1 and jump to address LABLE
BACK if value of register CX is not zero
MOV [6000], AL : store the value of register AL to offset 6000H
INT 03H
Program-3: Find number of even and odd numbers in an 8- Bit array.
ASSUME DS:DATA,CS:CODE
DATA SEGMENT
A DW 1,2,3,4,5,6,7,8,9,10
DATA ENDS
CODE SEGMENT
START: MOV AX,DATA
MOV DS,AX
LEA SI,A
MOV DX,0000
MOV BL,02
MOV CL,10
L1: MOV AX,WORD PTR[SI]
DIV BL
CMP AH,00
JNZ L2
INC DH
JMP L3
L2: INC DL
L3: ADD SI,2
DEC CL
CMP CL,00
JNZ L1
MOV AH,4CH
Page 59
INT 21H
CODE ENDS
END START
Program-4: convert a 16-bit binary number into equivalent BCD number.
DATA SEGMENT
NO1 DB "1001000000110110"
D1 DW 4 DUP (?)
DATA ENDS
CODE SEGMENT
ASSUME CS:CODE, DS:DATA
START: MOV AX, DATA
MOV DS, AX
LEA SI, NO1
LEA DI, D1
MOV CX, 04H
TOP: MOV BX, 00H
MOV AX, [SI]
ROR AX, 1
JNC P2
ADD BX, 08H
P2: INC SI
MOV AX, [SI]
ROR AX, 1
JNC P3
ADD BX, 04H
P3: INC SI
MOV AX, [SI]
ROR AX, 1
JNC P4
ADD BX, 02H
P4: INC SI
MOV AX, [SI]
ROR AX, 1
JNC P5
ADD BX, 01H
P5: MOV [DI], BX
INC DI
INC SI
DEC CX
JNZ TOP
INT 3
CODE ENDS
END START
Page 60
General MCQs From Unit-2:
1. The instruction that is used to transfer the data from source operand to destination operand is
a) data copy/transfer instruction
b) branch instruction
c) arithmetic/logical instruction
d) string instruction
2. Which of the following is not a data copy/transfer instruction?
a) MOV
b) PUSH
c) DAS
d) POP
5. In PUSH instruction, after each execution of the instruction, the stack pointer is
a) incremented by 1
b) decremented by 1
c) incremented by 2
d) decremented by 2
6. The instructions that are used for reading an input port and writing an output port respectively are
a) MOV, XCHG
b) MOV, IN
c) IN, MOV
d) IN, OUT
7. The instruction that is used for finding out the codes in case of code conversion problems is
a) XCHG
b) XLAT
c) XOR
d) JCXZ
8. The instruction that adds immediate data/contents of the memory location specified in an
instruction/register to the contents of another register/memory location is
a) SUB
b) ADD
Page 61
c) MUL
d) DIV
12. The contents of a base register are added to the contents of index register in
a) indexed addressing mode
b) based indexed addressing mode
c) relative based indexed addressing mode
d) based indexed and relative based indexed addressing mode
Answers :
1. Write an alp to perform arithmetic operations for the given numbers AF73H, 2369H.
2. Write an alp to find the 2’s complement for a given number.
3. Write an alp to get unpacked bcd output for given numbers.25h,63h.
Page 62
Unit-3: 8086 INTERFACING:
Unit Outcomes:
At the end of this unit you will learn:
5. Identify the different ways of interfacing memory and I/O with microprocessors.
6. Apply and Analyze the interfacing concept of different programmable interfacing modules
with microprocessors for real time applications.
What is an Interfacing?
Interface is the path for communication between two components. Interfacing is of two types,
memory interfacing and I/O interfacing.
What is an IO interfacing?
Page 63
There are various communication devices like the keyboard, mouse, printer, etc. So, we need to
interface the keyboard and other devices with the microprocessor by using latches and buffers. This type of
interfacing is known as I/O interfacing.
Concept-1
SEMICONDUCTOR MEMORIES INTERFACING (RAM,ROM)
Semiconductor memories are of two types, viz. RAM (Random Access Memory) and ROM (Read
Only Memory).
The semiconductor RAMs are of broadly two types-static RAM and dynamic RAM. The
semiconductor memories are organized as two dimensional arrays of memory locations.
For example, 4Kx8 or 4K byte memory contains 4096 locations, where each location contains 8-bit
data and only one of the 4096 locations can be selected at a time.
The general procedure of static memory interfacing with 8086 is briefly described as follows:
1. Arrange the available memory chips so as to obtain 16-bit data bus width. The upper 8-bit bank is called
"odd address memory bank" and the lower 8-bit bank is called "even address memory bank".
2. Connect available memory address lines of memory chips with those of the microprocessor and also
connect the memory RD’ and WR’ inputs to the corresponding processor control signals. Connect 16-bit
data bus of the memory bank with that of the microprocessor 8086.
3. The remaining address lines of the microprocessor, BHE’ and A0 are used for decoding the required chip
select signals for the odd and even memory banks. The CS’ of memory is derived from the O/P of the
decoding circuit.
Page 64
Problem1: Interfacing of two 4KX4 PROM and two 8KX4 RAM with 8086 CPU, Draw the memory
map and interfacing diagram for it, the RAM address follows the ROM address.
Solution:
Given Data:
Number of PROM chips =02, each one size 4KX4.
(4KX4)*2=8KX4
Number of RAM Chips =02, each one size 8KX4
(8KX4)*2 = 16KX4
PROM Odd Bank Size 4KX4, Even Bank Size 4KX4
RAM Odd Bank Size 8KX4, Even Bank Size 8KX4
After RESET, the IP and CS are initialized to form address FFFF0h. Hence, this address must lie in
the PROM. The address of RAM may be selected any where in the 1MB address space of 8086, but we will
select the RAM address such that the address map of the system is continuous.
Address Decoding Table
Let us assume that the latched address, BHE’ and de-multiplexed data lines are readily available for
interfacing.
1. Total 8K bytes of EPROM need 13 address lines A0-A12 (since 213 = 8K).
2. Address lines A13 - A19 are used for decoding to generate the chip select.
3. The BHE’ signal goes low when a transfer is at odd address or higher byte of data is to be accessed.
4. If A0 is 0, i.e., the address is even and is in RAM, then the lower RAM chip is selected indicating 8-
bit transfer at an even address.
5. If A0 is i.e., the address is odd and is in RAM, the BHE’ goes low, the upper RAM chip is selected,
further indicating that the 8-bit transfer is at an odd address.
6. If the selected addresses are in ROM, the respective ROM chips are selected.
7. If at a time A0 and BHE’ both are 0, both the RAM or ROM chips are selected, i.e., the data transfer
is of 16 bits.
Page 65
Memory Chip Selection Table:
Problem2: Design an interface between 8086 CPU and two chips of 16K×8 EPROM and two chips of
32K×8 RAM. Select the starting address of EPROM suitably. The RAM address must start at 00000
H. Solution: The last address in the map of 8086 is FFFFF H. after resetting, the processor starts
from FFFF0 H. hence this address must lie in the address range of EPROM.
It is better not to use a decoder to implement the above map because it is not continuous, i.e. there is some
unused address space between the last RAM address (0FFFF H) and the first EPROM address (F8000 H).
Hence the logic is implemented using logic gates.
Page 66
Problem3: It is required to interface two chips of 32K×8 ROM and four chips of 32K×8 RAM with
8086, according to following map. ROM 1 and ROM 2 F0000H - FFFFFH, RAM 1 and RAM 2
D0000H - DFFFFH, RAM 3 and RAM 4 E0000H - EFFFFH. Show the implementation of this
memory system. Solution:
Page 67
INTERFACING I/O PORTS
I/O ports or Input/output ports are the devices through which the microprocessor communicates with
other devices or external data source/destinations.
Input activity, as one may expect, is the activity that enables the microprocessor to read data from
external devices, and for example keyboards. These devices are known as input devices as they feed
data into microprocessor system.
Output activity transfers data from the microprocessor to the external devices, for example CRT
display. These devices which accept the data from a microprocessor system are called output
devices.
Thus for a microprocessor the input activity is similar to read operation, while the output activity is
similar to write operation. Steps in Interfacing an I/O Device
Connect the data bus of the microprocessor system with the data bus of the I/O port.
Derive a device address pulse by decoding the required address of the device and use it as the chip
select of the device.
Use a suitable control signal i.e. IOWR’ and IORD’ to carry out device operations.
Page 68
Problem: Interface an input port 74LS245 to read the status of switches SW1 to SW8. The switches,
when shorted, input a 1 else input a 0 to the microprocessor system. Store the status in register BL.
The address of the port is 0740H.
Solution:
Concept-2
8254 SOFTWARE PROGRAMMABLE TIMER/COUNTER
The Intel 8254 is a Programmable Interval Timer (PTIs) designed for microprocessors to perform
timing and counting functions using three 16-bit registers.
Page 69
Each counter has 2 input pins, i.e. Clock & Gate, and 1 pin for “OUT” output. To operate a counter,
a 16-bit count is loaded in its register. On command, it begins to decrement the count until it reaches 0, then
it generates a pulse that can be used to interrupt the CPU.
Features of 8254
8254 Architecture
Page 70
Working:
It is a tri-state, bi-directional, 8-bit buffer, which is used to interface the 8253/54 to the system data bus. It
has three basic functions −
Read/Write Logic
It includes 5 signals, i.e. RD, WR, CS, and the address lines A 0 & A1. In the peripheral I/O mode, the RD
and WR signals are connected to IOR and IOW, respectively. In the memory mapped I/O mode, these are
connected to MEMR and MEMW.
Address lines A0 & A1 of the CPU are connected to lines A 0 and A1 of the 8253/54, and CS is tied to a
decoded address. The control word register and counters are selected according to the signals on lines A 0 &
A1.
A1 A0 Result
0 0 Counter 0
0 1 Counter 1
1 0 Counter 2
Page 71
1 1 Control Word Register
X X No Selection
This register is accessed when lines A 0 & A1 are at logic 1. It is used to write a command word,
which specifies the counter to be used, its mode, and either a read or write operation. Following table
shows the result for various control inputs.
A1 A0 RD WR CS Result
0 0 1 0 0 Write Counter 0
0 1 1 0 0 Write Counter 1
1 0 1 0 0 Write Counter 2
0 0 0 1 0 Read Counter 0
0 1 0 1 0 Read Counter 1
1 0 0 1 0 Read Counter 2
1 1 0 1 0 No operation
X X 1 1 0 No operation
X X X X 1 No operation
Counters
Each counter consists of a single, 16 bit-down counter, which can be operated in either binary or BCD. Its
input and output is configured by the selection of modes stored in the control word register. The
programmer can read the contents of any of the three counters without disturbing the actual count in
process.
Page 72
8254 Control Word and Operating modes
When the chip is powering up, the state is undefined. The mode, count value, and outputs are
undefined in that time.
Each counter must be programmed before it is used. We do not need to program some unused
counters.
Counters are programmed by writing the control words and then one initial count.
SC SC0 Selection
1
0 0 Counter 0
0 1 Counter 1
1 0 Counter 2
1 1 Read the back
status
Page 73
The process of decrementing the counter continues till the terminal count is reached, i.e., the count
become zero and the output goes HIGH and will remain high until it reloads a new count.
The GATE signal is high for normal counting. When GATE goes low, counting is terminated and
the current count is latched till the GATE goes high again.
Page 74
Important questions from concept-2.
Concept-3
INTEL 8259 PROGRAMMABLE INTERRUPT CONTROLLER
The 8259 is known as the Programmable Interrupt Controller (PIC) microprocessor. In 8086
there are two hardware interrupts respectively. But adding 8259, we can increase the interrupt handling
capability. This chip combines the multi-interrupt input source to single interrupt output. This provides 8-
interrupts from IR0 to IR7.
Features
This chip is designed for 8085 and 8086.
It can be programmed either in edge triggered, or in level triggered mode
We can mask individual bits of Interrupt Request Register.
By cascading 8259 chips, we can increase interrupts up to 64 interrupt lines
Clock cycle is not needed.
The pin level diagram and functional pin diagram is like below -
Page 75
The block diagram is like below -
Page 76
Working
Block Description
Page 77
Block Description
Register
Interrupt Mask It stores interrupt level that will be masked, by storing the
Register masking bits of interrupt level.
It checks all three registers, and set the priority of the
interrupts. Interrupt with the highest priority is set in the ISR
Priority Resolver
register. It also reset the interrupt level which is already been
serviced in the IRR.
To increase number of interrupt pin, we can cascade more
number of pins, by using cascade buffer. When we are going to
Cascade Buffer
increase the interrupt capability, CSA lines are used to control
multiple interrupts.
Page 78
Initialization Command Word 1 (ICW1):
A write command issued to 8259A with A0=0 and D4=1 is interpreted as ICW1, which starts the
initialization sequence.
It specifies
1. Single or multiple 8259As in the system.
2. 4 or 8 bit interval between the interrupt vector locations.
3. The address bit A7-A5 to CALL instruction.
4. Edge triggered or level triggered interrupts.
5. ICW4 is needed or not.
Page 79
A write command following ICW1, with A0=1 is interpreted as ICW2. This is used to load high order byte
of the interrupt vector address of all interrupts.
Initialization Command Word 3 (ICW3):
ICW3 is required only if there is more than one 8259A in the system and if they are cascaded. An
ICW3 operation loads a slave register in the 8259.
For master each bit in ICW3 is used whether it has a slave 8259 attached to it on its corresponding IR
input.
For slave, bits D0-D2 of ICW3 are used to assign a slave identification code to the 8259A
It specifies
1. Whether to use special fully nested mode or non special fully nested mode.
2. Whether to use buffered mode or non buffered mode.
3. Whether to use automatic EOI or normal EOI.
4. CPU used 8086/8088
After initialization the 8259A is ready to process the interrupt request. However during operation it
might be necessary to change the mode of processing the interrupts.
Operation Command Words (OCWs) are used for this purpose.
Operation Command Word 1 (OCW1):
Page 80
A write command to the 8259 with A0=1 (after ICW2) is interpreted as OCW1. OCW1 is used for
enabling or disabling the recognition of specific interrupt requests by programming the IMR.
Page 81
Important questions from concept-3.
1. Explain the important features of 8259 interrupts controller.Nov’20
2. Draw and explain the architecture of 8259.
Concept-4
INTEL8237A DMA CONTROLLER
DMA stands for Direct Memory Access. It is designed by Intel to transfer data at the fastest rate. It
allows the device to transfer the data directly to/from memory without any interference of the CPU.
Using a DMA controller, the device requests the CPU to hold its data, address and control bus, so the
device is free to transfer data directly to/from the memory. The DMA data transfer is initiated only after
receiving HLDA signal from the CPU.
Initially, when any device has to send data between the device and the memory, the device has to
send DMA request (DRQ) to DMA controller.
The DMA controller sends Hold request (HRQ) to the CPU and waits for the CPU to assert the
HLDA.
Then the microprocessor tri-states all the data bus, address bus, and control bus. The CPU leaves the
control over bus and acknowledges the HOLD request through HLDA signal.
Now the CPU is in HOLD state and the DMA controller has to manage the operations over buses
between the CPU, memory, and I/O devices.
Programmable DMA Controller 8237a
The 8237 works in two modes i.e., master and slave modes.
In slave mode, the 8237 functions as an input/output device. In this mode the system buses arc
controlled by microprocessor and hence the microprocessor is connected to the system bus.
In master mode 8237 becomes the bus master and hence the microprocessor is isolated from the
system bus. This isolation is done by AEN signal.
In minimum configuration, 8237 DMA controller is used to transfer the data. The peripheral chips
are interface as normal 10 ports. Figure shows the interfacing of DMA controller with 8086.
In minimum mode the HOLD and HLDA signals are used to bus arbitration and in maximum mode
configuration RQ_0/GT_0; and RQ_1/GT_1.
The 8237 outputs only 16-bit memory address but not the complete 20-bit address of 8086. To store
the remaining four address hits A_16—A_19 a separate page latch is required.
The 8237 is not compatible with 8086 in its maximum mode configuration. This is because RQ/GT
is not compatible with HRQ and HLDA of 8237.
So if 8086 is to be interfaced with DMA controller, then 8089 10 processor is required.
The 8089 interfaces to the 8086's local multiplexed buses. It shares the bus buffers and system
controller of the host system. It is compatible with the RQ/GT signals of 8086 and outputs the
complete 20-bit address.
Page 82
Different data transfer modes of 8237 DMA controller:
The 8237 is in the idle cycle if there is no pending request or the 8237 is waiting for a request from one of the DMA
channels. Once a channel requests a DMA service, the 8237 sends the HOLD request to the CPU using its HRQ pin. If
the CPU acknowledges the hold request on HLDA, the 8237 enters an active cycle. In the active cycle, the actual data
transfer takes place in one of the following transfer modes as is programmed.
1. Single Transfer Mode: In this mode, the device transfers only one byte per request. The word count is
decremented and the address is decremented or incremented (depending on programming) after each such
transfer. The Terminal Count (TC) state is reached when the count becomes zero. For each transfer the DREQ
must be active until the DACK is activated, in order to get recognized. After TC the bus will be relinquished
for the CPU. For a new DREQ to 8237 it will again activate the HRQ signal to the CPU and the HLDA signal
from the CPU will push the 8237 again into the single transfer mode. This mode is also called as 'cycle
stealing'.
2. Block Transfer Mode: In this mode, the 8237 is activated by DREQ to continue the transfer until a TC is
reached, i.e. a block of data is transferred. The transfer cycle may be terminated due to EOP (either internal or
external) which forces Terminal Count (TC). The DREO needs to be activated only till the DACK signal is
activated by the DMA controller. Auto-initialization may be programmed in this mode.
3. Demand Transfer Mode: In this mode, the device continues transfers until a TC is reached or an external
EOP is detected or the DREQ signal goes inactive. Thus a transfer may exhaust the capacity of data transfer of
an I/O device. After the I/O device is able to catch up the service may be re-established activating the DREQ
signal again. Only the EOP generated by TC or external EOP can cause the auto-initialization, and only if it is
programmed for.
4. Cascade Mode: In this mode, more than one 8237 can be connected together to provide more than four DMA
channels. The HRQ and HLDA signals from additional 8237s are connected with DREQ and DACK pins of a
Page 83
channel of the host 8237 respectively. The priorities of the DMA requests may be preserved at each level. The
first device is only used for prioritizing the additional devices (slave 8237s), and it does not generate any
address or control signal of its own. The host 8237 responds to DREQ generated by slaves and generates the
DACK and the HRQ signals to coordinate all the slaves. All other outputs of the host 8237 are disabled.
5. Memory to memory Transfer: To perform the transfer of a block of data from one set of memory address to
another one, this transfer mode is used. Programming the corresponding mode bit in the command word, sets
the channel 0 and I to operate as source and destination channels, respectively. The transfer is initialized by
setting the DREQ0 using software commands. The 8237 sends HRQ (Hold Request) signal to the CPU as
usual and when the HLDA signal is activated by the CPU. the device starts operating in block transfer mode
to read the data from memory. The channel 0 current address register acts as a source pointer. The byte read
from the memory is stored in an internal temporary register of 8237. The channel 1 current address register
acts as a destination pointer to write the data from the temporary register to the destination memory location.
The pointers are automatically incremented or decremented, depending upon the programming. The channel 1
word count register is used as a counter and is decremented after each transfer. When it reaches zero, a TC is
generated, causing EOP to terminate the service. The 8237 also responds to external EOP signals to terminate
the service. This feature may be used to scan a block of data for a byte. When a match is found the process
may be terminated using the external EOP. Under all these transfer modes, the 8237 carries out three basic
transfers namely, write transfer, read transfer and verify transfer. In write transfer, the 8237 reads from an I/O
device and writes to memory under the control of IOR and MEMW signals. In read transfer, the 8237 reads
from memory and writes to an I/O device by activating the MEMR and IOW signals. In verify transfers, the
8237 works in the same way as the read or write transfer but does not generate any control signal.
Mode 0 − In this mode, Port A and B is used as two 8-bit ports and Port C as two 4-bit ports. Each
port can be programmed in either input mode or output mode where outputs are latched and inputs
are not latched. Ports do not have interrupt capability.
Mode 1 − In this mode, Port A and B is used as 8-bit I/O ports. They can be configured as either
input or output ports. Each port uses three lines from port C as handshake signals. Inputs and
outputs are latched.
Mode 2 − In this mode, Port A can be configured as the bidirectional port and Port B either in Mode
0 or Mode 1. Port A uses five signals from Port C as handshake signals for data transfer. The
remaining three signals from Port C can be used either as simple I/O or as handshake for port B.
Page 85
Features of 8255A
The prominent features of 8255A are as follows −
It consists of 3 8-bit IO ports i.e. PA, PB, and PC.
Address/data bus must be externally demux'd.
It is TTL compatible.
It has improved DC driving capability.
8255 Pin diagram
PA7-PA0: These are eight port A lines that acts as either latched output or buffered input
lines depending upon the control word loaded into the control word register.
PC7-PC4: Upper nibble of port C lines. They may act as either output latches or input buffers
lines. This port also can be used for generation of handshake lines in mode 1 or mode 2.
PC3-PC0: These are the lower port C lines, other details are the same as PC7-PC4 lines.
Page 86
PB0-PB7: These are the eight port B lines which are used as latched output lines or buffered
input lines in the same way as port A.
RD: This is the input line driven by the microprocessor and should be low to indicate read
operation to 8255.
WR: This is an input line driven by the microprocessor. A low on this line indicates write operation.
CS: This is a chip select line. If this line goes low, it enables the 8255 to respond to RD and
WR signals, otherwise RD and WR signal are neglected.
A1-A0: These are the address input lines and are driven by the microprocessor. These lines A1-
A0 with RD, WR and CS from the following operations for 8255. These address lines are used for
addressing any one of the four registers, i.e. three ports and a control word register as given in table
below. In case of 8086 systems, if the 8255 is to be interfaced with lower order data bus, the A0 and
A1 pins of 8255 are connected with A1 and A2 respectively.
D0-D7: These are the data bus lines those carry data or control word to/from the microprocessor.
RESET: A logic high on this line clears the control word register of 8255. All ports are set as
input ports by default after reset.
8255 Architecture
The following figure shows the architecture of 8255A −
It consists of 40 pins and operates in +5V regulated power supply. Port C is further divided into two
4-bit ports i.e. port C lower and port C upper and port C can work in either BSR (bit set rest) mode or in
mode 0 of input-output mode of 8255. Port B can work in either mode or in mode 1 of input-output mode.
Port A can work either in mode 0, mode 1 or mode 2 of input-output mode.
Page 87
It has two control groups, control group A and control group B. Control group A consist of port A
and port C upper. Control group B consists of port C lower and port B.
Depending upon the value if CSbar, A1 and A0 we can select different ports in different modes as
input-output function or BSR. This is done by writing a suitable word in control register (control word D0-
D7).
0 0 0 PORT A
0 0 1 PORT B
0 1 0 PORT C
0 1 1 Control
Register
1 X X No Selection
WR
It stands for write. This control signal enables the write operation. When this signal goes low, the
microprocessor writes into a selected I/O port or control register.
RESET
This is an active high signal. It clears the control register and sets all ports in the input mode.
RD
It stands for Read. This control signal enables the Read operation. When the signal is low, the
microprocessor reads the data from the selected I/O port of the 8255.
A0 and A1
These input signals work with RD, WR, and one of the control signal. Following is the table showing their
various signals with their result.
A1 A0 RD WR C Result
S
0 0 0 1 0 Input Operation
Page 88
PORT A → Data Bus
Output Operation
0 0 1 0 0
Data Bus → PORT A
Concept-6
KEYBOARD INTERFACING
Interfacing Keyboard with 8086
Interface a 4X4 keyboard with 8086 using 8255, and write an ALP for detecting a key closure and
return the key code in AL. The debouncing period for a key in 20 ms ?
Here we use port A as output port for selecting a row of keys while port B is used as an input port for
sensing a closed key.
Page 89
Hence the keyboard lines are selected one by one through Port A and the Port B lines are polled
continuously till a key closure is sensed.
The higher order lines of Port A and Port B are left unused. The flow chart of the ALP is as shown
below :
We suppose that we use simple mechanical switches. For keyboard, then to get the meaningful data from a
keyboard requires three steps :
•• (1) Detect a key press
• • (2) Debounce the key press
• • (3) Encode the key press T
The three tasks can be done with a hardware, software or a combination of the two.
The rows of the matrix are connected to four output port lines. The column line of the matrix are connected
to four input port lines
Concept-7
ALPHANUMERIC DISPLAYS (LED,7-SEGMENT DISPLAY, MULTIPLEXED 7-SEGMENT
DISPLAY, LCD),
Interfacing 7-Seg Display with 8086
Page 90
Interface an 8255 with 8086 at 80H as an I/O address of Port A. Interface five 7 segment displays with the
8255. Write an ALP to display 1, 2, 3, 4 and 5 over the 5 displays continuously as per their positions starting
with 1 at the least significant position?
We will first decide the codes and store them in a lookup table as shown in below.
Page 91
Page 92
The 8255 is to be interfaced with lower order data bus; i.e. D0-D7. The A0 and A1 pins of 8255 are
connected to A1 and A2 pins of the microprocessor respectively. We will use absolute decoding scheme that
uses all the 16 address lines. For deriving the device address pulse. Out of A0 – A15 lines, two address lines
A2 and A1 are directly required by 8255 for three port and CWR address decoding. Hence only A3 to A15
are used for decoding addresses. Circuit diagram, the 8086 is assumed to be in the maximum mode so that
IORD and I OWR are readily available.
LCD:
In systems where a large amount of data needs to be displayed a CRT is used to display the data. In system
where only a small amount of data needs to be displayed, simple digit-type displays are often used.
A display device is an output device for presentation of information in visual form. When the input
information is supplied as an electrical signal, the display is called an electronic display.
Types of displays:
Cathode Ray Tube (CRT)
Liquid Crystal Displays (LCD)
Light-Emitting Diode (LED)
Gas Plasma
DLP
LCD displays use very low power, so they are often used in portable, battery powered instruments.
They do not emit their own light; they simply change the reflection of available light. Therefore, for an
instrument that is to be used in low light conditions, you have to include a light source for LCDs or use
LEDs which emit their own light.
LCD(Liquid Crystal Display):
LCD (Liquid Crystal Display) is very popular for displaying in Embedded Applications. LCDs are very
cheap and easy to interface with microprocessors; LCDs are widely used in devices like telephones, vending
machines, washing machines, toys etc. LCD comes in several varieties i.e. 16*2, 20*2, 20*4 etc. These
Page 93
different LCD varieties can display different number of characters i.e. 16*2 can display 32 characters at a
time.
Page 94
Table: The Pin Configuration of the LCD Module
Sample Program:
CODE SEGMENT
ASSUME CS: CODE, DS: CODE, ES: CODE, SS: CODE
START: ORG 1000H; Use 1000H for MDA series
MOV AX,CS
MOV DS,AX; Making the DS (Data Segment) and CS (Code Segment) value same;
MOV SS,AX; Making the SS (Stack Segment) also same with CS, DS
MOV SP,STACK;
CALL ALLCLR;
CALL LN11
MOV SI,OFFSET LINE1
CALL STRING;
CALL LN21
MOV SI,OFFSET LINE2
CALL STRING; Blinks the whole display
BLINK: CALL DISPOFF
CALL TIMER
CALL DISPON
CALL TIMER
JMP BLINK;
LINE1 DB 'mpmc!’,00H,00H
LINE2 DB 'programming.',00H,00H;; LCD instruction
ALLCLR: MOV AH, 00000001B; Clears entire display
JMP OUT1;
DISPOFF: MOV AH, 00001000B; Display off, cursor off, not blink
JMP OUT1;
DISPON: MOV AH, 00001111B; Display on, cursor on, cursor blink
JMP OUT1;
LN11: MOV AH, 00000010B; Returns to home position
JMP OUT1;
LN21: MOV AH, 11000000B; Sets RAM address so that the cursor is positioned ;at the head of
the 2nd line.
JMP OUT;To write to instruction register
OUT1: PUSH AX
PUSH DX
CALL BUSY
MOV AL,AH
MOV DX,IR_WR
OUT DX,AL
POP DX
POP AX
RET
; busy flag check, must be done before any write operation
BUSY: PUSH DX
PUSH AX
MOV DX,ST_RD
BUSY1: IN AL,DX
AND AL,10000000B
JNZ BUSY1
POP AX
POP DX
Page 95
RET;
;To send a single character
CHAROUT: PUSH DX
PUSH AX
CALL BUSY
MOV AL,AH
MOV DX,DR_WR
OUT DX,AL
POP AX
POP DX
RET
;To out a string line from address CS:[SI]
STRING: MOV AH,BYTE PTR CS:[SI]
CMP AH,00H
JE STRING1;
CALL BUSY
CALL CHAROUT
INC SI
JMP STRING
STRING1: RET
; Timer Makes delay
TIMER: PUSH CX
MOV CX,0FFFFH
TIMER1: DEC CX
JNZ TIMER1
POP CX
RET;
CODE ENDS
END START
Concept-8
Page 96
The Keyboard can be interfaced either in the interrupt or the polled mode. In the Interrupt mode,
the processor is requested service only if any key is pressed, otherwise the CPU will continue with its main
task.
In the Polled mode, the CPU periodically reads an internal flag of 8279 to check whether any key is
pressed or not with key pressure.
The keyboard consists of maximum 64 keys, which are interfaced with the CPU by using the key-
codes. These key-codes are de-bounced and stored in an 8-byte FIFORAM, which can be accessed by the
CPU. If more than 8 characters are entered in the FIFO, then it means more than eight keys are pressed at a
time. This is when the overrun status is set.
If a FIFO contains a valid key entry, then the CPU is interrupted in an interrupt mode else the CPU checks
the status in polling to read the entry. Once the CPU reads a key entry, then FIFO is updated, and the key
entry is pushed out of the FIFO to generate space for new entries.
Page 97
This unit contains registers to store the keyboard, display modes, and other operations as programmed by
the CPU. The timing and control unit handles the timings for the operation of the circuit.
Scan Counter
It has two modes i.e. Encoded mode and Decoded mode. In the encoded mode, the counter provides the
binary count that is to be externally decoded to provide the scan lines for the keyboard and display.
In the decoded scan mode, the counter internally decodes the least significant 2 bits and provides a
decoded 1 out of 4 scan on SL0-SL3.
Return Buffers, Keyboard Debounce, and Control
This unit first scans the key closure row-wise, if found then the keyboard debounce unit debounces the key
entry. In case, the same key is detected, then the code of that key is directly transferred to the sensor RAM
along with SHIFT & CONTROL key status.
FIFO/Sensor RAM and Status Logic
This unit acts as 8-byte first-in-first-out (FIFO) RAM where the key code of every pressed key is entered
into the RAM as per their sequence. The status logic generates an interrupt request after each FIFO read
operation till the FIFO gets empty.
In the scanned sensor matrix mode, this unit acts as sensor RAM where its each row is loaded with the
status of their corresponding row of sensors into the matrix. When the sensor changes its state, the IRQ line
changes to high and interrupts the CPU.
Display Address Registers and Display RAM
This unit consists of display address registers which holds the addresses of the word currently read/written
by the CPU to/from the display RAM.
8279 − Pin Description
The following figure shows the pin diagram of 8279 −
Page 98
This pin indicates the transfer of command/status information. When it is low, it indicates the transfer of
data.
RD, WR
This Read/Write pin enables the data buffer to send/receive data over the data bus.
IRQ
This interrupt output line goes high when there is data in the FIFO sensor RAM. The interrupt line goes
low with each FIFO RAM read operation. However, if the FIFO RAM further contains any key-code entry
to be read by the CPU, this pin again goes high to generate an interrupt to the CPU.
Vss, Vcc
These are the ground and power supply lines of the microprocessor.
SL0 − SL3
These are the scan lines used to scan the keyboard matrix and display the digits. These lines can be
programmed as encoded or decoded, using the mode control register.
RL0 − RL7
These are the Return Lines which are connected to one terminal of keys, while the other terminal of the
keys is connected to the decoded scan lines. These lines are set to 0 when any key is pressed.
SHIFT
The Shift input line status is stored along with every key code in FIFO in the scanned keyboard mode. Till
it is pulled low with a key closure, it is pulled up internally to keep it high
CNTL/STB - CONTROL/STROBED I/P Mode
In the keyboard mode, this line is used as a control input and stored in FIFO on a key closure. The line is a
strobe line that enters the data into FIFO RAM, in the strobed input mode. It has an internal pull up. The
line is pulled down with a key closure.
BD
It stands for blank display. It is used to blank the display during digit switching.
OUTA0 – OUTA3 and OUTB0 – OUTB3
These are the output ports for two 16x4 or one 16x8 internal display refresh registers. The data from these
lines is synchronized with the scan lines to scan the display and the keyboard.
Operational Modes of 8279
There are two modes of operation on 8279 − Input Mode and Output Mode.
Input Mode
This mode deals with the input given by the keyboard and this mode is further classified into 3 modes.
Scanned Keyboard Mode − In this mode, the key matrix can be interfaced using either encoded or
decoded scans. In the encoded scan, an 8×8 keyboard or in the decoded scan, a 4×8 keyboard can be
interfaced. The code of key pressed with SHIFT and CONTROL status is stored into the FIFO
RAM.
Scanned Sensor Matrix − In this mode, a sensor array can be interfaced with the processor using
either encoder or decoder scans. In the encoder scan, 8×8 sensor matrix or with decoder scan 4×8
sensor matrix can be interfaced.
Strobed Input − In this mode, when the control line is set to 0, the data on the return lines is stored
in the FIFO byte by byte.
Output Mode
This mode deals with display-related operations. This mode is further classified into two output modes.
Display Scan − This mode allows 8/16 character multiplexed displays to be organized as dual 4-
bit/single 8-bit display units.
Display Entry − This mode allows the data to be entered for display either from the right side/left
side.
Page 99
Concept-9
STEPPER MOTOR
A stepper motor is a digital motor. It can be driven by digital signal.
Page 100
Fig: Full step excitation sequence
The given excitation sequence rotates the motor in clockwise direction.
To rotate motor in anticlockwise direction we have to excite motor in a reverse sequence.
The excitation sequence for Stepper Motor Interface many change due to change in winding
connections.
However, it is not desirable to excite both the ends of the same winding simultaneously.
This cancels the flux and motor winding may damage. To avoid this, digital locking system must be
designed.
Page 101
We know that Stepper Motor Interface is stepped from one position to the next by changing the
currents through the fields in the motor.
The winding inductance opposes the change in current and this puts limit on the stepping rate. For
higher stepping rates and more torque, it is necessary to use a higher voltage source and current
limiting resistors.
By adding series resistance, we decrease L/R time constant, which allows the current to change more
rapidly in the windings. There is a power loss across series resistor, but designer has to compromise
between power and speed.
ALP PROGRAM
MODEL SMALL
.STACK 100
.DATA
PORTA EQU FFC0H ; PORTA ADDRESS
PORTB EQU FFC2H ; PORTB ADDRESS
PORTC EQU FFC4H ; PORTC ADDRESS
CWR EQU FFC6H ; CONTROL PORT ADDRESS
PHASEC EQU 03H
PHASEB EQU 06H ; SEQUENCE IN SERIES TO ROTATE MOTOR
PHASED EQU 0CH ; IN CLOCKWISE DIRECTION
PHASEA EQU 09H
.CODE
START:
MOV AL,@DATA
MOV DX,CTL
OUT DX,AL
AGAIN:
MOV AL,PHASEC
MOV DX,PORTC
OUT DX,AL
MOV CX,0FFFFH
UP:
LOOP UP
MOV AL,PHASEB
MOV DX,PORTC
OUT DX,AL
MOV CX,0FFFFH
UP1:
LOOP UP1
MOV AL,PHASED
MOV DX,PORTC
OUT DX,AL
MOV CX,0FFFFH
UP2:
LOOP UP2
MOV AL,PHASEA
Page 102
MOV DX,PORTC
OUT DX,AL
MOV CX,0FFFFH
UP3:
LOOP UP3
JMP AGAIN ; REPEATE OUTPUT SEQUENCE
INT 03H
END START
Assembly Language Program to rotate Stepper Motor in Anticlockwise direction
MODEL SMALL
.STACK 100
.DATA
PORTA EQU FFC0H ; PORTA ADDRESS
PORTB EQU FFC2H ; PORTB ADDRESS
PORTC EQU FFC4H ; PORTC ADDRESS
CWR EQU FFC6H ; CONTROL PORT ADDRESS
PHASEC EQU 03H
PHASEA EQU 09H ; SEQUENCE IN SERIES TO ROTATE MOTOR
PHASED EQU 0CH ; IN ANTICLOCKWISE DIRECTION
PHASEB EQU 06H
.CODE
START:
MOV AL,@DATA
MOV DX,CTL
OUT DX,AL
AGAIN:
MOV AL,PHASEC
MOV DX,PORTC
OUT DX,AL
MOV CX,0FFFFH
UP:
LOOP UP
MOV AL,PHASEA
MOV DX,PORTC
OUT DX,AL
MOV CX,0FFFFH
UP1:
LOOP UP1
MOV AL,PHASED
MOV DX,PORTC
OUT DX,AL
MOV CX,0FFFFH
UP2:
LOOP UP2
Page 103
MOV AL,PHASEB
MOV DX,PORTC
OUT DX,AL
MOV CX,0FFFFH
UP3:
LOOP UP3
JMP AGAIN ; REPEATE OUTPUT SEQUENCE
INT 03H
END START
Concept-10
A/D & D/A Converters
Why Analog to Digital?
Signals in the real world are analog: light, sound, temperature, pressure, acceleration or other phenomenon.
So, real-world signals must be converted into digital, using a circuit called ADC (Analog-to-Digital
Converter), before they can be manipulated by digital equipment.
When you scan a picture with a scanner what the scanner is doing is an analog-to-digital conversion:
it is taking the analog information provided by the picture (light) and converting into digital.
When you record your voice on your computer, you are using an analog-to-digital converter to
convert your voice, which is analog, into digital information.
When an audio CD is recorded at a studio, once again analog-to-digital is taking place, converting
sounds into digital numbers that will be stored on the disc.
Whenever we need the analog signal back, the opposite conversion – digital-to-analog, which is done
by a circuit called DAC, Digital-to-Analog Converter – is needed.
When you play an audio CD, what the CD player is doing is reading digital information stored on the
disc and converting it back to analog so you can hear the audio.
Page 104
ADC 0808 is an 8 channel, 8 bit ADC. It can convert an analog voltage input into an 8 bit digital
data output.
To select an input out of 8 options, there are three select lines (C, B and A). We put a channel
number on these lines (0…7) and latch it using ALE. SOC signal is given to indicate start of
conversion.
The channel voltage is internally sampled and held into a capacitor. Conversion takes place
internally using “Successive Approximations Algorithm”.
Reference voltage for conversion is provided using +Vref and –Vref. The clock supply needed for
conversion is given through CLK (typically ~ 1MHz).
The end of conversion is indicated by the ADC using EOC signal. Now we give the OE signal
enabling 8-bit data output from the ADC to 8255.
This data from 8255 is now transferred to the microprocessor. The process is repeated for subsequent
channels, by changing the channel number. ADCs have a vast use in the modern electronic world for
Data Acquisition Systems. They can be used for temperature sensing, voice recording, speed sensing
etc.
Page 105
Features
- Easy interface to all microprocessors
- Operates ratio metrically or with 5 VDC or analog span adjusted voltage reference
- No zero or full-scale adjust required
- 8-channel multiplexer with address logic
- 0V to 5V input range with single 5V power supply
- Outputs meet TTL voltage level specifications
- ADC0808 equivalent to MM74C949
- ADC0809 equivalent to MM74C949-1
Page 106
DAC
A Digital to Analog Converter (DAC) converts a digital input signal into an analog output signal. The
digital signal is represented with a binary code, which is a combination of bits 0 and 1.
Pi Name Description
n
1 NC No connection
2 GND Ground
3 VEE Negative power supply
4 IO Output signal pin
5 A1 Digital input bit 1 (Most Significant Bit)
6 A2 Digital input bit 2
7 A3 Digital input bit 3
8 A4 Digital input bit 4
Page 107
9 A5 Digital input bit 5
10 A6 Digital input bit 6
11 A7 Digital input bit 7
12 A8 Digital input bit 8 (Least Significant Bit)
13 VCC Positive power supply
14 VREF+ Positive reference voltage
15 VREF- Negative reference voltage
16 COMPENSATION Compensation capacitor pin
DAC 0808 is an 8 bit Digital to Analog Converter. It can convert an 8 bit digital data input into an
analog voltage output.
Reference voltage for conversion is provided using +Vref and –Vref. The output can be amplified
(optional) using an op-amp.
DACs are used in various applications such as Waveform generation, PWM, Motor control
Applications, DSP etc. Here we connect the output to a display device like a CRO.
By simple programming we can generate several types of wave forms like Ramp, Saw-tooth,
Triangular waveform etc.
Page 108
Features:
Applications
Assembly language program in 8086 to generate a symmetrical square wave with 1KHz frequency? Give the
necessary circuit set up with a DAC.
Assume selected counter is Counter-1, Mode for Square wave is Mode-3, Address for Counter 1 is 82H
Calculation of CWR:
Page 109
Interface ADC 0808 with 8086 using 8255 ports. Use port A of 8255 for transferring digital data output of
ADC to the CPU and port C for control signals. Assume that an analog input is present at I/P2 of the ADC
and a clock input of suitable frequency in available for ADC. Draw the schematic and write required ALP.
Page 110
Important questions from concept-9.
1. Interface ADC 0808 with 8086 using 8255 ports. Use port A of 8255 for transferring digital data
output of ADC to the CPU and port C for control signals. Assume that an analog input is present at
I/P2 of the ADC and a clock input of suitable frequency in available for ADC. Draw the schematic
and write required ALP.
2. Discuss the applications of A-to-D and D-to-A converters.
3. Write an assembly language program in 8086 to generate a symmetrical square wave with 1KHz
frequency? Give the necessary circuit set up with a DAC.
1. The device that enables the microprocessor to read data from the external devices is
a) printer
b) joystick
c) display
d) reader
2. The number of counters that are present in the programmable timer device 8254 is
a) 1
b) 2
c) 3
d) 4
3. The generation of a square wave is possible in the mode
a) mode 1
b) mode 2
c) mode 3
d) mode 4
4. The number of hardware interrupts that the processor 8085 consists of is
a) 1
b) 3
c) 5
d) 7
5. The interrupt control logic
a) manages interrupts
b) manages interrupt acknowledge signals
c) accepts interrupt acknowledge signal
d) all of the mentioned
6. The registers that store the keyboard and display modes and operations programmed by CPU are
a) I/O control and data buffers
b) Control and timing registers
Page 111
c) Return buffers
d) Display address registers
7. When a key is pressed, a debounce logic comes into operation in
a) scanned keyboard special error mode
b) scanned keyboard with N-key rollover
c) scanned keyboard mode with 2 key lockout
d) sensor matrix mode
Answers :
1. b 2. c 3. c 4. c 5.d 6. b 7. c
Concept-I: Introduction
The 80386 is an advanced 32-bit microprocessor optimized for multitasking operating systems and
designed for applications needing very high performance.
The 32-bit registers and data paths support 32-bit addresses and data types.
The processor can address up to four gigabytes of physical memory and 64 terabytes (2^(46) bytes) of
virtual memory.
Page 112
The on-chip memory-management facilities include address translation registers, advanced multitasking
hardware, a protection mechanism, and paged virtual memory.
Special debugging registers provide data and code breakpoints even in ROM-based software.
Register Organisation
•The 80386 has eight 32 - bit general purpose
registers which may be used as either 8 bit or 16 bit
registers.
•A 32 - bit register known as an extended register,
is represented by the register name with prefix E.
Example : A 32 bit register corresponding to AX
is EAX, similarly BX is EBX etc.
•The 16 bit registers BP, SP, SI and DI in 8086 are
now available with their extended size of 32 bit and
are names as EBP,ESP,ESI and EDI.
•AX represents the lower 16 bit of the 32 bit
register EAX.
• BP, SP, SI, DI represents the lower 16 bit of their
32 bit counterparts, and can be used as independent
16 bit registers.
•The six segment registers available in 80386 are
CS, SS, DS, ES, FS and GS.
•The CS and SS are the code and the stack segment
registers respectively, while DS, ES, FS, GS are 4 data segment registers.
•A 16 bit instruction pointer IP is available along with 32 bit counterpart EIP.
•Flag Register of 80386: The Flag register of 80386 is a 32 bit register. Out of the 32 bits, Intel has reserved
bits D18 to D31, D5 and D3, while D1 is always set at 1.
•VM - Virtual Mode Flag: If this flag is set, the 80386 enters the virtual 8086 mode within the protection
Page 113
mode. This is to be set only when the 80386 is in protected mode. In this mode, if any privileged instruction
is executed an exception 13 is generated. This bit can be set using IRET instruction or any task switch
operation only in the protected mode.
•RF- Resume Flag: This flag is used with the debug register breakpoints. It is checked at the starting of
every instruction cycle and if it is set, any debug fault is ignored during the instruction cycle. The RF is
automatically reset after successful execution of every instruction, except for IRET and POPF instructions.
•Also, it is not automatically cleared after the successful execution of JMP, CALL and INT instruction
causing a task switch. These instruction are used to set the RF to the value specified by the memory data
available at the stack. •Segment Descriptor Registers: This registers are not available for programmers,
rather they are internally used to store the descriptor information, like attributes, limit and base addresses of
segments.
The six segment registers have corresponding six 73 bit descriptor registers. Each of them contains 32 bit
base address, 32 bit base limit and 9 bit attributes. These are automatically loaded when the corresponding
segments are loaded with selectors.
•Control Registers: The 80386 has three 32 bit control registers CR0, CR2 and CR3 to hold global machine
status independent of the executed task. Load and store instructions are available to access these registers.
•System Address Registers: Four special registers are defined to refer to the descriptor tables supported by
80386. •The 80386 supports four types of descriptor table, viz. global descriptor table (GDT), interrupt
descriptor table (IDT), local descriptor table (LDT) and task state segment descriptor (TSS).
•Debug and Test Registers: Intel has provide a set of 8 debug registers for hardware debugging. Out of these
eight registers DR0 to DR7, two registers DR4 and DR5 are Intel reserved.
•The initial four registers DR0 to DR3 store four program controllable breakpoint addresses, while DR6 and
DR7 respectively hold breakpoint status and breakpoint control information.
•Two more test register are provided by 80386 for page cacheing namely test control and test status register.
The Physical memory of 80386 is organized as a sequence of bytes. Each byte is assigned a unique address
that ranges from zero to a maximum of 2^(32) -1 (4 gigabytes). The logical memory of 80386 can address
up to 2^(46) bytes (64 terabytes).
The two types of memory models in 80386 are
A "flat" address space consisting of a single array of up to 4 gigabytes.
A segmented address space consisting of a collection of segments.
Both the models provide memory protection.
Flat Model
In a flat model, a programmer sees memory as a single array up to 4GB. The processor maps the 4 GB flat
space onto the physical address space by the address translation mechanisms.
A pointer into this flat address space is a 32-bit ordinal number that may range from 0 to 2^(32) -1.
Relocation of separately-compiled modules in this space must be performed by systems software (e.g.,
linkers, locators, binders, loaders)
Segmented Model
In Segmented model, address space is viewed as collection of segments. The segmented model can consist
of 16,383 segments.
Page 114
Applications programmers view the logical address space of the 80386 as a collection of up to 16,383 one-
dimensional subspaces, each with a specified length. Each of these linear subspaces is called a segment. A
segment is a unit of contiguous address space. Segment sizes may range from one byte up to a maximum of
2^(32) bytes (4 gigabytes).
A pointer in this address space consists of two parts:
A segment selector, which is a 16-bit field that identifies a segment.
An offset, which is a 32-bit ordinal that addresses to the byte level within a segment.
Important Questions from concept-4:
1. Explain the concept of memory organization of 80386.
Memory Addressing in Real Mode: In the real mode, the 80386 can address at the most 1Mbytes of physical
memory using address lines A0-A19.
•Paging unit is disabled in real addressing mode, and hence the real addresses are the same as the physical
addresses.
•To form a physical memory address, appropriate segment registers contents (16-bits) are shifted left by four
positions and then added to the 16-bit offset address formed using one of the addressing modes, in the same
way as in the 80386 real address mode.
•The segment in 80386 real mode can be read, write or executed, i.e. no protection is available.
•Any fetch or access past the end of the segment limit generate exception 13 in real address mode.
•The segments in 80386 real mode may be overlapped or non-overlapped.
•The interrupt vector table of 80386 has been allocated 1Kbyte space starting from 00000H to 003FFH.
Segmentation
•DESCRIPTOR TABLES: These descriptor tables and registers are manipulated by the operating system to
ensure the correct operation of the processor, and hence the correct execution of the program.
•Three types of the 80386 descriptor tables are listed as follows:
•GLOBAL DESCRIPTOR TABLE ( GDT )
•LOCAL DESCRIPTOR TABLE ( LDT )
•INTERRUPT DESCRIPTOR TABLE ( IDT )
•DESCRIPTORS: The 80386 descriptors have a 20-bit segment limit and 32-bit segment address. The
descriptor of 80386 are 8-byte quantities access right or attribute bits along with the base and limit of the
segments.
•Descriptor Attribute Bits: The A (accessed) attributed bit indicates whether the segmenthas been accessed
by the CPU or not.
Page 116
•The TYPE field decides the descriptor type and hence the segment type.
•The S bit decides whether it is a system descriptor (S=0) or code/data segment descriptor ( S=1).
•The DPL field specifies the descriptor privilege level.
•The D bit specifies the code segment operation size. If D=1, the segment is a 32-bit operand segment, else,
it is a 16-bit operand segment.
•The P bit (present) signifies whether the segment is present in the physical memory or not. If P=1, the
segment is present in the physical memory.
•The G (granularity) bit indicates whether the segment is page addressable. The zero bit must remain zero
for compatibility with future process.
•The AVL (available) field specifies whether the descriptor is for user or for operating system.
•The 80386 has five types of descriptors listed as follows:
1.Code or Data Segment Descriptors.
2.System Descriptors.
3.Local descriptors.
4.TSS (Task State Segment) Descriptors.
5.GATE Descriptors.
•The 80386 provides a four level protection mechanism exactly in the same way as the 80286 does.
Page 117
•Once the 80386 enters the protected mode from the real mode, it cannot return back to the real mode
without a reset operation.
•Thus, the virtual 8086 mode of operation of 80386, offers an advantage of executing 8086 programs while
in protected mode.
•The address forming mechanism in virtual 8086 mode is exactly identical with that of 8086 real mode.
•In virtual mode, 8086 can address 1Mbytes of physical memory that may be anywhere in the 4Gbytes
address space of the protected mode of 80386.
•Like 80386 real mode, the addresses in virtual 8086 mode lie within 1Mbytes of memory.
•In virtual mode, the paging mechanism and protection capabilities are available at the service of the
programmers.
•The 80386 supports multiprogramming, hence more than one programmer may be use the CPU at a time.
•Paging unit may not be necessarily enable in virtual mode, but may be needed to run the 8086 programs
which require more than 1Mbyts of memory for memory management function.
•In virtual mode, the paging unit allows only 256 pages, each of 4Kbytes size.
•Each of the pages may be located anywhere in the maximum 4Gbytes physical memory.
The virtual mode allows the multiprogramming of 8086 applications.
•The virtual 8086 mode executes all the programs at privilege level 3.Any of the other programmes may
deny access to the virtual mode programs or data.
•However, the real mode programs are executed at the highest privilege level, i.e. level 0.
•The virtual mode may be entered using an IRET instruction at CPL=0 or a task switch at any CPL,
executing any task whose TSS is having a flag image with VM flag set to 1.
•The IRET instruction may be used to set the VM flag and consequently enter the virtual mode.
•The PUSHF and POPF instructions are unable to read or set the VM bit, as they do not access it.
•Even in the virtual mode, all the interrupts and exceptions are handled by the protected mode interrupt
handler.
•To return to the protected mode from the virtual mode, any interrupt or execution may be used.
•As a part of interrupt service routine, the VM bit may be reset to zero to pull back the 80386 into protected
mode.
Page 118
Concept-VIII: Memory Paging Mechanism
PAGING OPERATION: Paging is one of the memory management techniques used for virtual memory
multitasking operating system.
•The segmentation scheme may divide the physical memory into a variable size segments but the paging
divides the memory into a fixed size pages.
•The segments are supposed to be the logical segments of the program, but the pages do not have any logical
relation with the program.
•The pages are just fixed size portions of the program module or data.
•The advantage of paging scheme is that the complete segment of a task need not be in the physical memory
at any time.
•Only a few pages of the segments, which are required currently for the execution need to be available in the
physical memory. Thus the memory requirement of the task is substantially reduced, relinquishing the
available memory for other tasks.
•Whenever the other pages of task are required for execution, they may be fetched from the secondary
storage.
•The previous page which are executed, need not be available in the memory, and hence the space occupied
by them may be relinquished for other tasks.
•Thus paging mechanism provides an effective technique to manage the physical memory for multitasking
systems.
•Paging Unit: The paging unit of 80386 uses a two level table mechanism to convert a linear address
provided by segmentation unit into physical addresses.
•The paging unit converts the complete map of a task into pages, each of size 4K. The task is further handled
in terms of its page, rather than segments.
•The paging unit handles every task in terms of three components namely page directory, page tables and
page itself.
•Paging Descriptor Base Register: The control register CR2 is used to store the 32-bit linear address at
which the previous page fault was detected.
•The CR3 is used as page directory physical base address register, to store the physical starting address of
the page directory.
•The lower 12 bit of the CR3 are always zero to ensure the page size aligned directory. A move operation to
CR3 automatically loads the page table entry caches and a task switch operation, to load CR0 suitably.
•Page Directory : This is at the most 4Kbytes in size. Each directory entry is of 4 bytes, thus a total of 1024
entries are allowed in a directory.
•The upper 10 bits of the linear address are used as an index to the corresponding page directory entry. The
page directory entries point to page tables.
•Page Tables: Each page table is of 4Kbytes in size and many contain a maximum of 1024 entries. The page
table entries contain the starting address of the page and the statistical information about the page.
•The upper 20 bit page frame address is combined with the lower 12 bit of the linear address. The address
bits A12- A21 are used to select the 1024 page table entries. The page table can be shared between the tasks.
•The P bit of the above entries indicate, if the entry can be used in address translation.
•If P=1, the entry can be used in address translation, otherwise it cannot be used.
•The P bit of the currently executed page is always high.
•The accessed bit A is set by 80386 before any access to the page. If A=1, the page is accessed, else
unaccessed.
•The D bit ( Dirty bit) is set before a write operation to the page is carried out. The D-bit is undefined for
page director entries.
Page 119
•The OS reserved bits are defined by the operating system software.
•The User / Supervisor (U/S) bit and read/write bit are used to provide protection. These bits are decoded to
provide protection under the 4 level protection model.
•The level 0 is supposed to have the highest privilege, while the level 3 is supposed to have the least
privilege.
•This protection provide by the paging unit is transparent to the segmentation unit.
Page 120
Important Questions from concept-8:
1. Draw and discuss the paging mechanism of 80386 in detail.
2. Draw and discuss the paging mechanism of 80386 in detail.
3. What is Paging? Explain its use.
4. Explain segmentation and paging schemes in 80386.
Page 121
80386 Microprocessor is a 32-bit processor that holds the ability to carry out 32-bit operation in one cycle. It has
data and address bus of 32-bit each. Thus has the ability to address 4 GB (or 2 32) of physical memory.
Multitasking and protection capability are the two key characteristics of 80386 microprocessor. 80386 has an
internal dedicated hardware that permits multitasking. The 8086 is a 16-bit microprocessor and 80286 was an
advancement of 8086 with some additional characteristics. But with the advent of technology Intel introduced a 32-
bit microprocessor whose processing speed was twice as that of 80286 microprocessor. This was 80386
microprocessor that was designed by Intel in October 1985 and was an upgraded version of 80286 microprocessor.
Features of 80386
The A (accessed) attributed bit indicates whether the segment has been accessed by the CPU or not.
•The TYPE field decides the descriptor type and hence the segment type.
•The S bit decides whether it is a system descriptor (S=0) or code/data segment descriptor ( S=1).
•The DPL field specifies the descriptor privilege level.
•The D bit specifies the code segment operation size. If D=1, the segment is a 32-bit operand segment, else,
it is a 16-bit operand segment.
•The P bit (present) signifies whether the segment is present in the physical memory or not. If P=1, the
segment is present in the physical memory.
•The G (granularity) bit indicates whether the segment is page addressable. The zero bit must remain zero
for compatibility with future process.
•The AVL (available) field specifies whether the descriptor is for user or for operating system.
•The 80386 has five types of descriptors listed as follows:
1. Code or Data Segment Descriptors. 2. System Descriptors. 3. Local descriptors. 4. TSS (Task State
Segment) Descriptors. 5. GATE Descriptors.
•The 80386 provides a four level protection mechanism.
Control Registers: The 80386 has three 32 bit control registers CR0, CR2 and CR3 to hold global machine
status independent of the executed task.
Page 122
Load and store instructions are available to access these registers
Common tasks performed by control registers include interrupt control, switching the addressing mode,
paging control, and coprocessor control.
CR0 contains system control flags, which control or indicate conditions that apply to the system as a whole,
not to an individual task.
PE (Protection Enable, bit 0): Setting PE causes the processor to begin executing in protected mode.
Resetting PE returns to real-address mode.
MP (Math Present, bit 1): MP controls the function of the WAIT instruction, which is used to coordinate a
coprocessor.
EM (Emulation, bit 2):EM indicates whether coprocessor functions are to be emulated.
TS (Task Switched, bit 3):The processor sets TS with every task switch and tests TS when interpreting
coprocessor instructions.
ET (Extension Type, bit 4):ET indicates the type of coprocessor present in the system (80287 or 80387).
PG (Paging, bit 31): PG indicates whether the processor uses page tables to translate linear addresses into
physical addresses.
CR2:
CR2 is used for handling page faults when PG is set. The processor stores in CR2 the linear address that
triggers the fault.
Contains a value called Page Fault Linear Address (PFLA). When a page fault occurs, the address the
program attempted to access is stored in the CR2 register.
CR3: Used when virtual addressing is enabled, hence when the PG bit is set in CR0, CR3 enables the
processor to translate linear addresses into physical addresses by locating the page directory and page tables
for the current task.
Typically, the upper 20 bits of CR3 become the page directory base register (PDBR), which stores the
physical address of the first page directory entry.
CR1: Reserved for Intel future purpose.
Bit
Bit Field: A group of at the most 32 bits (4bytes)
Bit String: A string of contiguous bits of maximum 4Gbytes in length.
Signed Byte: Signed byte data
Unsigned Byte: Unsigned byte data.
Integer word: Signed 16-bit data.
Long Integer: 32-bit signed data represented in 2's complement form.
Unsigned Integer Word: Unsigned 16-bit data
Unsigned Long Integer: Unsigned 32-bit data
Signed Quad Word: A signed 64-bit data or four word data.
Unsigned Quad Word: An unsigned 64-bit data.
Offset: 16/32-bit displacement that points a memory location using any of the addressing modes.
Page 123
Pointer: This consists of a pair of 16-bit selector and 16/32-bit offset.
Character: An ASCII equivalent to any of the alphanumeric or control characters.
Strings: These are the sequences of bytes, words or double words. A string may contain minimum
one byte and maximum 4 Gigabytes.
BCD: Decimal digits from 0-9 represented by unpacked bytes.
Packed BCD: This represents two packed BCD digits using a byte, i.e. from 00 to 99.
support various debug tools that trap on reads or writes to selected addresses.
allow access to more RAM (wider physical address) than the user-level address seems to support
(banking)
support many different programs all in RAM at the same time at different physical RAM locations, even
though they were all compiled to run at location 0x300.
allow a program to successfully read and write a large block of data using normal LOAD and STORE
instructions as if it were all in RAM, even though the machine doesn't have that much RAM (paging
with virtual memory)
support a "protected" supervisor-level system that can run buggy or malicious user-level code in an
isolated sandbox at full speed without damaging other user-level programs or the supervisor system
itself -- Popek and Goldberg virtualization, W xor X memory protection, etc. or some combination of
the above.
Cache Memory
A memory is just like a human brain. It is used to store data and instructions. Computer memory is the
storage space in the computer, where data is to be processed and instructions required for processing are
stored. The memory is divided into large number of small parts called cells. Each location or cell has a
unique address, which varies from zero to memory size minus one. For example, if the computer has 64k
Page 124
words, then this memory unit has 64 * 1024 = 65536 memory locations. The address of these locations
varies from 0 to 65535.
Memory is primarily of three types −
Cache Memory
Primary Memory/Main Memory
Secondary Memory
Cache Memory
Cache memory is a very high speed semiconductor memory which can speed up the CPU. It acts as a buffer
between the CPU and the main memory. It is used to hold those parts of data and program which are most
frequently used by the CPU. The parts of data and programs are transferred from the disk to cache memory
by the operating system, from where the CPU can access them.
Advantages
Disadvantages
Page 125
Based Index addressing Mode
Based Scaled Index addressing Mode
Based Index addressing Mode with Displacement
Based Scaled Index addressing Mode with Displacement
Register addressing Mode
The data is stored in a register and it is referred using a particular register. All register accept IP used in this
addressing mode. The 8/16/32 bit data required to execute an instruction is present in 8/16/32 bit register is
given along with the instruction is called “Register addressing mode. “
Example : ADD EAX,EBX
Immediate addressing Mode
In this addressing mode, immediate data is part of instruction. The 8/16/32 bit data required to execute an
instruction is given directly along with the instruction is called “Immediate addressing mode”.
Example : Mov EAX,12345678H
Direct addressing Mode
The 8/16/32 bit data required to execute an instruction is present in memory location and effective address
of this memory location is given directly along with the instruction then it is called “Direct addressing
mode”. Example : Mov AX,[5000H]
Register Indirect addressing Mode
A base register will contain the address of operand Example: MOV [ECX], EDX The 8/16/32 bit data
required to execute an instruction is present in memory location and effective address of that memory
location is present in a 32 bit register and the name of this register is given along with the instruction then it
is called “Register Indirect addressing mode”.
Based addressing Mode
A BASE register's contents is added to a DISPLACEMENT to form the operands offset.
Example: MOV ECX, [EAX+24]
Index addressing Mode
An INDEX register's contents is added to a DISPLACEMENT to form the operands offset.
EXAMPLE: ADD EAX, TABLE[ESI]
The 8/16/32 bit data required to execute an instruction is present in memory location and effective address
of that memory location is obtained by adding three contents : 1. The 32 bit content of base register 2. The
32 bit content of Index Register 3. Displacement.
The 80386 have a family of scaled modes. In the case of scaled modes, any of the index register values can
be multiplied by a valid scale factor to obtain the displacement. The valid scale factors are 1,2, 4, and 8.
Scaled Indexed Mode: The contents of an index register are multiplied by a scale factor that may be added
further to get the operand offset. Ex. MOV EBX, LIST [ESI* 2] MUL ECX, LIST [EBP*4]
Based Scaled Indexed mode: The contents of an index register are multiplied by a scale factor and then
added to base register to obtain the offset. Ex: MOV EBX, [EDX*4] [ECX] MOV EAX, [EBX*2] [ECX].
Based scaled indexed mode with displacement: the contents of an index register are multiplied by a scale
factor and the result is added to a base register and a displacement to get the offset of an operand. Ex: MOV
EAX, LIST [ESI* 2] [EBX+0800] MUL EBX, LIST [EDI*8] [ECX+0100].
Page 126
B. Paging Unit
1. Bus Interface Unit
The bus interface unit or BIU holds a 32-bit bidirectional data bus as well as 32-bit address bus. Whenever a
need for an instruction or a data fetch is generated by the system then the BIU generates signals (according
to the priority) for activating the data and address bus in order to fetch the data from the desired address.
The BIU connects the peripheral devices through the memory unit and also controls the interfacing of
external buses with the coprocessors.
2. Code Prefetch Unit
This unit fetches the instructions stored in the memory by making use of system buses. Whenever the system
generates a need for an instruction then the code prefetch unit fetches that instruction from the memory and
stores it in 16-byte prefetch queue.
So to speed up the operation this unit fetches the instructions in advance and the queue stores these
instructions.
The sequence in which the instructions are fetched and gets stored in the queue depends on the order they
exist in the memory.
As this unit fetches one double word in single access. So, in such a case, it is not necessary that each time
only a single instruction will be fetched, as the fetched instruction can be parts of two different instructions.
It is to be noted here that, code prefetching holds lower priority than data transferring. As whenever, a need
for data transfer is generated by the system then immediately the code prefetcher leaves the control over the
buses. So that the BIU can transfer the required data.
But prefetching of instruction and storing it in the queue reduces the wait for the upcoming instruction to
almost zero.
3. Instruction Decode Unit
We know that instructions in the memory are stored in the form of bits. So, this unit decodes the instructions
stored in the prefetch queue. Basically the decoder changes the machine language code into assembly
language and transfers it to the processor for further execution.
4. Execution Unit
The decoded instructions are stored in the decoded instruction queue. So, these instructions are provided to
the execution unit in order to execute the instructions.
The execution unit controls the execution of the decoded instructions. This unit has a 32-bit ALU, that
performs the operation over 32-bit data in one cycle. Also, it consists of 8 general purpose as well as 8
special purpose registers. These are used for data handling and calculation of offset address.
5. Memory Management Unit
This unit has two separate units within it. These are
1. Segmentation Unit and
2. Paging Unit
Segmentation unit: The segmentation unit plays a vital role in the 80836 microprocessor. It offers
protection mechanism in order to protect the code or data present in the memory from application programs.
It gives 4 level protection to the data or code present in the memory. Every information in the memory is
assigned a privilege level from PL0 to PL3. Here, PL0 holds the highest priority and PL3 holds the lowest
priority.
Suppose a file (either data or code) is needed to be accessed is stored in the memory at PL0. Then only those
programs which are working at PL0 would be able to access that file. While other programs will not be able
to access the same.
Also, if a file is present at PL1, then programs of PL0 and PL1 both can access it. As PL0 has higher priority
than PL1. So, for protection purpose the main part of OS is stored in PL0 while PL3 holds the user
programs.
Providing protection to the data or code inside the system is the most advantageous factor that was first
given by 80386 microprocessor.
Paging Unit: The paging unit operates only in protected mode and it changes the linear address into
physical address. As the programmer only provides the virtual address and not the physical address.
Page 127
The segmentation unit controls the action of paging unit, as the segmentation unit has the ability to convert
logical address into linear address at the time of executing an instruction.
Basically it changes the overall task map into pages and each page has a size of 4K. This allows the
handling of task in the form of pages rather than segments.
Paging unit supports multitasking. This is so because the physical memory is not required to hold the whole
segment of any task. Despite, only that part of the segment which is needed to be currently executed must be
stored in that memory whose physical address is calculated by the paging unit.
This resultantly reduces the memory requirement and hence this frees the memory for other tasks. Thus by
this we get an effective way for managing the memory to support multitasking.
•VM - Virtual Mode Flag: If this flag is set, the 80386 enters the virtual 8086 mode within the protection
mode. This is to be set only when the 80386 is in protected mode. In this mode, if any privileged instruction
is executed an exception 13 is generated. This bit can be set using IRET instruction or any task switch
operation only in the protected mode.
Page 128
•RF- Resume Flag: This flag is used with the debug register breakpoints. It is checked at the starting of
every instruction cycle and if it is set, any debug fault is ignored during the instruction cycle. The RF is
automatically reset after successful execution of every instruction, except for IRET and POPF instructions.
Bit Label EFLAGS Flag Description
Carry Flag: Set by arithmetic instructions which generate either a carry or borrow. Set when
0 CF
an operation generates a carry to or a borrow from a destination operand.
Parity flag: Set by most CPU instructions if the least significant (aka the low-order bits) of the
2 PF
destination operand contain an even number of 1's.
Auxiliary Carry Flag: Set if there is a carry or borrow involving bit 4 of EAX. Set when a
4 AF CPU instruction generates a carry to or a borrow from the low-order 4 bits of an operand. This
flag is used for binary coded decimal (BCD) arithmetic.
6 ZF Zero Flag: Set by most instructions if the result an operation is binary zero.
Sign Flag: Most operations set this bit the same as the most significant bit (aka high-order
7 SF
bit) of the result. 0 is positive, 1 is negative.
Trap Flag: (sometimes named a Trace Flag.) Permits single stepping of programs. After
executing a single instruction, the processor generates an internal exception 1. When Trap Flag
8 TF
is set by a program, the processor generates a single-step interrupt after each instruction. A
debugging program can use this feature to execute a program one instruction at a time.
Interrupt Enable Flag: when set, the processor recognizes external interrupts on the INTR
9 IF pin. When set, interrupts are recognized and acted on as they are received. The bit can be
cleared to turn off interrupt processing temporarily.
Direction Flag: Set and cleared using the STD and CLD instructions. It is used in string
10 DF processing. When set to 1, string operations process down from high addresses to low
addresses. If cleared, string operations process up from low addresses to high addresses.
Overflow Flag: Most arithmetic instructions set this bit, indicating that the result was too large
11 OF to fit in the destination. When set, it indicates that the result of an operation is too large or too
small to fit in the destination operand.
12-
IOPL Input/Output privilege level flags: Used in protected mode to generate four levels of security.
13
Nested Task Flag: Used in protected mode. When set, it indicates that one system task has
14 NT
invoked another via a CALL Instruction, rather than a JMP.
Resume Flag: Used by the debug registers DR6 and DR7. It enables you to turn off certain
16 RF
exceptions while debugging code.
17 VM Virtual 8086 Mode flag: Permits 80386 to behave like a high speed 8086.
Although all flags serve a purpose, most programs require only the carry, zero, sign, and direction
flags.
Page 129
UNIT-V: Intel 8051 MICROCONTROLLER:
Concept-I: Introduction
Concept-II: Architecture
Concept-III: Hardware Concepts: Input / Output Ports and Circuits
Concept-IV: External Memory
Concept-V: Counters/Timers
Concept-VI: Serial Data Input/Output
Concept-VII: Interrupts
Concept-VIII: Assembly Language Programming
Concept-IX: Addressing Modes
Concept-X: Instructions
Concept-XI: Simple Programs.
Concept-XII: Interfacing: Keyboard
Concept-XIII: Displays (LED, 7-segment display unit)
Concept-XIV: A/D and D/A converters.
Additional Concepts: 8051 Pin configuration
****
Concept-I: Introduction
8051 is one of the first most popular microcontroller also known as MCS-51. It was introduced by
Intel in the year 1981.
Initially it came out as N-type metal-oxide-semiconductor (NMOS) based microcontroller, but
later versions were based on complementary metal-oxide-semiconductor (CMOS) technology.
These microcontrollers were named as 80C51, where C in the name tells that it is based on CMOS
technology.
It is an 8-bit microcontroller which means data bus is of 8-bits. Therefore, it can process 8-bits at a
time.
It is used in wide variety of embedded systems like robotics, remote controls, automotive industry,
telecom applications, power tools etc .
COMMERCIAL MICROCONTROLLERS
There are various manufacturers who are supplying various types of microcontrollers suitable for
different applications depending on the power consumption and the available features. They are given below
in tables. First the various members of INTEL 51 family are given in below table.
INTEL MCS 51 Family
Concept-II: Architecture
Page 130
A microcontroller is designed by Intel in 1981. It is an 8-bit microcontroller. It is built with 40 pins
DIP (dual inline package), 4kb of ROM storage and 128 bytes of RAM storage, 2 16-bit timers.
It consists of are four parallel 8-bit ports, which are programmable as well as addressable as per the
requirement. An on-chip crystal oscillator is integrated in the microcontroller having crystal frequency of
12 MHz.
The difference between a Microprocessor and a Microcontroller is the availability of the on – chip
peripherals like Memory (both RAM and ROM), I/O Ports, Timers / Counters, Communication Interfaces
(like Serial Port), etc.
Page 131
Registers of 8051
8 bit Registers
The commonly used registers are R0 to R7, A, B, PSW these are all 8 bit registers. The registers
associated with the ALU are A, B and PSW. In most operations, ALU performs specified operation on
registers 'A' and 'B' and the result is stored back in 'A'. Hence Register 'A' is often called accumulator.
Program Status Word
'PSW' indicates various flags associated with the operation performed. Figure below shows the 8 bits
of the PSW register and their function is shown in the table.
CY Carry Flag
OV Overflow flag
P Parity flag
16 bit Registers.
There are also some 16 bit registers in 8051 as shown in the figure. The program counter points to the next
instruction that the CPU executes.
Page 132
The DPTR and other special function registers like SCON, TCON, P0, P1, P2 etc will be discussed
while using microcontroller features like timers, counter, serial communication, Interrupts etc.
There are 32 8-bit registers arranged in 4 groups. These are used as general purpose registers.
2. Bit Addressable RAM
8051 has 16 bytes of RAM, which is bit addressable. It is grouped as 16, 8 byte arrays and any of the
128 bits can also be set / cleared individually.
3. Scratch PAD RAM
The third group of registers occupy addresses 2Fh-7Fh, i.e. 80 locations, and does not have any special
functions or features. Scratch pad RAM is used by the ALU, while fetching, decoding and executing the
instructions during operation of the microcontroller.
Input and Output Ports
I/O Ports or Input / Output Ports provide the microcontroller, a physical connection to the outside
world. Input Ports provide a gateway for passing on the data from the outside world with the help of sensors.
The data from the input ports is manipulated (depending on the application) and will determine the
data on the output port.
Output Ports allow microcontroller to control external devices (like motors and LEDs). Generally, all
ports in microcontrollers have dual functionality i.e. they can act as both input and output port (not at the
same time though).
Program Memory
The instructions of the CPU are stored in the Program Memory. It is usually implemented as Read
Only Memory or ROM, where the Program written in to it will be retained even when the power is down or
the system is reset.
Modern Program Memory Modules are generally made up of EEPROM (Electrically Erasable
Programmable Read – only Memory), which is a type of non – volatile memory.
In this type of memory, the data can be erased and reprogrammed using special programming
signals.
When the microcontroller is powered on or manually reset, the processor executes a set of
instructions from a pre-defined memory location (address) in the Program Memory.
Data Memory
Data Memory in a Microcontroller is responsible for storing values of variables, temporary data,
intermediate results and other data for proper operation of the program.
Data Memory is often called as RAM (Random Access Memory), which is a type of volatile
memory. It is generally organized as registers and includes both Special Function Registers (SFRs) and user
accessible memory locations.
Page 134
ALE: Address Latch Enable is an active high-output signal. If we use multiple memory chips, then this pin
is used to distinguish between them. This Pin also gives program pulse input during programming of
EPROM.
WR: Writing Signal to write content on external RAM.
RD: Reading Signal to read contents of external RAM.
Important Questions from concept-2:
1. With a neat diagram, explain the internal architecture of 8051 microcontroller.
Port 0
− The P0 (zero) port is characterized by two functions −
o When the external memory is used then the lower address byte (addresses A0A7) is applied
on it, else all bits of this port are configured as input/output.
Page 135
o When P0 port is configured as an output then other ports consisting of pins with built-in pull-
up resistor connected by its end to 5V power supply, the pins of this port have this resistor
left out.
Input Configuration
If any pin of this port is configured as an input, then it acts as if it “floats”, i.e. the input has unlimited input
resistance and in-determined potential.
Output Configuration
When the pin is configured as an output, then it acts as an “open drain”. By applying logic 0 to a port bit,
the appropriate pin will be connected to ground (0V), and applying logic 1, the external output will keep on
“floating”.
In order to apply logic 1 (5V) on this output pin, it is necessary to build an external pullup resistor.
Port 1
P1 is a true I/O port as it doesn’t have any alternative functions as in P0, but this port can be configured as
general I/O only. It has a built-in pull-up resistor and is completely compatible with TTL circuits.
Port 2
P2 is similar to P0 when the external memory is used. Pins of this port occupy addresses intended for the
external memory chip. This port can be used for higher address byte with addresses A8-A15. When no
memory is added then this port can be used as a general input/output port similar to Port 1.
Page 136
Port 3
In this port, functions are similar to other ports except that the logic 1 must be applied to appropriate bit of
the P3 register.
The chip select logic is just a simple logic that is developed using additional circuitry to choose one chip
from multiple chips. If we’re interfacing more than one chip (they may be program ROM chip or data ROM
or even data RAM), each sharing the same address space range (say 0000H to FFFFH), and the address lines
of the microcontroller has the address 5FFFH on it, which chip is this address referring to? The chip select
logic enables the microcontroller to answer that question and understand which chip to select for the
particular address required to be accessed by the user.
How does Chip Select Logic work?
The central processing unit (CPU) provides the address of the location from where the data is desired. This
address is in the form of a mixture of address lines and some control lines. The decoding circuit is
responsible for decoding this information and locating the required memory block based on these signals.
The three different ways to generate chip select logic
Page 137
3. Programmable logic
External ROM – For program/data
ROM is a type of non-volatile memory. The data is not lost, even if the power supply to the IC is taken off.
ROM can be classified into:
PROM
EPROM
EEPROM
Flash EPROM
Mask ROM
External addressable ROM for the 8051 is of 128KB of address space which is be divided into two parts:
To access the program space, we require a program counter (PC), it locates and fetches instructions. We use
the MOVC A, @A+DPTR instruction to get data, where C stands for code. It is 64K bytes in size.
How to access program space?
For storing the program code, we can either use on-chip ROM or off-chip ROM or a combination of both
on-chip and off-chip ROM depending on the status of the EA pin.
1. Internal Program Memory (4KB) i.e. from 0000H to 0FFFH + External Program Memory (60KB)
i.e. from 1000H to FFFFH. We can select this mode by making EA = 1.
2. Total External Program Memory (64KB), i.e., over the entire range of 0000H to FFFFH. We can
select this mode by making EA = 0.
To access the data memory space, we use the instruction MOVX A, @DPTR. Connect the RD pin (PIN 3.7)
to the OE of data ROM and give an active low signal to the Chip enable (CE) pin of data ROM. Here we
access the data from the external ROM containing the data and transferred to internal RAM.
External RAM – For data
Page 138
The RAM memory is called volatile memory since cutting off the power to the IC will result in the loss of
data. An improvement of the default RAM is RAWM (read and write memory), which in contrast to ROM,
to which we cannot write any data.
There are three types of RAM:
If we want to connect external data memory, i.e. SRAM, we must connect the RD (Pin 3.7) and WR (Pin
3.6) to the SRAM data memory. In writing data to external data RAM, we use the instruction.
MOVX @DPTR, A
We can also use NV-RAM, as it is the most efficient type of RAM whose memory remains even after the
power to the IC is cut off. First off what is NV-RAM? It stands for non-volatile RAM and is the memory
element which combines the best features of both RAM and ROM.
Features of NV-RAM:
The read and write ability of RAM, plus the non-volatility of ROM
Extremely power-efficient SRAM cells built out of CMOS
Consists of an internal lithium battery as a backup energy source
Consists of intelligent control circuitry.
Concept-V: Counters/Timers
A timer is a specialized type of clock which is used to measure time intervals. A timer that counts from
zero upwards for measuring time elapsed is often called a stopwatch. It is a device that counts down from a
specified time interval and used to generate a time delay, for example, an hourglass is a timer.
A counter is a device that stores (and sometimes displays) the number of times a particular event or
process occurred, with respect to a clock signal. It is used to count the events happening outside the
microcontroller. In electronics, counters can be implemented quite easily using register-type circuits such
as a flip-flop.
Page 139
The points that differentiate a timer from a counter are as follows −
Timer Counter
Maximum count rate is 1/12 of Maximum count rate is 1/24 of the oscillator
the oscillator frequency. frequency.
A timer uses the frequency of the A counter uses an external signal to count pulses.
internal clock, and generates
delay.
The 8051 has two timers, Timer 0 and Timer 1. They can be used as timers or as event counters. Both
Timer 0 and Timer 1 are 16-bit wide. Since the 8051 follows an 8-bit architecture, each 16 bit is accessed
as two separate registers of low-byte and high-byte.
Timer 0 Register
The 16-bit register of Timer 0 is accessed as low- and high-byte. The low-byte register is called TL0
(Timer 0 low byte) and the high-byte register is called TH0 (Timer 0 high byte). These registers can be
accessed like any other register. For example, the instruction
MOV TL0, #4H moves the value into the low-byte of Timer #0.
Timer 1 Register
The 16-bit register of Timer 1 is accessed as low- and high-byte. The low-byte register is called TL1
(Timer 1 low byte) and the high-byte register is called TH1 (Timer 1 high byte). These registers can be
accessed like any other register. For example, the instruction
MOV TL1, #4H moves the value into the low-byte of Timer 1.
Page 140
Timer Control Register (TCON): TCON is another register used to control operations of counter and timers
in microcontrollers. It is an 8-bit register wherein four upper bits are responsible for timers and counters and
lower bits are responsible for interrupts.
TR1: The TR1 stands for timer1 start or stop bit. This timer starting can be through software instruction or
through hardware method.
EX: gate=0 (start timer 1 through software instruction)
TR1=1; (Start timer)
TF0: The TF0 stands for ‘timer0’ flag-bit. Whenever calculating the time delay in timer1, the TH0 and TL0
reaches to a maximum value that is ‘FFFF’, automatically.
EX: while (TF0==1):- Whenever the TF0=1, then clear the flag bit and stop the timer.
TR0: The TR0 stands for ‘timer0’ start or stop bit; this timer starting can be through software instruction or
through hardware method.
EX: gate=0 (start timer 1 through software instruction)
TR0=1; (Start timer)
Both Timer 0 and Timer 1 use the same register to set the various timer operation modes. It is an 8-bit
register in which the lower 4 bits are set aside for Timer 0 and the upper four bits for Timers. In each case,
the lower 2 bits are used to set the timer mode in advance and the upper 2 bits are used to specify the
location.
Gate − When set, the timer only runs while INT(0,1) is high.
C/T − Counter/Timer select bit.
Page 141
M1 − Mode bit 1.
M0 − Mode bit 0.
GATE
Every timer has a means of starting and stopping. Some timers do this by software, some by hardware, and
some have both software and hardware controls. 8051 timers have both software and hardware controls.
The start and stop of a timer is controlled by software using the instruction SETB TR1 and CLR TR1 for
timer 1, and SETB TR0 and CLR TR0 for timer 0.
The SETB instruction is used to start it and it is stopped by the CLR instruction. These instructions start
and stop the timers as long as GATE = 0 in the TMOD register. Timers can be started and stopped by an
external source by making GATE = 1 in the TMOD register.
This bit in the TMOD register is used to decide whether a timer is used as a delay generator or an event
manager. If C/T = 0, it is used as a timer for timer delay generation. The clock source to create the time
delay is the crystal frequency of the 8051. If C/T = 0, the crystal frequency attached to the 8051 also
decides the speed at which the 8051 timer ticks at a regular interval.
Timer frequency is always 1/12th of the frequency of the crystal attached to the 8051. Although various
8051 based systems have an XTAL frequency of 10 MHz to 40 MHz, we normally work with the XTAL
frequency of 11.0592 MHz. It is because the baud rate for serial communication of the 8051.XTAL =
11.0592 allows the 8051 system to communicate with the PC with no errors.
M1 / M2
M1 M2 Mode
0 0 13-bit timer mode.
0 1 16-bit timer mode.
1 0 8-bit auto reload mode.
1 1 Spilt mode.
Page 142
Different Modes of Timers
Both Timer 1 and Timer 0 in Mode 0 operate as 8-bit counters (with a divide-by-32 prescaler).
Timer register is configured as a 13-bit register consisting of all the 8 bits of TH1 and the lower 5 bits of
TL1. The upper 3 bits of TL1 are indeterminate and should be ignored. Setting the run flag (TR1) does not
clear the register. The timer interrupt flag TF1 is set when the count rolls over from all 1s to all 0s. Mode 0
operation is the same for Timer 0 as it is for Timer 1.
Timer mode "1" is a 16-bit timer and is a commonly used mode. It functions in the same way as 13-
bit mode except that all 16 bits are used. TLx is incremented starting from 0 to a maximum 255. Once the
value 255 is reached, TLx resets to 0 and then THx is incremented by 1. As being a full 16-bit timer, the
timer may contain up to 65536 distinct values and it will overflow back to 0 after 65,536 machine cycles.
Page 143
Mode 2 (8 Bit Auto Reload)
Both the timer registers are configured as 8-bit counters (TL1 and TL0) with automatic reload.
Overflow from TL1 (TL0) sets TF1 (TF0) and also reloads TL1 (TL0) with the contents of Th1 (TH0),
which is preset by software. The reload leaves TH1 (TH0) unchanged.
The benefit of auto-reload mode is that you can have the timer to always contain a value from 200 to
255. If you use mode 0 or 1, you would have to check in the code to see the overflow and, in that case, reset
the timer to 200. In this case, precious instructions check the value and/or get reloaded. In mode 2, the
microcontroller takes care of this. Once you have configured a timer in mode 2, you don't have to worry
about checking to see if the timer has overflowed, nor do you have to worry about resetting the value
because the microcontroller hardware will do it all for you. The auto-reload mode is used for establishing a
common baud rate.
Timer mode "3" is known as split-timer mode. When Timer 0 is placed in mode 3, it becomes two
separate 8-bit timers. Timer 0 is TL0 and Timer 1 is TH0. Both the timers count from 0 to 255 and in case
of overflow, reset back to 0. All the bits that are of Timer 1 will now be tied to TH0.
When Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be set in modes 0, 1 or 2,
but it cannot be started/ stopped as the bits that do that are now linked to TH0. The real timer 1 will be
incremented with every machine cycle.
Counters in 8051
The timer registers in 8051 are upward counters, increasing the value stored in them on each input
clock signal. In the case of timers, this clock frequency is given by the pre-scaler (making it count upwards
every 1.08 millisecond). Where as in the case of a counter, this signal is given by any input value. Now that
the clock signal to the register is given by an external stimulus, it counts upwards for each clock pulse given
by the external peripheral. Making it act as a counter. All of the things mentioned above about timers are
applicable for counters; the only difference being in the value of C/T bit in TMOD register.
Page 144
Note: due to the 16-bit size of timer registers the maximum value you can count up to is 65536 after which
the timer is reset. Input signals are taken from port 3.4 for timer 0 and port 3.5 for timer 1.
SBUF
• A byte of data to be transferred via the TxD line must be placed in the SBUF register
• SBUF holds the byte of data when it is received by the RxD line
• SBUF can be accessed like any other register
MOV SBUF, #'D' ;load SBUF=44H, ASCII for 'D‘
MOV SBUF, A ;copy accumulator into SBUF
MOV A, SBUF ;copy SBUF into accumulator
• When a byte is written in SBUF, it is framed by 8051 with the start and stop bits and transferred serially
via the TxD pin
• When the bits are received serially via RxD, it is deframed by 8051 by eliminating the stop and start bits,
making a byte out of the data received, and then placing it in the SBUF.
• Framing need not be done by programmer explicitly
• The special function register SBUF is physically two registers.
One is, write-only and is used to hold data to be transmitted out of the 8051 via TXD.
The other is, read-only and holds the received data from external sources via RXD.
• Both mutually exclusive registers have the same address 099H.
• SBUF is not bit addressable
SCON:-
Serial port control and status register is the special function register SCON.
This register contain not only the mode selection bits but also the 9th data bit for transmit and receive
(TB8 and RB8) and the serial part interrupt bits (TI and RI)
Page 145
SM SM1 Mode Description Baud Rate
O
Mode 1: Serial port operates as an 8-bit UART with a variable baud rate.10-bits are transmitted on TXD or
received on RXD. Start bit (always 0), 8 data bits (LSB first), and a stop bit (always 1). For a receive
operation, the stop bit goes into RB8 in SCON. Baud Rate Clock is variable using Timer 1 overflow or
external count input.
• Transmission is initiated by writing data to SBUF. Shifted data are outputted on the TXD line beginning
with the start bit. The transmit interrupt flag (TI) is set as soon as the stop bit appears on TXD.
• Reception is initiated by a 1-to-0 transition on RXD.
Page 146
Mode 2: Serial port operates as a 9-bit UART with a fixed baud rate. 11-bits are transmitted or received.
Start bit (always 0), 8 data bits (LSB first), a programmable 9th bit, and a stop bit (always 1).
• On transmission, the 9th bit whatever has been put in TB8 in SCON (may be a parity bit).
• On reception, the 9th bit is placed in RB8 in SCON.
• Baud Rate is programmable to either 1/32 or 1/64 of the on-chip oscillator frequency.
Mode 3: Serial port operates as a 9-bit UART with a variable baud rate. 11-bits are transmitted or received.
Baud Rate is programmable and provided by the Timer 1 overflow or external input.
PCON:-
The PCON or Power Control register, as the name suggests is used to control the 8051 Microcontroller’s
Power Modes and is located at 87H of the SFR Memory Space. Using two bits in the PCON Register, the
microcontroller can be set to Idle Mode and Power Down Mode.
During Idle Mode, the Microcontroller will stop the Clock Signal to the ALU (CPU) but it is given to other
peripherals like Timer, Serial, Interrupts, etc. In order to terminate the Idle Mode, you have to use an
Interrupt or Hardware Reset.
In the Power Down Mode, the oscillator will be stopped and the power will be reduced to 2V. To terminate
the Power Down Mode, you have to use the Hardware Reset.
Apart from these two, the PCON Register can also be used for few additional purposes. The SMOD Bit in
the PCON Register is used to control the Baud Rate of the Serial Port.
There are two general purpose Flag Bits in the PCON Register, which can be used by the programmer
during execution.
Bit 7 – SMOD
1 = Baud rate is doubled in UART mode 1, 2 and 3.
0 = No effect on Baud rate.
Bit 3:2 – GF1 & GF0:
These are general purpose bit for user.
Bit 1 – PD: Power Down
1 = Enable Power Down mode. In this mode, Oscillator clock turned OFF and both CPU and
peripherals clock stopped. Hardware reset can cancel this mode.
0 = Disable Power down mode.
Bit 0 – IDL: Idle
1 = Enable Idle mode. CPU clock turned off whereas internal peripheral module such as timer, serial
port, interrupts works normally. Interrupt and H/W reset can cancel this mode.
0 = Disable Idle mode.
Page 147
BASIS FOR COMPARISON SERIAL TRANSMISSION PARALLEL TRANSMISSION
Concept-VII: Interrupts
Interrupts are the events that temporarily suspend the main program, pass the control to the external
sources and execute their task. It then passes the control to the main program where it had left off.
8051 has 5 interrupt signals, i.e. INT0, TF0, INT1, TF1, RI/TI. Each interrupt can be enabled or
disabled by setting bits of the IE register and the whole interrupt system can be disabled by clearing the EA
bit of the same register.
IE (Interrupt Enable) Register
This register is responsible for enabling and disabling the interrupt. EA register is set to one for
enabling interrupts and set to 0 for disabling the interrupts.
Page 148
IP (Interrupt Priority) Register
We can change the priority levels of the interrupts by changing the corresponding bit in the Interrupt
Priority (IP) register.
A low priority interrupt can only be interrupted by the high priority interrupt, but not interrupted by
another low priority interrupt.
If two interrupts of different priority levels are received simultaneously, the request of higher
priority level is served.
If the requests of the same priority levels are received simultaneously, then the internal polling
sequence determines which request is to be serviced.
External Interrupt
The external interrupts of 8051 are INT0and. INT1 These interrupts can be programmed to either edge-
triggered or level triggered. The TCON register can be used top rogram external interrupts to edge or level
triggered. The TCON isTimer Control. TCON is another bit addressable SFR. Here the address is 88H.
BitAddress 8F 8E 8D 8C 8B 8A 89 88
Bit Details TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
Now, let us see the bit details and different operations when the value is low (0) and high(1).
Bit Details High Value(1) Low Value(0)
IT0 Set ( INT0) as negative edge Set ( INT0) as active low level triggered input.
triggeredinput.
IT1 Set ( INT1) as negative edge Set ( INT1) as active low level triggered input.
triggeredinput.
IE0 This will be 1, when INT0is activated as This will be 0, when INT0is activated as edge
level triggered. triggered.
IE1 This will be 1, when INT1 is activated as This will be 0, when INT1 is activated as edge
level triggered. triggered.
Page 149
Bit Details High Value(1) Low Value(0)
TF0 High when Timer T0 overflow occurs. After resetting the timer T0 thiswill also be
changed to 0 state
TF1 High when Timer T1 overflow occurs. After resetting the timer T1 this will also be
changed to 0 state.
The IT0 and IT1 are stands for Interrupt Type. These bits are used to decide whether
the INT0 and INT1 will be level trigged or edge triggered.
IE0 and IE1 bits are used to indicate the status of external interrupts. These bit can be set or reset by the
microcontroller itself.
The first four bits are the status information about timers. When TR0 and TR1 are 1, it indicates the running
mode of the timers. These bits provide software control over the running of timers. Timers can also be
controlled by the hardware. The priority of hardware mode is higher than the software mode.
The TF0 and TF1 are used to indicate the overflow of timer T0 and T1 respectively. When over flow occurs
these flags are set to 1. When the interrupt is handled by some interrupt service subroutine (ISS), these will
be 0.
The interrupt control system of 8051 is like below:
Page 150
All comments are typed in lower case
The last line of the program must be the END directive
The assembly language mnemonics are in the form of op-code, such as MOV, ADD, JMP, and so on, which
are used to perform the operations.
Op-code: The op-code is a single instruction that can be executed by the CPU. Here the op-code is a MOV
instruction.
Operands: The operands are a single piece of data that can be operated by the op-code. Example,
multiplication operation is performed by the operands that are multiplied by the operand.
The Elements of an Assembly Language Programming:
Assembler Directives
Instruction Set
Addressing Modes
Assembler Directives:
The assembling directives give the directions to the CPU. The 8051 microcontroller consists of various
kinds of assembly directives to give the direction to the control unit. The most useful directives are 8051
programming, such as:
ORG
DB
EQU
END
ORG(origin): This directive indicates the start of the program. This is used to set the register address during
assembly. For example; ORG 0000h tells the compiler all subsequent code starting at address 0000h.
Syntax: ORG 0000h
DB(define byte): The define byte is used to allow a string of bytes. For example, print the “EDGEFX”
where in each character is taken by the address and finally prints the “string” by the DB directly with double
quotes.
EQU (equivalent): The equivalent directive is used to equate address of the variable.
END:The END directive is used to indicate the end of the program.
Here we will discuss about the basic form of an assembly language. The steps to create, assemble, and run
an assembly language program are as follows −
Page 151
First, we use an editor to type in a program similar to the above program. Editors like MS-DOS
EDIT program that comes with all Microsoft operating systems can be used to create or edit a
program. The Editor must be able to produce an ASCII file. The "asm" extension for the source file
is used by an assembler in the next step.
The "asm" source file contains the program code created in Step 1. It is fed to an 8051 assembler.
The assembler then converts the assembly language instructions into machine code instructions and
produces an .obj file (object file) and a .lst file (list file). It is also called as a source file, that's why
some assemblers require that this file have the "src" extensions. The "lst" file is optional. It is very
useful to the program because it lists all the opcodes and addresses as well as errors that the
assemblers detected.
Assemblers require a third step called linking. The link program takes one or more object files and
produces an absolute object file with the extension "abs".
Next, the "abs" file is fed to a program called "OH" (object to hex converter), which creates a file
with the extension "hex" that is ready to burn in to the ROM.
Syntax:
MOV A, #20h //A is an accumulator register, 20 is stored in the A//
MOV R0,#15 // R0 is a general purpose register; 15 is stored in the R0 register//
MOV P0, #07h //P0 is a SFR register;07 is stored in the P0//
MOV 20h,#05h //20h is the address of the register; 05 stored in the 20h//
Ex:
MOV R0, #1
MOV R0, #20 //R0 <—R0[15]+20, the final value is stored in R0//
Syntax:
MOV A, B; // A is a SFR register, B is a general purpose register//
MOV R0, R1 //Invalid instruction, GPR to GPR not possible//
EX:
MOV R0, #02h
MOV A, #30h
ADD R0, A //R0<—R0+A, the final value is stored in the R0 register//
Syntax:
MOV A,20h // 20h is an address; A is a register//
MOV 00h, 07h // both are addressed of the GPS registers//
Ex:
MOV 07h,#01h
MOV A, #08h
ADD A,07h //A<—A+07h the final value is stored in A//
Syntax:
MOVR0, #01h //01 value is stored in the R0 register, R0 address is 08h//
MOV R1, #08h//R1 is the pointer variable that stores address (08h) of R0 //
MOV 20h,@R1 //01 value is stored in the 20h address of the GP register//
Page 154
MOVC A, @A+DPTR //C indicates code memory//
MOCX A, @A+DPTR // X indicate external memory//
EX: MOV A, #00H //00H is stored in the A register//
MOV DPTR, #0500H //DPTR points 0500h address in the memory//
MOVC A, @A+DPTR //send the value to the A register//
MOV P0, A //date of A send to the PO registrar//
Concept-X: Instructions
The instruction set is the structure of the controller or processor that provides commands to the controller to
guide the controller for processing data. The instruction set consists of instructions, native data types,
addressing modes, interrupt registers, exceptional handling and memory architecture.
The 8051 microcontroller can follow CISC instructions with Harvard architecture. In case of the 8051
programming different types of CISC instructions include:
Data Transfer Instruction set
Arithmetic Instruction set
Branching Instruction set
Conditional
Unconditional
Loop Instrcution Set
Logical Instruction set
Boolean or Bit Manipulation Instructions
MOV
MOVC
MOVX
PUSH
POP
XCH
XCHD
Mnemonic Description
MOV Move Data
MOVC Move Code
MOCX Move External Data
PUSH Move Data to Stack
POP Copy Data from Stack
XCH Exchange Data between two Registers
XCHD Exchange Lower Order Data between two Registers
Addition
Multiplication
Subtraction
Page 155
Division
Addition:
ORG 0000h
MOV R0, #03H // move the value 3 to the register R0//
MOV A, #05H // move the value 5 to accumulator A//
Add A, 00H // addA value with R0 value and stores the result inA//
END
Multiplication:
ORG 0000h
MOV R0, #03H // move the value 3 to the register R0//
MOV A, #05H // move the value 5 to accumulator A//
MUL A, 03H // Multiplied result is stored in the Accumulator A //
END
Subtraction:
ORG 0000h
MOV R0, #03H // move the value 3 to register R0//
MOV A, #05H // move the value 5 to accumulator A//
SUBB A, 03H // Result value is stored in the Accumulator A //
END
Division:
ORG 0000h
MOV R0, #03H // move the value 3 to register R0//
MOV A, #15H // move the value 5 to accumulator A//
DIV A, 03H // final value is stored in the Accumulator A //
END
Page 156
1. Syntax:
JB P1.0, label
––––––––
––––––––
Label: – – – – – – – –
––––––––
END
2. Syntax:
JNB P1.0, label
––––––––
––––––––
Label: – – – – – – – –
––––––––
END
3. Syntax:
JC, label
––––––––
––––––––
Label: – – – – – – – –
––––––––
END
4. Syntax:
JNC, label
––––––––
––––––––
Label: – – – – – – – –
––––––––
END
5. Syntax:
JZ, label
––––––––
––––––––
Label: – – – – – – – –
––––––––
END
6. Syntax:
JNZ, label
––––––––
––––––––
Label: – – – – – – – –
Page 157
––––––––
END
Page 158
Loop Instructions:
The loop instructions are used to repeat the block each time while performing the increment and
decrement operations. The 8051 microcontroller consist two types of loop instructions:
CJNE —> compare and jump if not equal
DJNZ —> decrement and jump if not zero
1. Syntax:
of CJNE
MOV A, #00H
MOV B, #10H
Label:INC A
––––––
––––––
CJNE A, label
2. Syntax:
of DJNE
MOV R0, #10H
Label:– – – – – –
––––––
DJNE R0, label
––––––
––––––
END
Logical Instruction Set:
The 8051 microcontroller instruction set provides the AND, OR, XOR, TEST, NOT and Boolean logic
instructions for set and clears the bits based on the need in the program.
1. Syntax:
MOV A, #20H /00100000/
MOV R0, #03H /00000101/
ORL A, R0 //00100000/00000101=00000000//
2. Syntax:
MOV A, #20H /00100000/
MOV R0, #03H /00000101/
ANL A, R0
3. Syntax:
Page 159
MOV A, #20H /00100000/
MOV R0, #03H /00000101/
XRL A, R0
Shifting Operators
The shift operators are used for sending and receiving the data efficiently. The
8051 microcontroller consist four shift operators:
RR —> Rotate Right
RRC —>Rotate Right through carry
RL —> Rotate Left
RLC —>Rotate Left through carry
Rotate Right (RR):
In this shifting operation, the MSB becomes LSB and all bits shift towards right side bit-by-bit,
serially.
Syntax:
MOV A, #25h
RR A
Syntax:
MOV A, #25h
RL A
Syntax:
MOV A, #27h
RRC A
Page 160
Syntax:
MOV A, #27h
RLC A
CLR
SETB
MOV
JC
JNC
JB
JNB
JBC
ANL
ORL
CPL
Mnemonic Description
CLR Clear a Bit (Reset to 0)
SETB Set a Bit (Set to 1)
MOV Move a Bit
JC Jump if Carry Flag is Set
JNC Jump if Carry Flag is Not Set
JB Jump if specified Bit is Set
JNB Jump if specified Bit is Not Set
JBC Jump if specified Bit is Set and also clear the Bit
ANL Bitwise AND
ORL Bitwise OR
CPL Complement the Bit
Page 161
MOV A,@R0 ;take the value from source to register A
MOV R5,A ; Move the value from A to R5
MOV R4,#00H ; Clear register R4 to store borrow
INC R0 ; Point to the next location
MOV A,@R0 ; take the value from source to register A
MOV R3,A ; store second byte
MOV A,R5 ;get back the first operand
SUBB A,R3 ; Subtract R3 from A
JNC SAVE
INC R4 ; Increment R4 to get borrow
MOV B,R4 ;Get borrow to register B
MOV @R1,B ; Store the borrow first
INC R1 ; Increase R1 to point to the next address
SAVE: MOV @R1,A ; Store the result
HALT: SJMP HALT ;Stop the program
2.
Page 162
Hex keypad
The hex keypad has 8 communication lines namely R1, R2, R3, R4, C1, C2, C3 and C4. R1 to R4
represents the four rows and C1 to C4 represents the four columns. When a particular key is pressed the
corresponding row and column to which the terminals of the key are connected gets shorted. For example if
key 1 is pressed row R1 and column C1 gets shorted and so on. The program identifies which key is pressed
by a method known as column scanning. In this method a particular row is kept low (other rows are kept
high) and the columns are checked for low. If a particular column is found low then that means that the key
connected between that column and the corresponding row (the row that is kept low) is been pressed. For
example if row R1 is initially kept low and column C1 is found low during scanning, that means key 1 is
pressed.
Interfacing hex keypad to 8051.
The circuit diagram for demonstrating interfacing hex keypad to 8051 is shown below.Like previous 8051
projects, AT89S51 is the microcontroller used here. The circuit will display the character/numeric pressed
on a seven segment LED display. The circuit is very simple and it uses only two ports of the
microcontroller, one for the hex keypad and the other for the seven segment LED display.
Page 164
MOV A,#12D
ACALL DISPLAY
NEXT13:JB P1.5,NEXT14
MOV A,#13D
ACALL DISPLAY
NEXT14:JB P1.6,NEXT15
MOV A,#14D
ACALL DISPLAY
NEXT15:JB P1.7,BACK
MOV A,#15D
ACALL DISPLAY
LJMP BACK
DISPLAY:MOVC A,@A+DPTR // gets digit drive pattern for the current key from LUT
MOV P0,A // puts corresponding digit drive pattern into P0
RET
Page 165
Digit drive pattern.
Digit drive pattern of a seven segment LED display is simply the different logic combinations of its
terminals ‘a’ to ‘h‘ in order to display different digits and characters. The common digit drive patterns (0 to
9) of a seven segment display are shown in the table below.
Digit a b c d e f g
0 1 1 1 1 1 1 0
1 0 1 1 0 0 0 0
2 1 1 0 1 1 0 1
3 1 1 1 1 0 0 1
4 0 1 1 0 0 1 1
5 1 0 1 1 0 1 1
6 1 0 1 1 1 1 1
7 1 1 1 0 0 0 0
8 1 1 1 1 1 1 1
9 1 1 1 1 0 1 1
Page 166
Interfacing 7 segment display to 8051
The circuit diagram shown above is of an AT89S51 microcontroller based 0 to 9 counter which has a 7
segment LED display interfaced to it in order to display the count. This simple circuit illustrates two things.
How to setup simple 0 to 9 up counter using 8051 and more importantly how to interface a seven segment
LED display to 8051 in order to display a particular result. The common cathode seven segment display D1
is connected to the Port 1 of the microcontroller (AT89S51) as shown in the circuit diagram. R3 to R10 are
current limiting resistors. S3 is the reset switch and R2,C3 forms a debouncing circuitry. C1, C2 and X1 are
related to the clock circuit. The software part of the project has to do the following tasks.
Form a 0 to 9 counter with a predetermined delay (around 1/2 second here).
Convert the current count into digit drive pattern.
Put the current digit drive pattern into a port for displaying.
Program.
Page 167
JZ START //Checks accumulator for zero and jumps to START. Done to check if counting has been finished.
SJMP LABEL
DB 3FH // digit drive pattern for 0
DB 06H // digit drive pattern for 1
DB 5BH // digit drive pattern for 2
DB 4FH // digit drive pattern for 3
DB 66H // digit drive pattern for 4
DB 6DH // digit drive pattern for 5
DB 7DH // digit drive pattern for 6
DB 07H // digit drive pattern for 7
DB 7FH // digit drive pattern for 8
DB 6FH // digit drive pattern for 9
DELAY: MOV R4,#05H // subroutine for delay
WAIT1: MOV R3,#00H
WAIT2: MOV R2,#00H
WAIT3: DJNZ R2,WAIT3
DJNZ R3,WAIT2
DJNZ R4,WAIT1
RET
END
Page 168
ADC0804 pinout
The voltage at Vref/2 (pin9) of ADC0804 can be externally adjusted to convert smaller input voltage spans
to full 8 bit resolution. Vref/2 (pin9) left open means input voltage span is 0-5V and step size is
5/255=19.6V. Have a look at the table below for different Vref/2 voltages and corresponding analogue input
voltage spans.
Vref/2 (pin9) (volts) Input voltage span (volts) Step size (mV)
Page 169
Interfacing ADC to 8051
The figure above shows the schematic for interfacing ADC0804 to 8051. The circuit initiates the ADC to
convert a given analogue input , then accepts the corresponding digital data and displays it on the LED array
connected at P0. For example, if the analogue input voltage Vin is 5V then all LEDs will glow indicating
11111111 in binary which is the equivalent of 255 in decimal. AT89s51 is the microcontroller used here.
Data out pins (D0 to D7) of the ADC0804 are connected to the port pins P1.0 to P1.7 respectively. LEDs D1
to D8 are connected to the port pins P0.0 to P0.7 respectively. Resistors R1 to R8 are current limiting
resistors. In simple words P1 of the microcontroller is the input port and P0 is the output port. Control
signals for the ADC (INTR, WR, RD and CS) are available at port pins P3.4 to P3.7 respectively. Resistor
R9 and capacitor C1 are associated with the internal clock circuitry of the ADC. Preset resistor R10 forms a
voltage divider which can be used to apply a particular input analogue voltage to the ADC. Push button S1,
resistor R11 and capacitor C4 forms a debouncing reset mechanism. Crystal X1 and capacitors C2,C3 are
associated with the clock circuitry of the microcontroller.
Program.
ORG 00H
MOV P1,#11111111B // initiates P1 as the input port
MAIN: CLR P3.7 // makes CS=0
SETB P3.6 // makes RD high
CLR P3.5 // makes WR low
SETB P3.5 // low to high pulse to WR for starting conversion
WAIT: JB P3.4,WAIT // polls until INTR=0
CLR P3.7 // ensures CS=0
CLR P3.6 // high to low pulse to RD for reading the data from ADC
MOV A,P1 // moves the digital data to accumulator
CPL A // complements the digital data (*see the notes)
MOV P0,A // outputs the data to P0 for the LEDs
SJMP MAIN // jumps back to the MAIN program
Page 170
END
Notes.
The entire circuit can be powered from 5V DC.
ADC 0804 has active low outputs and the instruction CPL A complements it t0 have a straight forward
display. For example, if input is 5V then the output will be 11111111 and if CPL A was not used it
would have been 00000000 which is rather awkward to see.
DAC
Microcontroller are used in wide variety of applications like for measuring and control of physical
quantity like temperature, pressure, speed, distance, etc.
In these systems microcontroller generates output which is in digital form but the controlling system
requires analog signal as they don't accept digital data thus making it necessary to use DAC which
converts digital data into equivalent analog voltage.
In the figure shown, we use 8-bit DAC 0808. This IC converts digital data into equivalent analog
Current. Hence we require an I to V converter to convert this current into equivalent voltage.
According to theory of DAC Equivalent analog output is given as:
Ex:
1. IF data =00H [00000000], Vref= 10V
Page 171
ORG 0000h
mov P1,#00H
repeat: call squarwave ; generate square wave
call triwave ; generate triangular wave
call stairwave ; generate staircase wave
jmp repeat
Page 172
squarwave: mov P1,#FFH
call delay2sec
mov P1,#00H
call delay2sec
ret
triwave: mov R7,#00H
triwave1: mov P1,R7
inc R7
cjne R7,#FFH,triwave1
mov R7,#FFH
triwave2: mov P1,R7
djnz R7,triwave2
ret
Additional Concepts:
8051 Pin configuration
Page 173
Port1 (Pin1 to Pin8): Port1 includes pin1.0 to pin1.7 and these pins can be configured as input or
output pins.
Pin 9 (RST): Reset pin is used to Reset 8051 Microcontroller by giving a positive pulse to this Pin.
Port3 (Pin 10 to 17): The Port3 Pins are similar to port1 pins and can be used as universal Input or
output pins. These pins dual-function Pins and the function of each Pin is given as:
Pin 10 (RXD): RXD pin is a Serial Asynchronous Communication Input or Serial synchronous
Communication Output.
Pin 11 (TXD): Serial Asynchronous Communication Output or Serial Synchronous Communication
clock Output.
Pin 12 (INT0): Input of Interrupt 0
Pin 13 (INT1): Input of Interrupt 1
Pin 14 (T0): Input of Counter 0 clock
Pin 15 (T1): Input of Counter 1 clock
Pin 16 (WR): Writing Signal to write content on external RAM.
Pin 17 (RD): Reading Signal to read contents of external RAM.
Pin 18 and 19 (XTAL2, XTAL1): X2 and X1 pins are input output pins for the oscillator. These
pins are used to connect an internal oscillator to the microcontroller.
Pin 20 (GND): Pin 20 is a ground pin.
Port2 (Pin 21 to Pin28): Port2 includes pin21 to pin28 which can be configured as Input Output
Pins. But, this is only possible when we don’t use any external memory. If we use external memory,
then these pins will work as high order address bus (A8 to A15).
Pin 29 (PSEN): This pin is used to enable external program memory. If we use an external ROM for
storing the program, then logic 0 appears on it, which indicates Micro controller to read data from
the memory.
Pin 30 (ALE): Address Latch Enable pin is an active high-output signal. If we use multiple memory
chips, then this pin is used to distinguish between them. This Pin also gives program pulse input
during programming of EPROM.
Pin 31 (EA): If we have to use multiple memories then the application of logic 1 to this pin instructs
the Microcontroller to read data from both memories: first internal and then external.
Port 0 (Pin 32 to 39): Similar to the port 2 and 3 pins, these pins can be used as input output pins
when we don’t use any external memory. When ALE or Pin 30 is at 1, then this port is used as data
bus: when the ALE pin is at 0, then this port is used as a lower order address bus (A0 to A7)
Pin40 (VCC): This VCC pin is used for power supply.
Page 174
Differentiate between microprocessors and microcontrollers
Some of the applications of 8051 is mainly used in daily life & industrial applications also
some of that applications are shown below
Light sensing and controlling devices
Temperature sensing and controlling devices
Fire detections and safety devices
Automobile applications
Defence applications
Some industrial applications of micro controller and its applications
Industrial instrumentation devices
Process control devices
Some of 8051 microcontroller devices are used in measurement applications
Voltmeter applications
Measuring and revolving objects
Current meter objects
Hand held metering system
Page 175
8051 Microcontroller Applications in Embedded Systems
The applications of 8051 microcontroller involves in 8051 based projects. The list of 8051 projects is listed
below.
Arduino Managed High Sensitive LDR based Power Saver for Street Light Control System
The Temperature Humidity Monitoring System of Soil Based on Wireless Sensor Networks using
Arduino
RFID based Electronic Passport System for Easy Governance using Arduino
Arduino based RFID Sensed Device Access
Arduino based DC Motor Speed Control
Arduino Based Line Following Robot
Zigbee based Automatic Meter Reading System
GSM based Electricity Energy Meter Billing with Onsite Display
Android Phone Speech Recognition Sensed Voice Command based Notice Board Display
Parking Availability Indication System
Voice Controlled Home Appliances
Remote Control Home Appliances
PC Mouse operated Electrical Load Control Using VB Application
Solar Highway Lighting System with Auto Turn Off in Daytime
8051 Microcontroller based Wireless Energy Meter
Farmer Friendly Solar Based Electric Fence for Deterring Cattles
Vehicle Movement Sensed Streetlight with Daytime auto off Features
Page 176
Important Questions from Additional concepts:
1. What is the significance of EA pin?
2. Draw the pin diagram of 8051 microcontroller and explain the function of each pin in detail.
3. List and discuss the applications of 8051 microcontrollers
4. Differentiate between microprocessors and microcontrollers
5. What are the additional features of microcontrollers over microprocessors?
6. Write short notes on (i) PSW (ii) SCON (iii) PCON (iv) TMOD (v) TCON.
7. Register organization of 8051 Microcontrollers
8. Explain the following registers (i) IP (ii)IE ( (iii) PSEN.
Unit VI
Page 177
Introduction:
The term PIC stands for Peripheral Interface Controller .It is the brain child of Microchip
Technology, USA . Originally this was developed as a supporting device for PDP computers to
control its peripheral devices, and therefore named as PIC, Peripheral Interface Controller. They
have coined this name to identify their single chip micro controllers. These 8-bit micro controllers
have become very important now -a -days in industrial automation and embedded applications etc.
One of the earlier versions of PIC Microcontrollers is PIC16C6x/7x. The 7x family has an
enhancement of Analog to Digital converter capability. These cs are available with a range of
capabilities packaged in both dual in-line (DIP) packages and surface-mount packages. These are
available in 28 pin DIP, 40 pin DIP ,44 pin surface mount package…etc.. some of PIC controllers
contain the letter A in their number. The presence of A indicates the brown-out reset feature, which
causes a reset of the PIC when the Power Supply voltage drops below 4.0v.
Characteristics of PIC microcontroller & PIC microcontroller families
The PIC 16F8XX Microcontrollers are basically RISC microcontrollers with very small
instruction set of only 35 instructions and a two-stage pipeline concept fetch and execution of
instructions. As a result, all instructions execute in a single cycle except for program
branches. .There are four devices in 16F8xx family, PIC16F873, PIC16F874, PIC16F876 and
PIC16F877.The PIC16F876/873 devices come in 28-pin packages and the PIC16F877/874 devices
come in 40-pin packages. The Parallel Slave Port is not implemented on the 28-pin devices.
PIC 16F877 is a 40-pin 8-Bit CMOS FLASH Microcontroller . The core architecture is high-
performance RISC CPU . Since it follows the RISC architecture, all single cycle instructions take
only one instruction cycle except for program branches which take two cycles. 16F877 comes with
3 operating speeds with 4, 8, or 20 MHz clock input. Since each instruction cycle takes four
operating clock cycles, each instruction takes 0.2 μs when 20MHz oscillator is used. It has two
types of internal memories .One is program memory and the other is data memory. Program
memory is provided by 8K words (or 8K*14 bits) of FLASH Memory, and data memory has two
sources. One type of data memory is a 368-byte RAM (random access memory) and the other is256-
byte EEPROM (Electrically erasable programmable ROM).The core features include interrupt up
to 14 sources, power saving SLEEP mode, a single 5V supply and In-Circuit Serial Programming
Page 178
(ICSP) capability. The sink/source current, which indicates a driving power from I/O port, is high
with 25mA. Power consumption is less than 2 mA in 5V operating condition.
Salient Features :
Speed :
When operated at its maximum clock rate a PIC executes most of its instructions in 0.2 s or
five instructions per microsecond.
Instruction set Simplicity :
The instruction set is so simple that it consists of only just 35 instructions
Integration of operational features:
Power-on-reset (POR) and brown-out protection ensure that the chip operates only when the
supply voltage is within specifications. A watch dog timer resets the PIC if the chip malfunctions or
deviates from its normal operation at any time.
Programmable timer options:
Three timers can characterize inputs, control outputs and provide internal timing for the
program execution.
Interrupt control:
Up to 12 independent interrupt sources can control when the CPU deal with each sources.
Powerful output pin control:
A single instruction can select and drive a single output pin high or low in its 0.2 s
instruction execution time. The PIC can drive a load of up to 25A.
I/O port expansion:
With the help of built in serial peripheral interface the number of I/O ports can be expanded.
EPROM/DIP/ROM options are provided.
High performance RISC CPU
Operating speed: DC – 20 MHz clock input DC – 200 ns instruction cycle
Eight level deep hardware stack
Direct, indirect and relative addressing modes
Power-up Timer (PWRT) and Oscillator Start-up Timer (OST)
Three Timers Timer0,Timer 1 and Timer 2.
Watchdog Timer (WDT) with its own on-chip RC oscillator for reliable operation
Programmable code-protection
Page 179
Power saving SLEEP mode
10-bit multi-channel Analog-to-Digital converter
Selectable oscillator options
One USART /SCI port with 9-bit address detection.
Low-power, high-speed CMOS EPROM/ROM technology
Fully static design
Wide operating voltage range: 2.5V to 6.0V
Commercial, Industrial and Extended temperature ranges
Low-power consumption: <2mA @5V, 4MHz, 15 A typical @ 3V, 32 kHz, <1 A typical
standby current
ARCHITECTURE
The PIC16FXX is a family of low-cost, high-performance, CMOS, fully-static, 8-bit
microcontrollers.
All PIC microcontrollers employ an advanced RISC architecture. The PIC16FXX microcontroller
family has enhanced core features, eight-level deep stack, and multiple internal and external interrupt
sources. The two-stage instruction pipeline allows all instructions to execute in a single cycle, except for
program branches (which require two cycles). A total of 35 instructions (reduced instruction set) are
available. Also, a large register set helps to achieve a very high performance.
. The PIC 16FXX uses Harvard architecture, in which, program and data are accessed from separate
memories using separate buses. This improves bandwidth over traditional Von Neumann architecture where
program and data may be fetched from the same memory using the same bus. Separating program and data
buses further allows instructions to be sized differently than 8-bit wide data words. Instruction opcodes are
14-bits wide making it possible to have all single word instructions. A 14-bit wide program memory access
bus fetches a 14-bit instruction in a single cycle. A two-stage pipeline overlaps fetch and execution of
instructions. Consequently, all instructions execute in a single cycle (200 ns@ 20MHz) except for program
branches.
Page 180
Block diagram of PIC 16F87X Microcontroller
The PIC 16F87X devices have a 13-bit program counter capable of addressing an 8KX14 program memory
space.The PIC 16FF876/877 devices have 8Kx 14 words of Flash program memory .The RESET vector is at
0000h and the Interrupt vector is at 0004h.
Memory organization :
The memory module of the PICcontroller has three memory blocks.
a) Program memory
b) Data memory and
c) Stack
a) Program Memory:
Page 181
The PIC 16F8XX has 4k x14 program memory space (0000H-0FFFH).It has a 13 bit Program
counter(PC) to access any address (2 13=4k). This PIC family uses 13-bit program counter allowing the
controllers to an 8k-program memory without changing the CPU structure.
Two addresses in the program memory address space are treated in a special way by the CPU. The
first address H’ 000’ being a go to mainline instruction the second special address, H’ 004’ being a ‘go to in
service’ instruction can be assigned to this address to make the CPU to jump to the beginning of the
Interrupt Service routine located elsewhere in the memory space.
Page 182
When we deal with tables, they are assigned to addresses in the range H’005 – H’0FF’ because for
most of the applications this space is sufficient. The main line program begins after the tables.
DATA MEMORY
The data memory of PIC 16F8XX is partitioned into multiple banks which contain the general purpose
registers and the Special function Registers.(SFRs).The bits RP1 and RP0 bits of the status register are used
to select these banks.Each bank extends upto 7FH(128 Bytes).The lower bytes of the each bank are reserved
for the Special Function Registers.Above the SFRs are general purpose registers implemented as static
RAM.
Page 183
CPU REGISTERS
The CPU registers are used in the execution of the instruction of the PIC microcontroller. The PIC
PIC16F877 Microcontroller has the following registers.
1. Working Register-W (Similar to Accumulator)
2. Status Register
3. FSR – File Select Register (Indirect Data memory address pointer)
4. INDF
5. Program Counter
1. Working Register:
Working Register is used by many instructions as the source of an operand. It also serves as the
destination for the result of instruction execution and it is similar to accumulator in other cs and ps.
2.Status Register:
This is an 8-bit register which denotes the status of ALU after any arithmetic operation and also
RESET status and the bank select bits for the data memory.
C: Carry/borrow bit
DC: Digit carry/borrow bit
Z: Zero bit
NOT_PD : Reset Status bit (Power-down mode bit)
NOT_TO : Reset Status bit (tme- out bit)
Page 184
RPO: Register bank Select
The bits 7 and 6 of Status Register are unused by 16c6x/7x. The ‘C’ bit is set when two 8-bit
operands are added together and a 9-bit result occurs. This 9-bit is placed in the carry bit.
The DC or Digit carry bit indicates that a carry from the lower 4 bits occurred during an 8-bit
addition.
Example: 0011 1000
0011 1000
0111 0000
Here DC=1 as a result of the carry from the bit 3 to the bit 4 position.
The Z or zero bits is affected by the execution of arithmetic or logic instructions.
The reset status bits NOT_TO and NOT_PD are used in conjunction with PIC’s sleep mode. The
micro controller can put itself to sleep mode to save power during intervals when it has nothing to do. It can
be reset by any of three kinds. Upon reset the CPU can check these two reset status bits to determine which
kind of event resettled it and then respond accordingly.
The Register bank select bit RPO is used to select either bank or bank.When RPO=0, select Bank 0,
RPO=1, select Bank 1.
Example: bcf STATUS, RPO ; Select bank 0
bsf STATUS, RPO ; Select bank 1.
3.FSR – (File Select Register):
It is the pointer used for indirect addressing. In the indirect addressing mode the 8-bit register file
address is first written into FSR. It is a special purpose register that serves as an address pointer to any
address through out the entire register file.
4.INDF – (Indirect File):
It is not a physical register addressing but this INDF will cause indirect addressing. Any instruction
using the INDF register actually access the register pointed to by the FSR.
5 .PROGRAM COUNTER
PIC PIC16F877A has a 13 bit program counter in which PCL is the lower 8-bits of the PC and
PCLATH is the write buffer for the upper 5 bits of the PC.
Page 185
PCLATH (program counter Latch can be read or from or written to without affecting the Program
Counter(PC).The upper 3 bits of PCLATH remain zero.It is only when PCL is written to that PCLATH is
automatically written into the PC at the same time.
PORT B:
Port B is an 8-bit wide, bi-directional port. Four of the PORT B pins RB 7 – RB4 have an interrupt-on-
change feature. Only the pins configured as inputs can cause this interrupt to occur.
PORT C:
Port C is an 8-bit wide, bidirectional port. Bits of the TRISC Register determine the function of its
pins. Similar to other ports, a logic one 1 in the TRISC Register configures the appropriate port pin as an
input.
PORT D:
Port D is an 8-bit wide bi-directional port. In addition to I/O port, Port D also works as 8-bit parallel
slave port or microprocessor port. When control bit PSPMODE (TRISE:4) is set.
PORT E:
It is a 3-bit bi-directional port. Port E bits are multiplexed with analog inputs of ADC and they serve
as control signals (RD , WR, CS) for parallel slave port mode of operation.
TIMER MODULES:
There are three completely independent Timers available in PIC 16F8XX Microcontrollers. They are
Timer 0
Timer1 and
Timer2
Timer 0:
The Timer 0 module is a simple 8-bit overflow counter. The clock source can be either the internal
system clock (Fosc/4) or an external clock. When the clock source is an external clock, the Timer0 module
can be selected to increment on either the rising or falling edge.
Page 186
The Timer 0 module also has a programmable prescaler option. This prescaler can be assigned to
either the Timer0 module or the Watchdog Timer. Bit PSA assigns the prescaler and bits PS2:PSO
determine the prescaler value. TMR0 can increment at the following rates: 1:1 when the prescaler is
assigned to Watchdog Timer, 1:2, 1:4, 1:8, 1:16, 1:32, 1:64, 1:128 and 1:256.
Synchronization of the external clock occurs after the prescaler. When the prescaler is used, the
external clock frequency may be higher then the device’s frequency. The maximum frequency is 50 MHz,
given the high and low time requirements of the clock.
OPTION_REG (TIMER0 CONFIGURATION REG)
The OPTION_REG Register is a readable and writable register, which contains various control bits to
configure the TMR0 Prescaler/WDT Postscaler (single assignable register known also as the Prescaler), the
external INT interrupt, TMR0, and the weak pull-ups on PORTB.
RBPU: PORTB Pull-up Enable bit (This bit is not used for timers)
1 = PORTB pull-ups are disabled
0 = PORTB pull-ups are enabled by individual port latch values
INTEDG Interrupt Edge Select bit
1 = Interrupt on the rising edge of RB0/INT pin
0 = Interrupt on the falling edge of RB0/INT pin
T0CS: TMR0 Clock Source Select bit
1 = Transition on T0CKI pin
0 = Internal instruction cycle clock (CLKO)
T0SE: TMR0 Source Edge Select bit
1 = Increment on high-to-low transition on T0CKI pin
0 = Increment on low-to-high transition on T0CKI pin
PSA: Prescaler Assignment bit
1 = Prescaler is assigned to the WDT
0 = Prescaler is assigned to the Timer0 module
PS2:PS0: Prescaler Rate Select bits
Page 187
Timer 1
Timer1 is a 16-bit timer/counter. The clock source can be either the internal system clock (Fosc/4),
an external clock, or an external crystal. Timer1 can operate as either a timer or a counter. When operating
as a counter (external clock source), the counter can either operate synchronized to the device or
asynchronously to the device. Asynchronous operation allows Timer1 to operate during sleep, which is
useful for applications that require a real-time clock as well as the power savings of SLEEP mode.
Timer 1 also has a prescaler option, which allows TMR1 to increment at the following rates: 1:1, 1:2,
1:4 and 1:8 TMR1 can be used in conjunction with the Capture/Compare/PWM module. When used with a
CCP module, Timer1 is the time-base for 16-bit capture or 16-bit compare and must be synchronized to the
device.
Page 188
Page 189
Timer 2
Timer 2 is an 8-bit timer with a programmable prescaler and a programmable postscaler, as well as
an 8-bit Period Register (PR2). Timer 2 can be used with the CCP module (in PWM mode) as well as the
Baud Rate Generator for the Synchronous Serial Port (SSP). The prescaler option allows Timer2 to
increment at the following rates: 1:1, 1:4 and 1:16.
The post scaler allows TMR2 register to match the period register (PR2) a programmable number of
times before generating an interrupt. The postscaler can be programmed from 1:1 to 1:16 (inclusive).
Page 190
TIMER2 BLOCK DIAGRAM
Page 191
PWM mode compares the TMR2 register to a 10-bit duty cycle register (CCPRxH:CCPRxl<5:4>) as
well as to an 8-bit period register (PR2). When the TMR2 register=Duty Cycle register, the CCPx pin will
be forced low. When TMR2=PR2, TMR2 is cleared to 00h, an interrupt can be generated, and the CCPx pin
(if an output) will be forced high.
INTERRUPTS :
The PIC16F8XX family has up to 11 sources of interrupt. The interrupt control register (INTCON)
records individual interrupt requests in flag bits. It also has individual and global interrupt enable bits.
Global interrupt enable bit, GIE enables all un-masked interrupts or disables all interrupts. When bit
GIE is enabled, and an interrupt flag bit and mask bit are set, the interrupt will vector immediately.
Individual interrupts can be disabled through their corresponding enable bits in the INTCON register. GIE is
cleared on reset.
The “return from interrupt” instruction, RETFIE, exits the interrupt routine as well as sets the GIE
bit, which re-enable interrupts.
The RBO/INT pin interrupt, the RB port change interrupt and the TMR0 overflow interrupt flag bits
are contained in the INTCON register.
The peripheral interrupt flag bits are contained in special function registers PIR1 and PIR2. The
corresponding interrupt enable bits are contained in special function registers PIE1 and PIE2 and the
peripheral interrupt enable bit is contained in special function register INTCON.
When an interrupt is responded to, bit GIE is cleared to disable any further interrupts, the return
address is pushed onto the stack and the PC is loaded with 0004h. Once in the interrupt service routine the
source(s) of the interrupt can be determined by polling the interrupt flag bits. The interrupt flag bit(s) must
be cleared in software before re-enabling interrupts to avoid recursive interrupts.
For external interrupt events, such as the RB0/INT pin or RB port change interrupt, the interrupt
latency will be three or four instruction cycles. The exact latency depends when the interrupt event occurs.
The latency is the same for one or two cycle instructions. Once in the interrupt service routine the source(s)
of the interrupt can be determined by polling the interrupt flag bits. The interrupt flag bit(s) must be cleared
in software before re-enabling interrupts to avoid infinite interrupt requests. Individual interrupt flag bits are
set regardless of the status of their corresponding mask bit or the GIE bit.
INT INTERRUPT :
External interrupt on RB0/INT pin is edge triggered: either rising if edge select bit INTEDG is set, or
falling, if bit INTEDG is clear. When a valid edge appears on the RB0/INT pin, flag bit INTF is set. This
interrupt can be disabled by clearing enable bit INTE. The INTF bit must be cleared in software in the
interrupt service routine before re-enabling this interrupt. The INT interrupt can wake the processor from
SLEEP, if enable bit INTE was set prior to going into SLEEP. The status of global enable bit GIE decides
whether or not the processor branches to the interrupt vector following wake-up. See for details on SLEEP
mode.
Page 192
TMR0 INTERRUPT:
An overflow in the TMR0 register will set flag bit T0IF. The interrupt can be enabled/disabled by
setting/clearing enable bit T0IE.
PORTB INTERRUPT ON CHANGE :
An input change on PORTB sets flag bit RBIF. The interrupt can be enabled/disabled by
setting/clearing enable bit RBIE.
WATCH DOG TIMER (WDT):
The Watchdog Timer is a free running on-chip RC oscillator which does not require any external
components. This RC oscillator is separate from the RC oscillator of the OSC1/CLKIN pin. That means that
the WDT will run, even if the clock on the OSC1/CLKIN and OSC2/CLKOUT pins of the device has been
stopped, for example, by execution of a SLEEP instruction. During normal operation, a WDT time-out
generates a device reset. If the device is in SLEEP mode, a WDT time-out causes the device to wake-up and
continue with normal operation. The WDT can be permanently disabled by clearing configuration bit
WDTE.
WDT PERIOD:
The WDT has a nominal time-out period of 18 ms, (with no prescaler). The time-out periods vary
with temperature, VDD and process variations from part to part (see DC specs). If longer time-out periods
are desired, a prescaler with a division ratio of up to can be assigned to the WDT under software control by
writing to the OPTION register. Thus, time-out periods up to seconds can be realized.
The CLRWDT and SLEEP instructions clear the WDT and the postscaler, if assigned to the WDT,
and prevent it from timing out and generating a device RESET condition.
The TO bit in the STATUS register will be cleared upon a WDT time-out.
WDT PROGRAMMING CONSIDERATIONS:
It should also be taken in account that under worst case conditions (V DD = Min., Temperature =
Max., max WDT prescaler) it may take several seconds before a WDT time-out occurs.
ADDRESSING MODES.
The PIC microcontrollers support only TWO addressing modes .They are
(i) Direct Addressing Mode
(ii) Indirect Addressing mode
Direct Addressing Mode :
In direct addressing mode 7 bits (0-6) of the instruction identify the register file address and the 8 th bit
of the register file address register bank select bit(RP0).
Page 193
The above diagram explains the method of accessing register file address 13H by direct addressing method.
Indirect Addressing Mode
In the indirect addressing mode the 8-bit register file address is first written into a Special Function
Register(SFR) which acts as a pointer to any address location in the register file.A subsequent direct access
of INDF will actually access the register file using the content of FSR as a pointer to the desired location of
the operand.
INSTRUCTION SET
While writing the instructions the following guidelines are followed.
a) Write the instructions mnemonics in lower case (example: xorwf)
b) Write special Register names, RAM variable names and bit names in upper case (example: STATUS,
RPO….)
c) Write instruction and subroutine labels in mixed case (example: Mainline, LoopTime..)
The instruction set of PIC is divided into Three basic categories. They are
(a) Byte oriented Instructions
(b) Bit oriented Instructions
(c) Literal and Control Instructions
Byte Oriented Instructions
In a byte oriented Instructions f represents a file register and d represents destination register.The
destination specifies where the result of operation is to be placed. If D= 0 the result is placed in W
register(Accumulator) and if d = 1 , the result is placed in the file register specified in the instruction.
ADDWF f, d ; Add W and f
CLRF f ; Clear f
MOVWF f ,d ; Move f
Page 194
NOP ; No operation
SUBWF f ,d ; Subtract W from f
Page 196
Clear/move
Clrw ;Clear the working register, W
clrf TEMP1 ;Clear temporary variable TEMP1
movlw 5 ;Load 5 into W
movlw 10 ;Load D ‘10’ or H ‘10’ into W
;depending upon default representation
movwf TEMP1 ;Move W into TEMP1
movwf TEMP1, F ;Incorrect syntax
movf TEMP1, W ;Move TEMP1 into W
swapf TEMP1, F ;Swap 4-bit nibbles of TEMP1
swapf TEMP1, W ;Move TEMP1 to W, swapping nibbles
;and leave TEMP1 unchanged
Increment/decrement/complement
incf TEMP1, F ;Increment TEMP1
incf TEMP1, W ;W < - TEMP1 + 1; TEMP1 unchanged
decf TEMP1, F ;Decrement TEMP1
comf TEMP1, F ;Change 0s to 1s and 1s to 0s
Multiple-bit manipulation
andlw B’00000111’ ;Force upper 5 bits of W to zero
andwf TEMP1, F ;TEMP1 < - TEMP1 and W
andwf TEMP1, W ;W < - TEMP1 AND W
iorlw B’00000111’ ;Force lower 3 bits of W to one
iorwf TEMP1, F ;TEMP1 < - TEMP1 or W
xorlw B’00000111’ ;Complement lower 3 bits of W
xorwf TEMP1, W ;W < - TEMP1 XOR W
Addition/Subtraction
addlw 5 ;Add 5 to W
addwf TEMP1, F ;TEMP1 < - TEMP1 + W
sublw 5 ;W < - 5 – W (not W < - W – 5!)
subwf TEMP1, F ;TEMP1 < - TEMP1 – W
Rotate
rlf TEMP1, F ;Nine-bit left rotate through C
;(C < - TEMP1, 7; TEMP1, I+1 < - TEMP1, I
; TEMP1, 0 < - C)
rrf TEMP1, W ; Leave TEMP1 unchanged
Page 197
;copy to W and rotate W right through C
Conditional branch
btfsc TEMP1, 0 ;Skip the next instruction if bit 0 of
;TEMP1 equals zero
btfss STATUS, C ;Skip if C = 1
decfsz TEMP1 , F ;Decrement TEMP1; skip if zero
incfsz TEMP1, W ;Leave TEMP1 unchanged; skip if
;TEMP1 = H’FF’; W< - TEMP1 + 1
Goto/call/return/return from interrupt
goto There ;Next instruction to be executed is
; labeled “There”
call Task1 ;Pushed return address; next instruction
;to be executed is labeled “Task1”
return ;Pop return address off of stack
retlw 5 ;Pop return address; W < -5
retfie ;Pop return address; reenable interrupts
Miscellaneous
Clrwdt ;If watchdog timer is enabled, this; instruction will
reset it (before it,;resets the CPU)
sleep ;Stop clock; reduce power; wait,;for watchdog timer
or external signal;to begin program execution
nop again ;
Do nothing; wait one clock cycles
Bank Switching : In PIC 18F family of microcontrollers the data memory 4096 bytes is partitioned into
multiple banks. These banks contain the general purpose registers and the Special function
Registers(SFRs).The minimum bank that every PIC has is known as Access bank.The access bank consists
of 128 bytes of lower addresses and 128 bytes of higher addresses.The lower 128 bytes of address space 000
– 07fh is used for general purpose RAM and the higher 128 bytes F80 – FFF H are dedicated to SFRs.Bank
switching is used to take the advantage of the entire RAM. Space. By default the access bank is selected.If
we want to change the bank ,the bit in the bank selection register A must be changed. If A =1 , the
instruction MOVWF filereg A, will use the bank selector register (BSR) to select the desired bank.
The BSR is a part of SFRs and it is an 8- bit register .Among the 8-bits only the least 4-bits are used in
bank switching and the upper 4-bits are set to zero and ignored. Using these 4-bits , we can select any of the
16 banks namely Bank 0 to Bank F, which covers the entire 4096 bytes of the RAM area. If the BSR is
Page 198
equal to 1 ,it will select Bank 1 and if BSR is 2 ,Bank2 is selected .The diagram below shows the Data RAM
registers.
MOVLW 0 ; wreg = 0
INCF MYREG F ,1 ; A =1
In the above examples ,the bit A = 1 ,so the BSR can be used to switch to banks other than default access
bank.
Table processing: PIC 18F microcontrollers have a ROM area equal to 2MB,which is also known as
program memory. This program memory is under the direct control of program counter register. So, to fetch
the data from this ROM we need a special function register and hence this method is widely known as
register indirect addressing mode.This process of accessing the Code in the ROM is also called Table
processing.
Certain instructions are provided for accessing the tables. To read the fixed data type ,an address pointer is
used ,which points to to the byte to be fetched. The TBLPTR is a 21 –bit register used to point to the byte to
be fetched. With this 21-bit register ,the entire 2MB of program ROM space can be covered. But the
Page 199
problem is ,there is no instruction to load the 21 –bit address into TBLPTR. So,the TBLPTR is divided into
three 8-bit registers called TBLPTRL(low),TBLPTRH(high) and TBLPTRU(upper).All the three are part of
the SFRs
The other SFR register used for table processing is TAB-LAT(Table Latch) which is used to keep the
fetched byte into the CPU.The instruction INCF TBLPTRL is used to increment the pointer. There are also
instructions like TBLRD*+ ,which read the table and increment and TBLRD*D, which read the table and
decrement.
The following table gives the table read instructions and their description.
Macros and Modules : In assembly language programming certain group of instructions may have to be
called repeatedly in the program. It will be highly time consuming to write the code every time we use it.
Instead of writing the code every time we use the concept of writing the code once and invoking it when
ever it is required..This concept is called Macros. These Macros will allow to call and execute the
program written already .
To create a Macro ,first it must be defined. Every Macro definition has three parts as shown below.
---------
----------
ENDM
Page 200
Here the MACRO is a directive which indicates the beginning and the ENDM directive indicates the End of
the Macro. The code between MACRO and ENDM denotes the body of the macro. The dummies are the
names or parameters or even registers used in the body of the macro.Once the macro is written ,it can be
called by its name and suitable values can be added to the dummy parameters. The normally used Macro
service is moving the literal data in to RAM.This can be done as shown below.
MOVLW K
MOVWF MYJOB
ENDM.
Example 1: MOVLF 0X55 ,0X20 ;send the value 55H to the location 20H
The directive LOCAL is used to indicate the labels field body of the macro.
INCLUDE is another directive used to write the macros and save them in a file and later bring them into
any program file.
Differences between Macros and Subroutines: Macros increase the code size every time they are
invoked.For example if we call a macro of 5 instructions for 5 times ,the code size is increased by 25
instructions.This is not the same in the case of a subroutine .In a subroutine the code size remains same.The
limitation of the subroutine is ,that it uses the stack space when called, which gives problems during the
nested callsdue to stack overflow.
MODULES : Generally ,while developing big software programs ,it is customary to divide the work into
small packages and distribute the task of writing these parts among the different programmers. These small
packages are called the modules and this method is called modular programming. This modular
programming has the following advantages.
Page 201
(i).Each module can be developed ,debugged and tested individually
(iv).One can use the modules to link with high level languages like C.
After writing each module in a program it is tested and all the modules are linked to make the complete
program.To enable these modules to be linked ,certain assembly language directives are used. The two
widely used directives are EXTERN (external) and GLOBAL. This GLOBAL is same as PUBLIC in other
assembly language programs.
The EXTERN directive is used to notify the assembler and linker that certain names and variables that are
not defined in the present module are defined externally .In the absence of the EXTERN directive ,the
assembler would show an error, because it cannot find the where the names are defined.
PIC I/O programming ( Programming the Ports ) : The PIC 16F family of microcontrollers have a total
of 33 pins arranged into 5 ports. PortA , Port B, Port C , Port D and Port E. In order to use them as I/O
ports, they must be properly programmed. In addition to acting as I/O ports , they also have certain
additional functions like ADC, Timers ,Interrupts and serial communication pins etc.
PORT A: Port A is a 6-bit wide bi-directional port. Its data direction register is TRISA setting TRISA bit to
1 will make the corresponding PORT A Pin an input. Clearing a TRIS a bit will make the corresponding pin
as an output.
PORT B:
Port B is an 8-bit wide, bi-directional port. Four of the PORT B pins RB 7 – RB4 have an interrupt-on-
change feature. Only the pins configured as inputs can cause this interrupt to occur.
PORT C:
Port C is an 8-bit wide, bidirectional port. Bits of the TRISC Register determine the function of its
pins. Similar to other ports, a logic one 1 in the TRISC Register configures the appropriate port pin as an
input.
PORT D:
Port D is an 8-bit wide bi-directional port. In addition to I/O port, Port D also works as 8-bit parallel
slave port or microprocessor port. When control bit PSPMODE (TRISE:4) is set.
PORT E:
It is a 3-bit bi-directional port. Port E bits are multiplexed with analog inputs of ADC and they serve
as control signals (RD , WR, CS) for parallel slave port mode of operation.
Page 202
The Ports of PIC controller are made either inpur or output ports by using the TRISx register ,which is a
SFR.To make the Port an output,0 must be written to the TRISx register and to use the pPort as input ,a 1
must be put in to the TRISx register. Fors example to make the PortB as input port , the bits of TRISB are
made 1(High).
The following example explains the I/O port programming.
Example 1: MOVLW 0x0
CALL DELAY
MOVLW 0X AA
CALL DELAY
GO TO L1
Example 2: In this example Port B and PORT C are used to transfer the data continuously.
Page 203
GOTO L2 ; Continue the loop.
So , it is clear that unless the TRIS bits are activated by putting a 1 ,the data will not be transferred to
WREG from the port pins of PORT C.
Page 204