MPMC TN
MPMC TN
COURSE OBJECTIVES:
➢ To introduce fundamental architectural concepts of microprocessors and microcontrollers.
➢ To impart knowledge on addressing modes and instruction set of 8086 and 8051
➢ To introduce assembly language programming concepts
➢ To explain memory and I/O interfacing with 8086 and 8051
➢ To introduce 16-bit and 32-bit microcontrollers.
COURSE OUTCOMES:
After completion of the course, the student will be able to
CO1: Understand the Architecture of 8086 microprocessor (K2)
CO2: Develop 8086 Assembly language programs (K3)
CO3: Explain interfacing of 8086 with peripheral devices (K3)
CO4: Develop assembly language programs for 8051 Microcontroller (K3)
CO5: Illustrate interfacing of 8051 with peripheral devices (K4)
CO-PO MAPPING:
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
CO1 2 - - - - - - - - - - 3 - 3
CO2 3 2 - - - - - - - - - 3 - 3
CO3 3 2 - - - - - - - - - 3 - 3
CO4 3 2 - - - - - - - - - 3 - 3
CO5 3 3 2 - - - - - - - - 3 - 3
UNIT – I (9 Hrs)
8086 Architecture: Evolution of Microprocessors, Main features of 8086, 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.
Learning Outcomes: At the end of this unit, students should be able to
• Summarize features of a microprocessor (L2)
• Understand the concepts of architecture of 8086. (L2)
• Explain about ISR and interrupt structure of 8086 (L2)
• Compare the minimum and maximum mode configurations of 8086 (L2)
Sreenivasa Institute of Technology and Management Studies R23
[AUTONOMOUS]
UNIT – II (8 Hrs)
8086 Programming: Program development steps, instructions, addressing modes, assembler
directives, writing simple programs with an assembler, assembly language program development
tools.
Learning Outcomes: At the end of this unit, students should be able to
• Understand instruction set of 8086 microprocessor (L2)
• Explain addressing modes of 8086 (L2)
• Develop assembly language programs for various problems (L3)
UNIT – IV (9 Hrs)
8051 Microcontroller and Programming: Comparison of Microprocessor and Microcontroller, Main
features of 8051, Architecture of 8051, 8051 pin diagram, Special Function Registers (SFRs), I/O
Pins Ports and Circuits, Instruction set, Addressing modes, Assembly language programming.
Learning Outcomes: At the end of this unit, students should be able to
• Describe architecture and features of Intel 8051 microcontroller (L2)
• Develop assembly language programs to perform various operations using 8051 (L3)
• Distinguish between microprocessor and a microcontroller (L2)
UNIT – V (9 Hrs)
Interfacing Microcontroller: Programming 8051 Timers, Serial Port Programming, Interrupts
Programming, LCD & Keyboard Interfacing, ADC, DAC & Sensor Interfacing, External Memory
Interface, Stepper Motor and Waveform generation.
Advanced Microcontrollers: PIC and ARM processors.
Learning Outcomes: At the end of this unit, students should be able to
• Explain memory & I/O interfacing with 8051 (L3)
• Illustrate interfacing of 8051 with peripheral devices (L4)
• Understand the advancements in the processors (L2)
TEXTBOOKS:
1. “Microprocessors and Interfacing – Programming and Hardware”, Douglas V
Hall, SSSPRao, Tata McGraw Hill Education Private Limited, 3rd Edition,
1994.
2. “Advanced Microprocessors and Peripherals”, K M Bhurchandi, A K Ray,
McGraw HillEducation, 3rd Edition, 2017.
3. “Microcontrollers: Architecture, Programming, Interfacing and System
Design”, RajKamal, Pearson, 2nd Edition, 2012.
REFERENCE BOOKS:
1. “Microprocessor 8086 Architecture, Programming, Interfacing”, Sunil
Mathur, PHILearning Private Limited, 2011.
2. “The 8051 Microcontroller”, Kenneth J. Ayala, Cengage Learning, 3rd Edition, 2004.
3. “Embedded Systems Fundamentals on Arm Cortex-M based
Microcontrollers: APractical Approach”, Alexander G. Dean
1. Introduction to 8086
2. Architecture of 8086
3. Memory segmentation
4. Registers of 8086
5. Pin configuration of 8086
6. Min. mode operation with Timing diagram
7. Max. mode operation with Timing diagram
8. Physical memory organization and Memory banks accessing
9. Interrupts of 8086 and Interrupt Vector Table (IVT)
----------------------------------------------------------------------------------------------------------------
The Intel released 8086 microprocessor in 1978, which is fabricated using HMOS technology.
The features of Intel 8086 are given below
Note: The architecture of 8088 is similar to 8086 except for two changes:
- The 8088 has 4-byte instruction queue where as 8086 has 6-byte instruction queue.
- The 8088 has 8-bit data bus where as 8086 has 16-bit data bus
- There is no B̅̅̅̅ H̅̅̅̅ E̅̅̅̅ signal in 8088
2
The Bus Interface Unit is responsible for all read and write operations of Memory and I/O.
It sends out 20-bit Physical address, fetches instruction code bytes from memory and stores
them in Instruction Queue.
The Execution unit is responsible for decoding and executing the instructions. It receives
instruction code bytes from Instruction Queue in BIU, decodes and executes them.
These two parts are operated in parallel for implementing pipelining concept and to increase
the execution speed.
The BIU handles all transfer of address, data and code on Buses. The BIU consists of
(i) Instruction Queue
(ii) Segment Registers
(iii) Instruction Pointer
(iv) 20-bit Physical address calculation circuit
The pipelining concept is implemented in 8086 using an Instruction Queue. While Execution
Unit (EU) is executing an instruction, the BIU will fetch upto 6- instruction code bytes from
memory and stores them in a FIFO group of registers called as Instruction Queue. When EU
is ready for its next instruction, it simply takes instruction bytes from Instruction Queue in
BIU. This is much faster than sending out an address to memory, waiting for memory to
send-back the next instruction bytes.
Note that the Instruction Queue fails in the case of branch instructions execution (Ex: JMP,
CALL, RET, etc). After the execution of branch instructions, the program execution jumps to
different location. Hence, the instructions available in the Instruction Queue will be erased
during the execution of branch instructions.
3
The 8086 uses memory segmentation. In this scheme, the complete 1 MB physical memory is
divided into number of logical segments. The size of each segment is 64 KB in size and is
addressed by one of the segment registers. The segment registers in BIU are used to define
the starting address of logical segments.
The segment registers in BIU hold the upper 16-bits of starting address of logical segments.
The BIU inserts ZERO’s for lower 4-bits of 20-bit starting address.
The IP register holds the offset address of the next instruction to be fetched from Code
segment. The Offset address is defined as the distance of operand from the Starting address
of the Segment.
The segment register defines the segment base address and a location within a segment
can be addressed by 16-bit offset address.
Note that the 20-bit Physical address is generally represented in the form of
Segment base : Offset = CS:IP = 2000:5678 H
The Execution unit is responsible for decoding and executing the instructions. It receives
instruction code bytes from Instruction Queue in BIU, decodes and executes them.
The EU consists of
(i) 16-bit ALU
(ii) General purpose registers: AX,BX,CX,DX
(iii) Index Registers : SI and DI
(iv) Pointers : SP and BP
(v) Flag Register/Program Status Word (PSW)
The EU consists of 16-bit ALU which can perform Arithmetic operations (such as Addition,
Subtraction, Multiplication, Division, Increment, Decrement, etc) and Logic operations (such
as Logic AND, OR, NOT, Ex-OR, Shift, Rotate, etc).
5
The 8086 has 4- general purpose registers - AX, BX, CX, DX.
All these registers are 16-bit registers used to store 16-bit data
Each register is divided in two 8-bit registers to store 8-bit data
These registers have multiple functions, shown in following Table.
Data Index Used to hold a part of result from MUL & DIV.
DX (or) Extended It is also used to hold the 16-bit I/O port address during
Accumulator I/O operation.
▪ The Index Registers are used to hold the 16-bit offset address of data stored in Data
and Extra segments.
▪ These registers are used in string operations to hold the offset address of source
string and destination strings.
The SI register holds the offset address of source string in Data Segment.
The DI register holds the offset address of destination string in Extra Segment.
▪ Address of source string → DS:[SI]
▪ Address of destination string → ES:[DI]
▪ The directional flag (DF) selects the increment (or) decrement mode for SI and DI
registers during String instructions manipulation.
DF = 0 selects increment mode and
DF = 1 selects decrement mode.
(iv) Pointers :
▪ The Pointers are used to hold the offset address relative to data and stack segments.
▪ The base pointer (BP) is used to access data in stack segment.
▪ The stack pointer (SP) is used to hold the address of stack top.
6
The flag register is used to indicate the status information (or) condition produced by an
instruction execution.
The 8086 has 6- status flags and 3-control flags.
Control flags:
These flags control the operation of the processor.
The 3- control flags of 8086 are DF, IF, TF.
15 12 11 10 9 8 7 6 5 4 3 2 1 0
OF DF IF TF SF ZF AF PF CF
Parity Flag(PF) : It is set to 1, if the result of an operation has even number of 1’s
Overflow Flag (OF) : It is set to 1, if the result of a signed operation exceeds the register
capacity.
7
Problem :
The content of registers AL and BL are 79H and 88H respectively. Determine the
status of control flags of 8086, after the execution of the instruction ADD AL,BL?
Ans:
AL = 79 H = 0111 1001 AL
BL = 88 H = 1000 1000 BL
The 8086 uses memory segmentation. In this scheme, the complete 1 MB physical memory is
divided into number of logical segments. The size of each segment is 64 KB in size and is
addressed by one of the segment registers.
The 64 KB logical segment can be located anywhere in 1 MB memory, but the segment will
always start at an address with ZERO’s in lowest 4-bits.
Note that the 8086 does not work the whole 1 MB memory at any given time. However it
works only with four 64 KB segments within the whole 1MB memory.
The four segment registers in BIU define the starting addresses of the four memory
segments with which the 8086 is working at that instant of time. The segment registers in
BIU are used to hold the upper 16-bits of starting address of logical segments. The BIU
inserts ZERO’s for lower 4-bits of 20-bit starting address.
9
Code Segment :
▪ The Code segment is used to store the program instruction codes.
▪ The Code Segment register (CS) is used to hold the upper 16-bits of starting address
of the Code segment. The BIU inserts ZERO’s for lower 4-bits of 20-bit starting
address.
▪ For example, if CS=2000H then the Code segment starts at 20000H.
Data Segment :
▪ The Data segment is used to store data variables and constants of the program.
▪ The Data Segment register (DS) is used to hold the upper 16-bits of starting address
of the Data segment.
▪ Data are accessed from Data segment by an Offset address.
▪ The SI, DI, BX, BP registers are used to store the offset address for data segment
Extra Segment :
▪ The Extra segment is an additional data segment.
▪ It is used in String operations to store the destination string.
▪ The Extra Segment register (ES) is used to hold the upper 16-bits of starting address
of the Extra segment.
▪ The SI, DI, BX, BP registers are used to store the offset address for data segment
Stack Segment :
▪ The Stack segment defines the area of memory used for stack.
▪ Stack is a section of memory where the data are accessed in LIFO manner
▪ The stack memory is used to store data, address and status information. It is used by
CPU to store return address during the execution of procedures and ISRs.
▪ The Stack Segment register (SS) is used to hold the upper 16-bits of starting address
of the Stack segment.
▪ The Stack Pointer (SP) register holds the address of Stack top.
The segment register holds the upper 16-bits of starting address of logical segments. The BIU
inserts ZERO’s for lower 4-bits of 20-bit starting address.
The Offset address is defined as the distance of operand from the Starting address of the
Segment. The registers used to store the 16-bit offset addresses for various segments are
given in Table.
▪ The lower order 16-address lines (A0 - A15) of 8086 are multiplexed with 16- data lines
(D0 - D15).
▪ During T1 state of Bus-cycle, the 8086 sends out address on these lines and during
later part of Bus-cycle this multiplexed bus is used as Data bus.
▪ All the above multiplexed pins are at high-impedance state during DMA operation.
▪ The higher order 4-address lines (A16 - A19) are multiplexed with Status lines (S3 - S6).
▪ The S3 and S4 shows which segment is accessed during current bus cycle.
▪ The S5 indicates the status of IF flag.
▪ The S6 is always logic 0 and it is not used.
▪ All the above multiplexed pins are at high-impedance state during DMA operation.
S4 S3 Segment
0 0 Code Segment
0 1 Data Segment
1 0 No Segment
1 1 Extra Segment
13
̅ ̅ / S7
𝐁̅̅̅̅𝐇̅̅𝐄̅̅ :
▪ The 1 MB Physical memory of 8086 is divided into two banks for accessing 16-bit
numbers. Each bank size is 512 K bytes.
▪ The Bus High Enable B̅̅̅̅ H̅̅̅̅ E̅̅̅̅ signal is used to enable the higher order data bus (D8 - D15)
connected to HIGH BANK.
▪ The status signal S7 is used by arithmetic co-processor 8087 to determine whether the
CPU is 8086 (or) 8088.
RESET :
▪ It forces all the registers to a predefined values and microprocessor gets reset.
▪ When Reset is active DS, ES, SS, IP and FLAG registers are initialized to 0000H and
CS is initialized to FFFF H.
▪ After Reset, the processor starts execution from FFFF0 H.
READY:
▪ A slow peripheral (or) memory device can be connected to microprocessor through
READY line. It is used to insert wait states in bus cycles as needed to interface with
slow memory & I/O
▪ It is used by the MPU to sense whether the peripheral is ready to transfer data or not
If READY =1, peripheral is ready to transfer data.
If READY=0, the processor WAITS until it goes to HIGH
14
𝐓̅̅̅̅𝐄̅̅̅𝐒̅̅𝐓̅̅̅ :
▪ This input is examined by WAIT instruction.
▪ The 8086 enters into WAIT state after the execution of WAIT instruction.
If T̅̅̅̅ E̅̅̅̅ S̅̅ T̅̅̅̅ = 0, the WAIT instruction functions as NOP
If T̅̅̅̅ E̅̅̅̅ S̅̅ T̅̅ =1, the processor waits until T̅̅̅̅ E̅̅̅̅ S̅̅ T̅̅ = 0.
▪ If the co-processor has finished its work then it makes T̅̅̅̅ E̅̅̅̅ S̅̅ T̅̅ = 0.
𝐑̅̅̅̅𝐃̅̅̅ :
The Read Control Signal is active whenever the processor is ready to read data from
Memory (or) I/O.
MN/ 𝐌̅̅̅̅̅𝐗̅̅̅̅ :
▪ The 8086 can be operated in two modes – Minimum mode and Maximum mode.
▪ The pin MN/M̅̅X̅̅̅̅ is used to select the Min. (or) Max. mode of operation.
MN/M̅̅X̅̅̅̅ = 1 for Minimum mode operation
MN/M̅̅X̅̅̅̅ = 0 for Maximum mode operation
▪ The pins (24-31) issues two different set of signals – for minimum & maximum
mode operations. These pins are described below:
Note : The [Link] pins and [Link] pins are described in sections [Link] 1.7.
Minimum mode:
▪ The min. mode operation is selected by connecting the pin MN/MX to + 5 V
▪ The 8086 is operated in minimum mode in simple systems with a single CPU
▪ In min. mode operation, all the control signals are generated by CPU
▪ It is least expensive way to operate and the operation is similar to 8085A.
▪ Min. Mode signals → I̅̅N̅̅T̅̅̅̅ A̅̅̅̅ , ALE, D̅̅E̅̅̅̅ N̅̅̅̅ , DT/R̅̅ , M/I̅̅ O̅̅, W̅̅̅̅ R̅̅̅̅ , HLDA, HOLD
Maximum mode:
▪ The max. mode operation is selected by connecting the pin MN/MX to GND
▪ The 8086 is operated in maximum mode in multi-processor system with more than
one processor.
▪ In max. mode, the control signals are generated by external Bus-controller 8288.
▪ The maximum mode operation is used only when the system contains arithmetic co-
processor such as 8087 numeric co-processor.
▪ Max. Mode signals → QS1, QS0, S̅̅̅̅ 0̅ , S̅̅ 1 , S̅̅̅̅ 2̅ , L̅̅ O̅̅̅̅ C̅̅ K̅̅ , RQ/G̅̅̅̅ T̅̅̅̅ 1̅ , RQ/G̅̅̅̅ T̅̅̅̅ 0̅
15
Clock generator :
▪ It generates a CLK of frequency 5 MHz
▪ It provides the basic timing for µp and bus control activity
▪ It also synchronizes some external signals with the system clock
Address Latches :
▪ Latches are used for de-multiplexing of AD0 – AD15 , A16/S3 - A19/S6 and B̅̅̅̅ H̅̅ E̅̅̅̅ / S7
▪ Latches are used for the separation of address and data lines
▪ Address latch enable (ALE) signal is used to enable the Latches
Transceivers/ Bi-directional data buffers
▪ The Bi-directional data buffers (transmitters/receivers) are used to maintain proper
signal quality. i.e., to increase the fan-out of the system.
▪ The D̅̅E̅̅̅̅ N̅̅̅̅ signal is used to enable the bi-directional data buffers
▪ The DT/R̅̅ signal controls the flow of data through data buffers
16
𝐈̅̅𝐍̅̅̅𝐓̅̅̅𝐀̅̅̅ ( pin-24) :
▪ The interrupt acknowledge signal is a response to the INTR.
▪ It indicates the recognition of an Interrupt Request.
ALE (pin-25) :
▪ The address latch enable signal is used to indicate the presence of valid address
information on multiplexed bus (AD0 - AD15 )
▪ This signal is used to enable the Address Latches.
▪ The address latches are used to separate the address and data lines.(demultiplexing)
𝐃̅̅̅̅𝐄̅̅̅𝐍̅̅̅ (pin-26) :
▪ The data buffers enable signal is used to enable the bi-directional data bus buffers.
▪ The data bus buffers or transceivers (transmitters/receivers) are used to maintain
proper signal quality.
𝐖̅̅̅̅̅𝐑̅̅̅̅ (pin-29) :
This control signal is active whenever the processor is writing data to Memory or I/O
▪ The working of microprocessor based system can be explained with the help of
Timing diagrams.
▪ The timing diagrams provide the information about the various conditions of the
signal while a machine cycle is executed.
Instruction cycle:
▪ The time required for the microprocessor to fetch, decode & execute an instruction is
called an Instruction cycle.
▪ An instruction cycle consists of one (or) more bus cycles.
The timing diagram for Memory Read cycle in Minimum mode is shown in figure.
18
▪ The max. mode operation is selected by connecting the pin MN/MX to GND
▪ The 8086 is operated in max. mode in multi-processor system with more than one
processor.
▪ In max. mode, the control signals are generated by external Bus-controller 8288.
▪ The maximum mode operation is used only when the system contains arithmetic co-
processor such as 8087 numeric co-processor.
▪ Max. Mode signals → QS1, QS0, S̅̅̅̅ 0̅ , S̅̅ 1 , S̅̅̅̅ 2̅ , L̅̅ O̅̅̅̅ C̅̅ K̅̅, RQ/G̅̅̅̅ T̅̅̅̅ 1̅ , RQ/G̅̅̅̅ T̅̅̅̅ 0̅
19
𝐋̅̅̅̅𝐎̅̅̅𝐂̅̅̅𝐊̅̅̅ : ( pin-29)
▪ This pin indicates that the processor is executing a LOCK prefixed instruction and
the System bus is not to be used by another bus-master.
▪ This pin is used in multi-processor system to prevent other Bus masters from taking
the control of System bus during the execution of a critical instruction.
▪ The Physical memory of 8086 is divided into TWO banks for accessing 16-bit
numbers. Each bank size is 512 K bytes.
▪ The data bus (D0 - D7) is connected to LOW bank /EVEN bank.
▪ The data bus (D8 - D15) is connected to HIGH bank/ ODD bank.
▪ Both Banks are enabled at a time for 16-bit operations
▪ Address lines (A1-A19) are used to select a location within the bank
▪ The LOW bank is selected by A0
▪ The HIGH bank is selected by B̅̅̅̅ H̅̅̅̅ E̅̅̅̅ signal.
▪ Both Banks are enabled at a time for 16-bit operations.
▪ Note that the address must be EVEN for 16-bit access.
▪ Interrupt is an event that causes the µp to stop the normal program execution.
▪ The µp services the interrupt by executing a subroutine called Interrupt Service Routine
▪ After executing ISR, the control is transferred back again to the main program.
Hardware Interrupts :
These interrupts occur as signals on the external pins of the microprocessor. 8086 has
two pins to accept hardware interrupts, NMI and INTR.
Software Interrupts :
These interrupts are caused by writing the software interrupt instruction INT N
where ‘N’ can be any value from 0 to 255 (00H to FFH). Hence all 256 interrupts can
be invoked by software.
Error conditions :
The 8086 is interrupted when some special conditions occur while executing certain
instructions in the program.
Example: Divide error, Overflow etc
23
Processing of Interrupts
The code to handle an interrupt is called an interrupt handler or Interrupt Service Routine (ISR).
An interrupt service routine must always finish with the special instruction IRET (return
from interrupt), which performs the following actions.
In 8086 interrupt system, the first 1 KB memory from 00000 H to 003FF H is reserved for
storing the starting addresses of ISRs. This block of memory is called as IVT.
▪ The Interrupt vector table contains 256 interrupt vectors
▪ The interrupt vector contains IP and CS values of ISR
▪ The address of interrupt vector can be calculated by multiplying the TYPE with 4
▪ For example, The interrupt vector address for Type-02 interrupt = 02 H*4= 00008 H
Problem:
The contents of memory location 0000:008C are given below
0000:008C → 12, 34, 56, 78, 90, 92
(a) What is the interrupt vector address for Type-23H interrupt?
(b) Find the address of ISR corresponding to INT 23H
(c) For which type of interrupt, the interrupt vector address is 0000:00C8H
UNIT-2
ASSEMBLY LANGUAGE PROGRAMMING WITH 8086
----------------------------------------------------------------------------------------------------------------
1. Immediate addressing: The operand (or) data is available in the instruction itself.
Ex: MOV AX, 1234H
ADD AX, 4567H
2. Register addressing: The data is available in any one of the general purpose registers.
Ex: MOV AX, BX
ADD AX, BX
3. Direct addressing: The offset /effective address of the data is available in the instruction.
Ex: MOV BX, DS:[2000H]
ADD AX, DS:[3000H]
The effective address of data is available in any one of the Base (or) Index registers
6. Implicit addressing:
There are some instructions which operate on the content of Accumulator. Such
instructions do not require the address of operand. This type of addressing is called as
Implicit (or) Implied addressing.
Ex: DAA - Decimal Adjust Accumulator after addition
AAA - ASCII Adjust Accumulator after addition
(a) Fixed port addressing: The 8-bit I/O port address is available in the instruction
Ex: IN AL, 80H ; Reads data from port address 80H to AL
OUT 82H, AL ; Sends data from AL to port address 82H
(b) Variable port addressing: The 16-bit I/O port address is available in DX register.
Ex: IN AL, DX
OUT DX, AL
For the Control transfer instructions (or) Branch instructions such as JMP, CALL, RET,...etc,
the addressing modes depend on whether the destination address lies in the same code
segment (or) different code segment.
These are 2- types : (a) Intra segment mode
(b) Inter segment mode
▪ In this mode, the destination address lies in the same Code segment.
▪ Here only IP is modified. CS remains the same.
(i) Intra-segment Direct : In this mode the instruction specifies the DISP value
destination IP = Present IP + 8-bit (or) 16-bit DISP given in instruction
Ex: JMP displacement
JMP SHORT Lable
Note:
(i) If the displacement is 8-bit, the destination lies within -128 bytes to +127 bytes.
This type of JUMP is called as SHORT JUMP.
(ii) If the displacement is 16-bit, the destination lies within -32 K bytes to +32 K bytes
This type of JUMP is called as LONG JUMP.
30
destination IP [BX]
destination CS [BX+2]
31
Problem :
Calculate the offset address and 20-bit physical address for the following addressing
modes. The content of different registers are given below:
DS = 4000H, ES =6000H, SS= 8000H, SP=1998H
BX = 6688H, SI= 3333H, DI= 4444H
(a) MOV AX, DS:[5060H] (or) MOV AX, [5060H] -- Direct addressing
Offset address = 5060 H
Segment base = DS*10 = 40000 H
20-bit Physical address = 45060 H
(d) MOV AX, 5000 [BX] [SI] - Relative Based Indexed addressing
Offset address = BX+SI = 99CC H
Segment base = DS*10 = 40000 H
20-bit Physical address = 499CC H
Here, Source is AX SP SP - 2
Destination is Stack [SP] AX
Instruction
▪ There are 6- instruction formats in 8086 instruction set. The length of an instruction may
vary from 1 to 6 bytes.
D7 DO
D7 D0 D7 D6 D5 D4 D3 D2 D1 D0
OPCODE W 1 1 REG R/M
D7 D0 D7 D6 D5 D4 D3 D2 D1 D0
OPCODE W MOD REG R/M
▪ This format is also two bytes long, and similar to Register to Register format, except
the MOD filed.
▪ The first byte represents Op-code and width of the operand
▪ The second byte represents the register operands and R/M fields
▪ The MOD filed represents mode of addressing.
D7 D0 D7 D6 D5 D4 D3 D2 D1 D0
OPCODE W MOD REG R/M
D7 D0 D7 D0
Low byte of DISP High byte of DISP
▪ This format contains one (or) two additional bytes for DISP along with 2-byte format
of Register to Memory without Displacement.
D7 D0 D7 D6 D5 D4 D3 D2 D1 D0
OPCODE 11 OPCODE R/M
D7 D0 D7 D0
Low byte of data High byte of data
▪ In this format, the first byte and 3-bits from the second byte are used to represent the
Op-code. (Immediate addressing mode)
▪ It also contains one (or) two additional bytes of immediate data
D7 D0 D7 D6 D5 D4 D3 D2 D1 D0
OPCODE MOD OPCODE R/M
D7 D0 D7 D0
Low byte of DISP High byte of DISP
D7 D0 D7 D0
Low byte of data High byte of data
Registers Codes
Segment
REG W=1 W=0 SREG
Register
000 AX AL 00 ES
001 CX CL 01 CS
010 DX DL 10 SS
011 BX BL 11 DS
100 SP AH
101 BP CH
110 SI DH
111 DI BH
3 XOR dest, source Performs bitwise Ex-OR operation of Source and Destination
4 NOT dest Performs 1’s complement of destination
Performs bitwise logical AND operation on the two operands.
5 TEST dest, source
Only flags are affected. Result is not stored anywhere
6 SHL / SAR Logical shift Left / Arithmetic shift Left (by 1 or CL)
7 SHR Logical shift Right
▪ Directives are used to direct the assembler during assembly process, for which no
machine code is generated. The Assembler directives are hints given to the assembler
(ii) ENDS : This directive is used to indicate the ending of the logical segment
Syntax : Seg_name ENDS
Example : DATA ENDS
(iii) END : This directive is used after the last statement of the program to indicate
the ending of the program
Syntax : END
(iv) ASSUME : This directive is used to inform the name of the logical segments to be
used as Code segment, Data segment, Extra segment and Stack segment
Syntax : ASSUME Seg_Reg : Seg_name
Example : ASSUME CS: CODE, DS: DATA, ES: EXTRA
(v) GROUP : This directive is used to group the logical segments into one logical
segment. i.e., the grouped segments will have same segment base.
Syntax : Group_name GROUP: Seg1_name, Seg2_name, ....
Example : SMALL_SYSTEM GROUP DATA, CODE, EXTRA
39
These directives are used to define the program variables and allocate a specified
amount of memory to them. They are of type Byte, Word, Double word and Quad word.
(iii) DD : This directive is used to define a variable of type Double word (4-bytes)
Syntax : Var_name DD value
Examples : N DD 11223344 H
(iv) DQ : This directive is used to define a variable of type Quad word (8-bytes)
Syntax : Var_name DQ value
Examples : N DD 1122334455667788 H
(v) DT : This directive is used to define a variable of type Ten bytes (10-bytes)
Syntax : Var_name DT value
Examples : N DT 11223344556677889900 H
3. Alignment Directives
These directives are used to modify the memory location counter
(i) ORG: This directive is used to set the location counter to desired value.
Syntax : ORG value
Examples : ORG 4000 H ; location counter = 4000 H
ORG $+1000 H ; location counter is incremented by 1000H
(ii) EVEN : This directive is used to increment the location counter to next Even
address, if the present address is Odd. The 8086 can access a word in one
bus-cycle, if the address is Even. Hence a series of words can be quickly
accessed, if they are stored at Even address
Syntax : EVEN
40
(i) OFFSET : This directive is used to determine the offset address of the variable
Example : MOV SI, OFFSET ARRAY
(ii) TYPE : This directive is used to determine the Type of the variable
(1- Byte , 2- Word, 4- Double word, 8- Quad word)
Example : MOV AX, TYPE ARRAY
(iii) LENGTH : This directive is used to determine the no. of elements in a data item
Example : MOV AX, LENGTH ARRAY
(iv) SIZE : This directive is used to determine the no. of bytes allocated to data item
Example : MOV AX, SIZE ARRAY
(v) SEG : This directive is used to determine the segment base, in which the specified
data item is defined
Example : MOV AX, SEG ARRAY
(ii) PUBLIC :
▪ This directive informs the assembler that the data items /procedures declared as
PUBLIC can be accessed from any other program module.
▪ It helps in managing multiple program modules by sharing the global variables
(iii) EXTRN :
▪ This directive informs the assembler that the data items declared after EXTRN
have already been defined in some other program module.
▪ Note that, only PUBLIC variables are accessible when EXTRN is used d variables
can be accessed from any other program module.
▪ It helps in managing multiple program modules by sharing the global variables
Example:
The data items N1 and N2 are defined in Program module-1 and declared as PUBLIC.
These variables can be accessed in Program module-2, by declaring them as EXTRN
42
Example:
DATA SEGMENT
ORG 4000 H
N1 DW 1234 H
ARRAY DW 1000H, 2000H, 3000H, 4000H
N2 DW ?
DATA ENDS
2.5. PROCEDURES
A procedure is a group of instructions that usually perform one task and stored in
memory once, but used as often as necessary.
Disadvantages : (1) it takes some time to link from main program to procedure and
Procedure to main program
(2) it uses stack memory (to store the Return address)
▪ A procedure which lies in the same code segment is called as NEAR procedure
▪ Since, the procedure lies in the same code segment, only IP will be modified
and CS remains the same. (Intra-segment)
▪ The near CALL instruction is used to call a near procedure
▪ The Near CALL instruction performs the following two actions
- It pushes the return address (only IP value) on to the stack
- It loads IP with the offset address of procedure, so that the flow of
execution is transferred to procedure
▪ The RET instruction at the end of the NEAR procedure returns the flow of
execution from Procedure to main program. This instruction pops the return
address from stack memory.
44
▪ The RET instruction at the end of the NEAR procedure returns the flow of
execution from Procedure to main program. This instruction pops the return
address from stack memory.
Note: The procedures are defined using directives PROC and ENDP
PROC → indicates the beginning of the procedure
ENDP → indicates the ending of the procedure
The data values passed from main program to procedure and from procedure to main
program are called as parameters. The different methods of passing parameters are
(a) Using registers
(b) Using pointes / general purpose memory
(c) Using stack memory
(a) Using registers → The parameters to be passed are stored in register and then
CALL instruction is executed.
Ex: MOV AL, N
CALL fact
MOV RES, BX
In above example, the register AL is used to pass the input number N to the procedure
and register BX is used to pass the result from procedure to main program.
Using this method, we can’t pass more number of parameters.
(b) Using Pointers → In this method, the parameters can be directly accessed from
memory using pointers from procedure.
Ex: MOV SI, OFFSET N
MOV DI, OFFSET RES
CALL fact
In above example, before calling the procedure, the SI and DI registers are initialized
to set as source and destination pointers. Hence, the parameters can be directly
accessed from memory using these pointers.
Using this method, more number of parameters can be passed by incrementing the
pointers.
(c) Using Pointers → In this method, the parameters to be passed are pushed onto the
stack memory, before calling the procedure.
Ex: PUSH AX
CALL fact
POP BX
In above example, before calling the procedure, the parameters to be passed are
pushed on to the stack. In procedure, we can read the parameter from stack by using
POP instruction.
46
2.6. MACROS
▪ If a group of instructions are repeating again and again in the main program, the
listing will be lengthy. The process of assigning a label (or) macro name to
the group of repeated instructions is called Macro. The macro name is then
used throughout the main program to refer that group of instructions.
▪ During the assembly process, the assembler generates machine codes for the
group of instructions and replaces the macro name with the group of instructions.
Disadvantages : (1) Main program length increases, because the macro name is
replaced with group of instructions
▪ The parameters can be directly passed to macro along with macro name
FACT MACRO N
MOV AL, N
MOV CL, AL
DEC CL
UP: MUL CL
DEC CL
JNZ UP
MOV BX, AX
ENDM
Machine code will be put in memory Machine code of macro are added to
2 only once, and called many times from main program each time the macro is
main program called
(1) Write an ALP to find the average of N- words which are located at ARRAY.
DATA SEGMENT
N DW 0005H
ARRAY DW 1000H, 2000H, 3000H, 4000H, 5000H
RES DW ?
DATA ENDS
CODE SEGMENT
ASSUME CS:CODE, DS:DATA
MOV AX, DATA
MOV DS, AX
down : INC SI
INC SI
LOOP UP
MOV BX, N
DIV BX
MOV RES, AX
HLT
CODE ENDS
END
49
CODE SEGMENT
ASSUME CS:CODE
CODE ENDS
END
(3) An array of 16-bit numbers are located at ARRAY1. Find the 2’s complement
of each word and store them at ARRAY2.
CODE SEGMENT
ASSUME CS:CODE
INC SI
INC SI
INC DI
INC DI
LOOP UP
HLT
CODE ENDS
END
50
(4) An array of 8-bit numbers are located at ARRAY. Write an ALP to separate the ODD
and EVEN numbers. Store the ODD numbers at ARRAY2 and EVEN numbers at
at ARRAY3.
CODE SEGMENT
ASSUME CS:CODE
down: INC SI
LOOP UP
HLT
CODE ENDS
END
(5) Write a program to count the number of positive numbers and negative numbers in a
given series of signed numbers
CODE SEGMENT
ASSUME CS:CODE
INC BX
JMP down
odd_num : INC DX
down: INC SI
LOOP UP
HLT
CODE ENDS
END
(6) Write an 8086 ALP to find the largest number in given array of N-numbers
CODE SEGMENT
ASSUME CS:CODE
down: INC SI
LOOP UP
HLT
CODE ENDS
END
52
CODE SEGMENT
ASSUME CS:CODE
HLT
CODE ENDS
END
CODE SEGMENT
ASSUME CS:CODE
INC DI
LOOP UP
MOV AX,0000H
JMP exit
exit : HLT
CODE ENDS
END
53
(9) Write an 8086 ALP to search a character ‘R’ in the given string.
If the character is found, store 1111H in AX. Otherwise store 0000H in AX
CODE SEGMENT
ASSUME CS:CODE
REPNE : SCASB
JE down
MOV AX,0000H
JMP exit
exit : HLT
CODE ENDS
END
(10) Write an 8086 ALP to count the number of characters ‘R’ in the given string.
CODE SEGMENT
ASSUME CS:CODE
UP: NOP
SCASB
JNE down
down: LOOP UP
HLT
CODE ENDS
END
54
(11) Write an 8086 assembly language program to move a string of length of 8-bytes
from ‘OLD_HOME’ to ‘NEW_HOME’
CODE SEGMENT
ASSUME CS:CODE
REP: MOVSB
HLT
CODE ENDS
END
REP: MOVSB
RET
movstr ENDP
REP: MOVSB
ENDM
55
CODE SEGMENT
ASSUME CS:CODE
HLT
CODE ENDS
END
(15) Write a Program to compare two strings, which are located at ARRAY1 and ARRAY2
If two strings are equal than store 1111H in AX , otherwise store 0000H in AX
CODE SEGMENT
ASSUME CS:CODE
MOV AX,1111H
REPE: CMPSB
JE down
down : NOP
HLT
CODE ENDS
END
(16) Write a Program to check whether the given string is Palindrome (or) not?
(17) Write an ALP to sort the given series of numbers in ascending order
CODE SEGMENT
ASSUME CS:CODE
UP : MOV AL,[SI]
INC SI
CMP AL,[SI]
JB down
XCHG AL,[SI]
DEC SI
MOV [SI],AL
INC SI
down: DEC BX
JNZ UP
LOOP BACK
HLT
CODE ENDS
END
UNIT III
8086 Interfacing
MEMORY AND I/O INTERFACING
I/O Interface
Any application of a microprocessor system requires the transfer of data between
microprocessor and external environment and also with in the microprocessor. This is known as Input/Output. There
are three different ways that the data transfer can take place. They are
Memory interfacing
Memory is an integral part of a microcomputer system. There
are two main types of
memory.
(i) Read only memory (ROM): As the name indicates this memory is available only for
reading purpose. The various types available under this category are PROM, EPROM,
EEPROM which contain system software and permanent system data.
(ii) Random Access memory (RAM): This is also known as Read Write Memory. It is a volatile
memory. RAM contains temporary data and software programs generally for different
applications.
While executing particular task it is necessary to access memory to get instruction codes
and data stored in memory. Microprocessor initiates the necessary signals when read or write
operation is to be performed. Memory device also requires some signals to perform read and write
operations using various registers. To do the above job it is necessary to have a device and a circuit,
which performs this task is known as interfacing device and as this is involved with memory it-is known
as memory interfacing device. The basic concepts of memory interfacing involve three different tasks.
The microprocessor should be able to read from or write into the specified register. To do this it must
be able to select the required chip, identify the required register and it must enable the appropriate
buffers.
Any memory device must contain address lines and Input, output lines, selection input, control
input to perform read or write operation. All memory devices have address inputs that select memory
location with in the memory device. These lines are labeled as AO AN. The number of address lines
indicates the total memory capacity of the memory device. A 1K memory requires 10 address lines A0-
A9. Similarly a 1MB requires 20 lines A0-A19 (in the case of 8086). The memory devices may have
separate I/O lines or a common set of bidirectional I/O lines. Using these lines data can be transferred
in either direction. Whenever output buffer is activated the operation is read whenever input buffers are
activated the operation is write. These lines are labelled as I/O,......... I/On or DO Dn. The size of a
memory location is dependent upon the number of data bits. If the number of data lines are eight D 0 -
D7 then 8 bits or 1 byte of data can be stored in each location. Similarly if numbers of data bits are 16
(D0 - D15) then the memory size is 2 bytes. For example 2K x 8 indicates there are 2048 memory
locations and each memory location can store 8 bits of data.
Memory devices may contain one or more inputs which areused to select the memory
device or to enable the memory device. This pin is denoted by CS (Chip select) or CE (Chip enable).
When this pin is at logic '0' then only the memory device performs a read or a write operation. If this
pin is at logic ‘1’ the memory chip is disabled. If there are more than one CS input then all these pins
must be activated to perform read or write operation.
All memory devices will have one or more control inputs. When ROM is used we
find OE output enable pin which allows data to flow out of the output data pins. To perform this task
both CS and OE must be active. A RAM contains one or two control inputs.
They are R / W or RD and WR . If there is only one input R/ W then it performs read
operation when R/ W pin is at logic 1. If it is at logic 0 it performs write operation. Note that
this ispossible only when CS is also active.
n address lines, then it is able to address at the most N locations of memory, where 2n = N. However, if
out of N locations only P memory locations are to be interfaced, then the least significant p address
lines out of the available n lines can be directly connected from the microprocessor to the memory chip
while the remaining (n-p) higher order address lines may be used for address decoding (as inputs to
the chip selection logic). The memory address depends upon the hardware circuit used for decoding
the chip select ( CS ). The output of the decoding circuit is connected with the CS pin of the memory
chip. 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
[Link] the 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. CS of memory is derived
from theO/P of the decoding circuit.
As a good and efficient interfacing practice, the address map of the system should be
continuous as far as possible, i.e. there should be no windows in the map. A memory location
should have a single address corresponding to it, i.e. absolute decoding should be preferred,
and minimum hardware should be used for decoding. In a number of cases, linear decoding
may be used to minimise the required [Link] us now consider a few example problems
on memory interfacing with 8086.
PIO 8255:
The two groups of I/O pins are named as Group A and Group B. Each of thesetwo
groups contains a subgroup of eight I/O lines called as 8-bit port and anothersubgroup of
four lines or a 4-bit port. Thus Group A contains an 8-bit port Aalong with a 4-bit port C
upper.
The port A lines are identified by symbols PA0-PA7 while the port C lines are
identified as PC4-PC7 similarly. Group B contains an 8-bit port B, containing lines PB0-
PB7 and a 4-bit port C with lower bits PC0-PC3. The port C upper and port C lower can be
used in combination as an 8-bit port C. Both the port Cs is assigned the same address.
Thus one may have either three 8-bit I/O ports or two 8-bit and two 4-bit I/O ports from
8255. All of these ports can function independently either as input or as output ports.
This can be achieved by programming the bits of an internal register of 8255 called as
control word register (CWR). The internal block diagram and the pin configuration of
8255 are shown in figs.
The 8-bit data bus buffer is controlled by the read/write control logic. The read/write
control logic manages all of the internal and external transfer of both data and control
words. RD, WR, A1, A0 and RESET are the inputs, provided by the microprocessor to
READ/WRITE control logic of 8255. The 8-bit, 3-state bidirectional buffer is used to
interface the 8255 internal data bus with the external system data bus. This buffer
receives or transmits data upon the execution of input or output instructions by the
microprocessor. The control words or status information is also transferred through the
buffer.
Pin Diagram of 8255A
The port A lines are identified by symbols PA0-PA7 while the port C lines are
Identified as PC4-PC7. Similarly, Group B contains an 8-bit port B, containing
lines PB0-PB7 and a 4-bit port C with lower bits PC0- PC3. The port C upper
and port C lower can be used in combination as an 8-bit port C.
Both the port C is assigned the same address. Thus one may have
either three 8-bit I/O ports or two 8-bit and two 4-bit ports from 8255. All of
these ports can function independently either as input or as output ports. This
can be achieved by programming the bits of an internal register of 8255 called as
control word register (CWR).
The 8-bit data bus buffer is controlled by the read/write control logic. The
read/write control logic manages all of the internal and external transfers of
both data and control words.
RD,WR, A1, A0 and RESET are the inputs provided by the microprocessor to the
READ/ WRITE control logic of 8255. The 8-bit, 3-state bidirectional buffer is used to
interface the 8255 internal data bus with the external system data bus.
This buffer receives or transmits data upon the execution of input or output
instructions by the microprocessor. The control words or status information is also
transferred through the buffer.
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 mode1 or mode2.
PC3-PC0: These are the lower port C lines; other details are the same as PC7-PC4
lines.
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.
D0-D7: These are the data bus lines those carry data or control word to/from the
microprocessor.
RESET:Logic high on this line clears the control word register of 8255. All ports are
set as input ports by default after reset.
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.
Modes of Operation of 8255
These are two basic modes of operation of 8255. I/O mode and Bit Set-Reset mode
(BSR).
In I/O mode, the 8255 ports work as programmable I/O ports, while in BSR mode only
port C (PC0-PC7) can be used to set or reset its individual port bits.
Under the I/O mode of operation, further there are three modes of operation of 8255,
so as to support different types of applications, mode 0, mode 1 and mode 2.
BSR Mode: In this mode any of the 8-bits of port C can be set or reset depending on D0
of the control word. The bit to be set or reset is selected by bit select flags D3, D2 and D1
of the CWR as given in table.
I/O Modes:
a) Mode 0 (Basic I/O mode): This mode is also called as basic input/output Mode. This
mode provides simple input and output capabilities using each of the three ports. Data
can be simply read from and written to the input and output ports respectively, after
appropriate initialization.
The salient features of this mode are as listed below:
1. Two 8-bit ports (port A and port B) and two 4-bit ports (port C upper and lower)
are available. The two 4-bit ports can be combined used as a third 8-bit port.
2. Any port can be used as an input or output port.
3. Output ports are latched. Input ports are not latched.
4. A maximum of four ports are available so that overall 16 I/O configurations
arepossible.
1. Two groups – group A and group B are available for strobed data transfer.
2. Each group contains one 8-bit data I/O port and one 4-bit control/data port.
3. The 8-bit data port can be either used as input and output port. The inputs
andoutputs both are latched.
4. Out of 8-bit port C, PC0-PC2 are used to generate control signals for port B
andPC3-PC5 are used to generate control signals for port A. the lines PC6, PC7
may be used as independent data lines.
The control signals for both the groups in input and output modes are explained as
follows:
• STB (Strobeinput) – If this lines falls to logic low level, the data available at 8-
bit input port is loaded into input latches.
• IBF (Input buffer full) – If this signal rises to logic 1, it indicates that data
hasbeen loaded into latches, i.e. it works as an acknowledgement. IBF is set
by a lowon STB and is reset by the rising edge of RD input.
• INTR (Interruptrequest) – This active high output signal can be used
tointerrupt the CPU whenever an input device requests the service. INTR is
set by ahigh STBpin and a high at IBF pin. INTE is an internal flag that can be
controlledby the bit set/reset mode of either PC4 (INTEA) or PC2 (INTEB) as
shown in fig.
• INTR is reset by a falling edge of RD input. Thus an external input device can
berequest the service of the processor by putting the data on the bus and
sending thestrobe signal.
• OBF (Output buffer full) – This status signal, whenever falls to low,
indicatesthat CPU has written data to the specified output port. The OBF flip-
flop will beset by a rising edge of WR signal and reset by a low going edge at
the ACKinput.
• ACK (Acknowledgeinput) – ACK signal acts as an acknowledgement to begiven
by an output device. ACK signal, whenever low, informs the CPU that thedata
transferred by the CPU to the output device through the port is received
bythe output device.
• INTR (Interruptrequest) – Thus an output signal that can be used to
interruptthe CPU when an output device acknowledges the data received
from the [Link] is set when ACK, OBF and INTE are 1. It is reset by a
Falling edge on WR input. The INTEA and INTEB flags are controlled by the
bitset-reset mode ofPC6 and PC2 respectively.
c) Mode 2 (Strobed bidirectional I/O): This mode of operation of 8255 is also called as
strobed bidirectional I/O. This mode of operation provides 8255 with additional features for
communicating with a peripheral device on an 8-bit data bus. Handshaking signals are
provided to maintain proper data flow and synchronization between the data transmitter
and receiver. The interrupt generation and other functions are similar to mode 1.
In this mode, 8255 is a bidirectional 8-bit port with handshake signals. The Rdand WR signals
decide whether the 8255 is going to operate as an input port or output port.
INTR – (Interrupt request) As in mode 1, this control signal is active high and
isused to interrupt the microprocessor to ask for transfer of the next data
byteto/from it. This signal is used for input (read) as well as output (write)
operations.
Control Signals for Output operations:
OBF (Output buffer full) – This signal, when falls to low level, indicates that
theCPU has written data to port A.
ACK (Acknowledge) This control input, when falls to logic low level,
Acknowledges that the previous data byte is received by the destination and
nextbyte may be sent by the processor. This signal enables the internal tristate
buffersto send the next data byte on port A.
INTE1 ( A flag associated with OBF ) This can be controlled by bit set/resetmode
with PC6.
STB (Strobe input)a low on this line is used to strobe in the data into the
inputLatches of 8255.
IBF (Input buffer full) when the data is loaded into input buffer, this signal risesto
logic „1‟. This can be used as an acknowledge that the data has been receivedby
the receiver.
The waveforms in fig show the operation in Mode 2 for output as well as
inputport.
Note: WR must occur before ACK and STB must be activated before RD.
The following fig shows a schematic diagram containing an 8-bit
bidirectionalport, 5-bit control port and the relation of INTR with the control
pins. Port B caneither be set to Mode 0 or 1 with port A( Group A ) is in Mode
2.
Mode 2 is not available for port B. The following fig shows the control word.
The INTR goes high only if IBF, INTE2, STB and RD go high or OBF,
INTE1, ACK and WR go high. The port C can be read to know the status of
theperipheral device, in terms of the control signals, using the normal
I/Oinstructions.
Interfacing switches and LEDS
LED ( light emitting diode):
Light emitting diodes is the most commonly used comp[onents, usually for displaying pins
digital states. Typical uses of LEDs include alarm devices, timers and confirmation of user input
such as a mouse click or keystroke.
INTERFACING LED:
fig.1 shows how to interface the LED to microprocessor. As you can see the anode is connected
through a resister to GND & the cathide is connected to the microprocessor pin. So when the port pin is
HIGH the LED is OFF 7 when the port pin is LOW the LED is turned ON.
Display Interface
Interfacing multiplexed 7-segment display
Software and Hardware interrupt applications
1. Hardware Interrupt :
Hardware Interrupt is caused by some hardware device such as request to start an I/O, a hardware failure or
something similar. Hardware interrupts were introduced as a way to avoid wasting the processor’s valuable time in
polling loops, waiting for external events.
For example, when an I/O operation is completed such as reading some data into the computer from a tape drive.
2. Software Interrupt :
Software Interrupt is invoked by the use of INT instruction. This event immediately stops execution of the program
and passes execution over to the INT handler. The INT handler is usually a part of the operating system and
determines the action to be taken. It occurs when an application program terminates or requests certain services from
the operating system.
For example, output to the screen, execute file etc.
Applications of interrupts:
1. Applications of interrupts include the following: system timers, disk I/O, power-off signals, and traps.
2. Other interrupts exist to transfer data bytes using UARTs or Ethernet; sense key-presses; or anything else the
equipment must do.
3. Another typical use is to generate periodic interrupts by dividing the output of a crystal oscillator and having an
interrupt handler count the interrupts in order for a processor to keep time.
4. These periodic interrupts are often used by the OS's task scheduler to reschedule the priorities of running
processes.
5. Some older computers generated periodic interrupts from the power line frequency because it was controlled by
the utilities to eliminate long-term drift of electric clocks.
6. For example, a disk interrupt signals the completion of a data transfer from or to the disk peripheral; a process
waiting to read or write a file starts up again.
7. As another example, a power-off interrupt predicts or requests a loss of power, allowing the computer
equipment to perform an orderly shut-down.
8. Also, interrupts are used in type ahead features for buffering events like keystrokes.
Intel 8251 USART architecture and interfacing
USART stands for Universal Synchronous and Asynchronous Receiver Transmitter.
8251 universal synchronous asynchronous receiver transmitter (USART) acts as a mediator between
microprocessor and peripheral to transmit serial data into parallel form and vice versa.
1. It takes data serially from peripheral (outside devices) and converts into parallel data.
2. After converting the data into parallel form, it transmits it to the CPU.
3. Similarly, it receives parallel data from microprocessor and converts it into serial form.
4. After converting data into serial form, it transmits it to outside device (peripheral)
.
Block Diagram/ Architecture of 8251 USART –
• The chip select for I/O mapped devices are generated by using a 3-to-8 decoder. • The address lines A5, A6
and A7 are decoded to generate eight chip select signals (IOCS-0 to IOCS-7) and in this, the chip select
signal IOCS-2 is used to select 825lA. • The address line A0 and the control signal M/IO(low) are used as
enable for decoder. • The line A1 of 8086 is connected to C/D(low) of 8251A to provide the internal
addresses. • The lines D0 – D7 connected to D0 – D7 of the processor to achieve parallel data transfer. • The
RESET and clock signals are supplied by 8284 clock generator. Here the processor clock is directly
connected to 8251A. This clock controls the parallel data transf er between the processor and 825lA. • 8251A
in I/O mapped in the system is shown in the figure.
⚫ The peripheral clock (PCLK) supplied by 8284, is divided by suitable clock dividers like programmable
timer 8254 and then used as clock for serial transmission and reception.
⚫ In 8251A the transmission and reception baud rates can be different or same. • The TTL logic levels of
the serial data lines and the control signals necessary for serial transmission and reception are converted
to RS232 logic levels using MAX232 and then terminated on a standard 9-pin [Link] connector. • The
device, which requires serial communication with processor, can be connected to this 9-pin D-type
connector using 9-core cable. • The signals TxEMPTY, TxRDY and RxRDY can be used as interrupt
signals to initiate interrupt driven data transfer scheme between processor and 8251 A. • The I/O
addresses allotted to the internal devices of 8251A are listed in table.
Intel 8237a DMA controller
Suppose any device which is connected to input-output port wants to transfer data to memory, first of all it will send
input-output port address and control signal, input-output read to input-output port, then it will send memory address
and memory write signal to memory where data has to be transferred. In normal input-output technique the processor
becomes busy in checking whether any input-output operation is completed or not for next input-output operation,
therefore this technique is slow.
This problem of slow data transfer between input-output port and memory or between two memory is avoided by
implementing Direct Memory Access (DMA) technique. This is faster as the microprocessor/computer is bypassed
and the control of address bus and data bus is given to the DMA controller.
Suppose a floppy drive that is connected at input-output port wants to transfer data to memory, the following steps
are performed:
• Step-1: First of all the floppy drive will send a DMA request (DREQ) to the DMAC, it means the floppy
drive wants its DMA service.
• Step-2: Now the DMAC will send a HOLD signal to the CPU.
• Step-3: After accepting the DMA service request from the DMAC, the CPU will send hold acknowledgment
(HLDA) to the DMAC, it means the microprocessor has released control of the address bus the data bus to DMAC
and the microprocessor/computer is bypassed during DMA service.
• Step-4: Now the DMAC will send one acknowledgement (DACL) to the floppy drive which is connected at
the input-output port. It means the DMAC tells the floppy drive be ready for its DMA service.
• Step-5: Now with the help of input-output read and memory write signal the data is transferred from the
floppy drive to the memory.
Modes of DMAC:
1. Single Mode – In this only one channel is used, means only a single DMAC is connected to the bus
system.
2. Cascade Mode – In this multiple channels are used, we can further cascade more number of DMACs.
The method that is used to transfer information between internal storage and external I/O devices is known as I/O
interface. The CPU is interfaced using special communication links by the peripherals connected to any computer
system. These communication links are used to resolve the differences between CPU and peripheral. There exists
special hardware components between CPU and peripherals to supervise and synchronize all the input and output
transfers that are called interface units.
Mode of Transfer:
The binary information that is received from an external device is usually stored in the memory unit. The information
that is transferred from the CPU to the external device is originated from the memory unit. CPU merely processes the
information but the source and target is always the memory unit. Data transfer between CPU and the I/O devices may
be done in different modes.
Data transfer to and from the peripherals may be done in any of the three possible ways
1. Programmed I/O.
2. Interrupt- initiated I/O.
3. Direct memory access( DMA).
Now let’s discuss each mode one by one.
1. Programmed I/O: It is due to the result of the I/O instructions that are written in the computer program.
Each data item transfer is initiated by an instruction in the program. Usually the transfer is from a CPU register
and memory. In this case it requires constant monitoring by the CPU of the peripheral devices.
Example of Programmed I/O: In this case, the I/O device does not have direct access to the memory unit. A
transfer from I/O device to memory requires the execution of several instructions by the CPU, including an input
instruction to transfer the data from device to the CPU and store instruction to transfer the data from CPU to memory.
In programmed I/O, the CPU stays in the program loop until the I/O unit indicates that it is ready for data transfer.
This is a time consuming process since it needlessly keeps the CPU busy. This situation can be avoided by using an
interrupt facility. This is discussed below.
2. Interrupt- initiated I/O: Since in the above case we saw the CPU is kept busy unnecessarily. This situation
can very well be avoided by using an interrupt driven method for data transfer. By using interrupt facility and
special commands to inform the interface to issue an interrupt request signal whenever data is available from any
device. In the meantime the CPU can proceed for any other program execution. The interface meanwhile keeps
monitoring the device. Whenever it is determined that the device is ready for data transfer it initiates an interrupt
request signal to the computer. Upon detection of an external interrupt signal the CPU stops momentarily the task
that it was already performing, branches to the service program to process the I/O transfer, and then return to the
task it was originally performing.
Note: Both the methods programmed I/O and Interrupt-driven I/O require the active intervention of the
processor to transfer data between memory and the I/O module, and any data transfer must transverse
a path through the processor. Thus both these forms of I/O suffer from two inherent drawbacks.
• The I/O transfer rate is limited by the speed with which the processor can test and service a
device.
• The processor is tied up in managing an I/O transfer; a number of instructions must be executed
for each I/O transfer.
3. Direct Memory Access: The data transfer between a fast storage media such as magnetic disk and memory
unit is limited by the speed of the CPU. Thus we can allow the peripherals directly communicate with each other
using the memory buses, removing the intervention of the CPU. This type of data transfer technique is known as
DMA or direct memory access. During DMA the CPU is idle and it has no control over the memory buses. The
DMA controller takes over the buses to manage the transfer directly between the I/O devices and the memory unit.
Bus Request : It is used by the DMA controller to request the CPU to relinquish the control of the buses.
Bus Grant : It is activated by the CPU to Inform the external DMA controller that the buses are in high impedance
state and the requesting DMA can take control of the buses. Once the DMA has taken the control of the buses it
transfers the data. This transfer can take place in many ways.
Types of DMA transfer using DMA controller:
Burst Transfer :
DMA returns the bus after complete data transfer. A register is used as a byte count,
being decremented for each byte transfer, and upon the byte count reaching zero, the DMAC will
release the bus. When the DMAC operates in burst mode, the CPU is halted for the duration of the data
transfer.
Steps involved are:
1. Bus grant request time.
2. Transfer the entire block of data at transfer rate of device because the device is usually slow than the
speed at which the data can be transferred to CPU.
3. Release the control of the bus back to CPU
So, total time taken to transfer the N bytes
= Bus grant request time + (N) * (memory transfer rate) + Bus release control time.
Where,
X µsec =data transfer time or preparation time (words/block)
Y µsec =memory cycle time or cycle time or transfer time (words/block)
% CPU idle (Blocked)=(Y/X+Y)*100
% CPU Busy=(X/X+Y)*100
Cyclic Stealing :
An alternative method in which DMA controller transfers one word at a time after which it must return the control of
the buses to the CPU. The CPU delays its operation only for one memory cycle to allow the direct memory I/O
transfer to “steal” one memory cycle.
Steps Involved are:
1. Buffer the byte into the buffer
2. Inform the CPU that the device has 1 byte to transfer (i.e. bus grant request)
3. Transfer the byte (at system bus speed)
4. Release the control of the bus back to CPU.
Before moving on transfer next byte of data, device performs step 1 again so that bus isn’t tied up and
the transfer won’t depend upon the transfer rate of device.
So, for 1 byte of transfer of data, time taken by using cycle stealing mode (T).
= time required for bus grant + 1 bus cycle to transfer data + time required to release the bus, it will be
NxT
In cycle stealing mode we always follow pipelining concept that when one byte is getting transferred then Device is
parallel preparing the next byte. “The fraction of CPU time to the data transfer time” if asked then cycle stealing
mode is used.
Where,
X µsec =data transfer time or preparation time
(words/block)
Y µsec =memory cycle time or cycle time or transfer
time (words/block)
% CPU idle (Blocked) =(Y/X)*100
% CPU busy=(X/Y)*100
Interleaved mode: In this technique , the DMA controller takes over the system bus when the microprocessor is not
using [Link] alternate half cycle i.e. half cycle DMA + half cycle processor.
The DMA mode of data transfer reduces CPU’s overhead in handling I/O operations. It also allows parallelism in
CPU and I/O operations. Such parallelism is necessary to avoid wastage of valuable CPU time while handling I/O
devices whose speeds are much slower as compared to CPU. The concept of DMA operation can be extended to
relieve the CPU further from getting involved with the execution of I/O operations. This gives rises to the
development of special purpose processor called Input-Output Processor (IOP) or IO channel.
The Input Output Processor (IOP) is just like a CPU that handles the details of I/O operations. It is more equipped
with facilities than those are available in typical DMA controller. The IOP can fetch and execute its own instructions
that are specifically designed to characterize I/O transfers. In addition to the I/O – related tasks, it can perform other
processing tasks like arithmetic, logic, branching and code translation. The main memory unit takes the pivotal role.
It communicates with processor by the means of DMA.
The block diagram –
The Input Output Processor is a specialized processor which loads and stores data into memory along with the
execution of I/O instructions. It acts as an interface between system and devices. It involves a sequence of events to
executing I/O operations and then store the results into the memory.
Advantages –
• The I/O devices can directly access the main memory without the intervention by the processor in I/O
processor based systems.
It is used to address the problems that are arises in Direct memory access method.
Motion step A B C D
1 1 0 0 0
2 0 1 0 0
Clock wise 3 0 0 1 0
4 0 0 0 1
5 1 0 0 0
1 1 0 0 0
2 0 0 0 1
Anticlock
3 0 0 1 0
wise
4 0 1 0 0
5 1 0 0 0
Motion step A B C D
1 0 0 1 1
2 0 1 1 0
Clock wise 3 1 1 0 0
4 1 0 0 1
5 0 0 1 1
1 0 0 1 1
2 1 0 0 1
Anticlock
3 1 1 0 0
wise
4 0 1 1 0
5 0 0 0 0
Interfacing Analog to Digital Data Converters:
In most of the cases, the PIO 8255 is used for interfacing the analog to digital
converters with microprocessor.
We have already studied 8255 interfacing with 8086 as an I/O port, in previous section.
This section we will only emphasize the interfacing techniques of analog to digital
converters with 8255.
The analog to digital converters is treated as an input device by the microprocessor
that sends an initializing signal to the ADC to start the analogy to digital data
conversation process. The start of conversation signal is a pulse of a specific duration.
19.1 The analog to digital converter chips 0808 and 0809 are 8-bit CMOS,
successive approximation converters. This technique is one of the fast
techniques for analog to digital conversion. The conversion delay is 100µs at a
clock frequency of 640 KHz, which is quite low as compared to other
converters. These converters do not need any external zero or full scale
adjustments as they are already taken care of by internal circuits.
19.2 These converters internally have a 3:8 analog multiplexer so that at a
time eight different analog conversion by using address lines - ADD A, ADD
B, ADD C, as shown. Using these address inputs, multichannel data
acquisition system can be designed using a single ADC. The CPU may drive
these lines using output port lines in case of multichannel applications. In
case of single input applications, these may be hardwired to select the
proper input.
19.3 There are unipolar analog to digital converters, i.e. they are able to convert
only positive analog input voltage to their digital equivalent. These chips do
not contain any internal sample and hold circuit.
19.4 If one needs a sample and hold circuit for the conversion of fast signal into
equivalent digital quantities, it has to be externally connected at each of the
analog inputs.
Fig (1) and Fig (2) show the block diagrams and pin diagrams for ADC 0808/0809.
Table.1
Address lines
Analog I/P selected
C B A
I/P 0 0 0 0
I/P 1 0 0 1
I/P 2 0 1 0
I/P 3 0 1 1
I/P 4 1 0 0
I/P 5 1 0 1
I/P 6 1 1 0
I/P 7 1 1 1
Fig.1 Block Diagram of ADC 0808/0809
Table.2
The digital to analog converters convert binary numbers into their analog
equivalent voltages. The DAC find applications in areas like digitally controlled gains,
motor speed controls, programmable gain amplifiers, etc.
The supply range extends from +5V to +15V , while Vref may be anywhere
between -10V to +10V. The maximum analog output voltage will be +10V,
when all the digital inputs are at logic high state. Usually a Zener is connected
between OUT1 and OUT2 to save the DAC from negative transients.
An operational amplifier is used as a current to voltage converter at the output
of AD 7523 to convert the current output of AD7523 to a proportional output
voltage.
111
It also offers additional drive capability to the DAC
output. An external feedback resistor acts to control
the gain. One may not connect any external feedback
resistor, if no gain control is required.
It is also known as a priority interrupt controller and was designed by Intel to increase the
interrupt handling ability of the microprocessor. An 8259 PIC never services an interrupt; it
simply forwards the interrupt to the processor for the execution of interrupt service routine.
We know whenever an interrupt occurs then the microprocessor suspends the current program
and switches to the Interrupt Service Routine (ISR).
We know 8085 has 5 interrupts, which are: Trap, RST7.5, RST6.5, RST5.5 and INTR.
Among all these, only INTR is a non-vectored type of interrupt, rest are vectored interrupts.
We know vectored interrupts are those interrupts whose ISR address is known to the
processor. Or we can say in case of vectored interrupts, the processor holds the address of the
memory location where ISR is stored.
But in case of non-vectored interrupts, the processor has to reach the ISR but it does not hold
the address of ISR. So, in this case, the interrupt generating device provides the ISR address
to the microprocessor.
An 8085 has 5 major interrupts for which a fixed number of lines are present in the chip. But
there are many devices connected to a processor. So, for such a case the processor must have
more number of lines to handle several interrupts.
But it is not practically possible to increase the number of lines each time with the increase in
the number of interrupts.
So, to overcome this problem 8259 PIC chip is used. 8259 allows the combining of multiple
interrupts and providing them to the processor based on priority through a common line.
As we have already discussed that the processor holds the address of ISR in case of vectored
interrupts. So, it is not possible to combine a non-vectored interrupt with a vectored one.
Therefore, 8259 is used to combine various interrupts which are non-vectored in nature.
Also, suppose in some way or the other, two devices generate interrupt simultaneously
through a common line without the involvement of 8259.
So, the processor gets two INTR signals at the same time but how does the processor get to
know that from where the interrupt is generating and where to send the INTA in order to have
the ISR address.
This shows the necessity of 8259. The programmable interrupt controller tells the
microprocessor about the interrupt. Basically the external devices initially interrupt the 8259
and further the 8259 interrupts the microprocessor.
INTRODUCTION TO MICROCONTROLLERS
8051 MICROCONTROLLER:
The Intel 8051 microcontroller is one of the most popular general purpose microcontrollers
in use today. The success of the Intel 8051 spawned a number of clones which are collectively
referred to as the MCS-51 family of microcontrollers, which includes chips from vendors such
as Atmel, Philips, Infineon, and Texas Instruments
The Intel 8051 is an 8-bit microcontroller which means that most available operations are
limited to 8 bits. There are 3 basic "sizes" of the 8051: Short, Standard, and Extended. The Short
and Standard chips are often available in DIP (dual in-line package) form, but the Extended 8051
models often have a different form factor, and are not "drop-in compatible". All these things are
called 8051 because they can all be programmed using 8051 assembly language, and they all
share certain features (although the different models all have their own special features).
Some of the features that have made the 8051 popular are:
8051 models may also have a number of special, model-specific features, such as UARTs,
ADC, Op-Amps, etc...
Typical applications:
8051 chips are used in a wide variety of control systems, telecom applications, robotics as
well as in the automotive industry. By some estimation, 8051 family chips make up over 50%
of the embedded chip market.
Basic Pins:
Pin 9: PIN 9 is the reset pin which is used reset the microcontroller‘s internal registers and
ports upon starting up. (Pin should be held high for 2 machine cycles.)
Pins 18 & 19: The 8051 has a built-in oscillator amplifier hence we need to only connect a
crystal at these pins to provide clock pulses to the circuit.
Pin 40 and 20: Pins 40 and 20 are VCC and ground respectively. The 8051 chip needs +5V
500mA to function properly, although there are lower powered versions like the Atmel 2051
which is a scaled down version of the 8051 which runs on +3V.
Pins 29, 30 & 31: As described in the features of the 8051, this chip contains a built-in flash memory. In order
to program this we need to supply a voltage of +12V at pin 31. If external memory is connected then PIN 31,
also called EA/VPP, should be connected to ground to indicatethe presence of external memory. PIN 30 is
called ALE (address latch enable), which is used when multiple memory chips are connected to the controller
and only one of them needs to be selected. We will deal with this in depth in the later chapters. PIN 29 is
called PSEN. This is "program store enable". In order to use the external memory it is required to provide the
low voltage (0) on both PSEN and EA pins.
Ports:
There are 4 8-bit ports: P0, P1, P2 and P3.
PORT P1 (Pins 1 to 8): The port P1 is a general purpose input/output port which can be used
for a variety of interfacing tasks. The other ports P0, P2 and P3 have dual roles or
additional functions associated with them based upon the context of their usage.
PORT P3 (Pins 10 to 17): PORT P3 acts as a normal IO port, but Port P3 has additional
functions such as, serial transmit and receive pins, 2 external interrupt pins, 2 external
counter inputs, read and write pins for memory access.
PORT P2 (pins 21 to 28): PORT P2 can also be used as a general purpose 8 bit port when no
external memory is present, but if external memory access is required then PORT P2 will
act as an address bus in conjunction with PORT P0 to access external memory. PORT P2
acts as A8-A15, as can be seen from fig 1.1
PORT P0 (pins 32 to 39) PORT P0 can be used as a general purpose 8 bit port when no
external memory is present, but if external memory access is required then PORT P0 acts
as a multiplexed address and data bus that can be used to access external memory in
conjunction with PORT P2. P0 acts as AD0-AD7, as can be seen from fig 1.1
Oscillator Circuits
The 8051 requires the existence of an external oscillator circuit. The oscillator circuit usually
runs around 12MHz, although the 8051 (depending on which specific model) is capable of
running at a maximum of 40MHz. Each machine cycle in the 8051 is 12 clock cycles,
giving an effective cycle rate at 1MHz (for a 12MHz clock) to 3.33MHz (for the
maximum 40MHz clock).
Internal Architecture
Data and Program Memory
The 8051 Microprocessor can be programmed in PL/M, 8051 Assembly, C and a number of
other high-level languages. Many compilers even have support for compiling C++ for an 8051.
Program memory in the 8051 is read-only, while the data memory is considered to be
read/write accessible. When stored on EEPROM or Flash, the program memory can be
rewritten when the microcontroller is in the special programmer circuit.
Direct Memory
The 8051 has 256 bytes of internal addressable RAM, although only the first 128 bytes are
available for general use by the programmer. The first 128 bytes of RAM (from 0x00 to 0x7F)
are called the Direct Memory, and can be used to store data.
The 8051 has 4 selectable banks of 8 addressable 8-bit registers, R0 to R7. This means that there are
essentially 32 available general purpose registers, although only 8 (one bank) can be directly
accessed at a time. To access the other banks, we need to change the current bank number in the flag
status register.
A and B Registers
The A register is located in the SFR memory location 0xE0. The A register works in a similar
fashion to the AX register of x86 processors. The A register is called the accumulator, and by
default it receives the result of all arithmetic operations. The B register is used in a similar manner,
except that it can receive the extended answers from the multiply and divide operations. When not
being used for multiplication and Division, the B register is available as an extra general-purpose
register.
ADDRESSING MODES OF 8051
Various methods of accessing the data are called addressing
1. Immediate addressing.
2. Register addressing.
3. Direct addressing.
4. Indirect addressing.
5. Relative addressing.
6. Absolute addressing.
7. Long addressing.
8. Indexed addressing.
9. Bit inherent addressing.
10. Bit direct addressing.
1. Immediate addressing.
In this addressing mode the data is provided as a part of instruction itself. In other words
data immediately follows the instruction.
Eg. MOV A,#30H
ADD A, #83 # Symbol indicates the data is immediate.
2. Register addressing.
In this addressing mode the register will hold the data. One of the eight general
registers(R0 to R7) can be used and specified as the operand.
Eg. MOV
A,R0
ADD
A,R6
R0 – R7 will be selected from the current selection of register bank. The default register bank will be bank 0.
3. Direct addressing
There are two ways to access the internal memory. Using direct address and indirect address. Using direct
addressing mode we can not only address the internal memory but SFRs also. In direct addressing, an 8 bit internal
data memory address is specified as part of the instruction and hence, it can specify the address only in the range of
00H to FFH. In this addressing mode, data is obtained directly from the memory.
Eg. MOV
A,60h
ADD
A,30h
4. Indirect addressing
The indirect addressing mode uses a register to hold the actual address that will be used in data movement.
Registers R0 and R1 and DPTR are the only registers that can be used as data pointers. Indirect addressing cannot be
used to refer to SFR registers. Both R0 and R1 can hold 8 bit address and DPTR can hold16 bit address.
Eg. MOV A,@R0
ADD A,@R1
MOVX
A,@DPTR
5. Indexed addressing.
In indexed addressing, either the program counter (PC), or the data pointer
(DTPR)—is used to hold the base address, and the A is used to hold the offset address. Adding
the value of the base address to the value of the offset address forms the effective address.
Indexed addressing is used with JMP or MOVC instructions. Look up tables are easily
implemented with the help of index addressing.
Eg. MOVC A, @A+DPTR // copies the contents of memory location pointed by the sum of the accumulator
A and the DPTR into accumulator A.
MOVC A, @A+PC // copies the contents of memory location pointed by the sum of the
accumulator A and the program counter into accumulator A.
6. Relative Addressing.
Relative addressing is used only with conditional jump instructions. The relative address,
(offset), is an 8 bit signed number, which is automatically added to the PC to make the address of
the next instruction. The 8 bit signed offset value gives an address range of +127 to —128
[Link] jump destination is usually specified using a label and the assembler calculates the
jump offset accordingly. The advantage of relative addressing is that the program code is easy to
relocate and the address is relative to position in the memory.
Eg. SJMP
LOOP1JC
BACK
7. Absolute addressing
Absolute addressing is used only by the AJMP (Absolute Jump) and ACALL (Absolute Call)
instructions. These are 2 bytes instructions. The absolute addressing mode specifies the lowest 11bit
of the memory address as part of the instruction. The upper 5 bit of the destination address are the
upper 5 bit of the current program counter. Hence, absolute addressing allows branching onlywithin
the current 2 Kbyte page of the program memory.
8. Long Addressing
The long addressing mode is used with the instructions LJMP and LCALL. These are 3 byte
instructions. The address specifies a full 16 bit destination address so that a jump or a call can be
made to a location within a 64 Kbyte code memory space.
Eg. LJMP FINISH
LCALL
DELAY
2. 8051 Instructions
The instructions of 8051 can be broadly classified under the following headings.
1. Data transfer instructions
2. Arithmetic instructions
3. Logical instructions
4. Branch instructions
5. Subroutine instructions
6. Bit manipulation instructions
Data transfer instructions.
In this group, the instructions perform data transfer operations of the following types.
a. Move the contents of a register Rn to A
i. MOV A,R2
ii. MOV A,R7
b. Move the contents of a register A to Rn
i. MOV R4,A
ii. MOV R1,A
c. Move an immediate 8 bit data to register A or to Rn or to a memory location(direct or
indirect)
i. MOV A, #45H iv. MOV @R0, #0E8H
ii. MOV R6, #51H v. MOV DPTR, #0F5A2H
iii. MOV 30H, #44H vi. MOV DPTR, #5467H
d. Move the contents of a memory location to A or A to a memory location using direct and
indirect addressing
i. MOV A, 65H iii. MOV 45H, A
ii. MOV A, iv. MOV @R1, A
@R0
e. Move the contents of a memory location to Rn or Rn to a memory location using direct
addressing
i. MOV R3, 65H
ii. MOV 45H, R2
f. Move the contents of memory location to another memory location using direct and
indirect addressing
i. MOV 47H, 65H
ii. MOV 45H, @R0
g. Move the contents of an external memory to A or A to an external memory
i. MOVX A,@R1 iii. MOVX A,@DPTR
ii. MOVX @R0,A iv. MOVX@DPTR,A
h. Move the contents of program memory to A
i. MOVC A, @A+PC
ii. MOVC A, @A+DPTR
FIG. Addressing Using MOV, MOVX and MOVC
The 8051 can perform addition, subtraction. Multiplication and division operations on 8 bit
numbers.
Addition
In this group, we have instructions to
i. Add the contents of A with immediate data with or without carry.
i. ADD A, #45H
ii. ADDC A, #OB4H
ii. Add the contents of A with register Rn with or without carry.
i. ADD A, R5
ii. ADDC A, R2
iii. Add the contents of A with contents of memory with or without carry using direct and
indirect addressing
i. ADD A, 51H
ii. ADDC A, 75H
iii. ADD A, @R1
iv. ADDC A, @R0
Subtraction
In this group, we have instructions to
i. Subtract the contents of A with immediate data with or without carry.
i. SUBB A, #45H
ii. SUBB A, #OB4H
ii. Subtract the contents of A with register Rn with or without carry.
i. SUBB A, R5
ii. SUBB A, R2
iii. Subtract the contents of A with contents of memory with or without carry using direct and
indirect addressing
i. SUBB A, 51H
ii. SUBB A, 75H
iii. SUBB A, @R1
iv. SUBB A, @R0
Multiplication
MUL AB. This instruction multiplies two 8 bit unsigned numbers which are stored in A and B
register. After multiplication the lower byte of the result will be stored in accumulator and higher
byte of result will be stored in B register.
Eg. MOV A,#45H ;[A]=45H
MOV B,#0F5H ;[B]=F5H
MUL AB ;[A] x [B] = 45 x F5 = 4209
;[A]=09H, [B]=42H
Division
DIV AB. This instruction divides the 8 bit unsigned number which is stored in A by the 8 bit
unsigned number which is stored in B register. After division the result will be stored in
accumulator and remainder will be stored in B register.
Eg. MOV A,#45H ;[A]=0E8H
MOV B,#0F5H ;[B]=1BH
DIV AB ;[A] / [B] = E8 /1B = 08 H with remainder 10H
;[A] = 08H, [B]=10H
When two BCD numbers are added, the answer is a non-BCD number. To get the result in BCD, weuse
DA A instruction after the addition. DA A works as follows.
• If lower nibble is greater than 9 or auxiliary carry is 1, 6 is added to lower nibble.
• If upper nibble is greater than 9 or carry is 1, 6 is added to upper nibble.
Eg 1: MOV A,#23H
MOV R1,#55H
ADD A,R1 // [A]=78
DA A // [A]=78 no changes in the accumulator after da a
Eg 2: MOV A,#53H
MOV R1,#58H
ADD A,R1 // [A]=ABh
DA A // [A]=11, C=1 . ANSWER IS 111. Accumulator data is changed after DA A
INC increments the value of source by 1. If the initial value of register is FFh, incrementing the value will
cause it to reset to 0. The Carry Flag is not set when the value "rolls over" from 255 to 0.
In the case of "INC DPTR", the value two-byte unsigned integer value of DPTR is incremented. If the
initial value of DPTR is FFFFh, incrementing the value will cause it to reset to 0.
DEC decrements the value of source by 1. If the initial value of is 0, decrementing the value will cause it
to reset to FFh. The Carry Flag is not set when the value "rolls over" from 0 to FFh.
Logical Instructions
Logical AND
ANL destination, source: ANL does a bitwise "AND" operation between source and destination,
leaving the resulting value in destination. The value in source is not affected. "AND" instruction logically
AND the bits of source and destination.
ANL A,#DATA ANL A,
Rn ANL A,DIRECT ANL
A,@Ri
ANL DIRECT,A ANL DIRECT, #DATA
Logical OR
ORL destination, source: ORL does a bitwise "OR" operation between source and destination,
leaving the resulting value in destination. The value in source is not affected. " OR " instruction
logically OR the bits of source and destination.
ORL A,#DATA ORL A,
Rn ORL A,DIRECT ORL
A,@Ri
ORL DIRECT,A ORL DIRECT, #DATA
Logical Ex-OR
XRL destination, source: XRL does a bitwise "EX-OR" operation between source and
destination, leaving the resulting value in destination. The value in source is not affected. " XRL "
instruction logically EX-OR the bits of source and destination.
XRL A,#DATA XRL A,Rn
XRL A,DIRECT XRL
A,@Ri
XRL DIRECT,A XRL DIRECT, #DATA
Logical NOT
CPL complements operand, leaving the result in operand. If operand is a single bit then the state ofthe
bit will be reversed. If operand is the Accumulator then all the bits in the Accumulator will be reversed.
Rotate Instructions
RR A
This instruction is rotate right the accumulator. Its operation is illustrated below. Each bit is shifted one
location to the right, with bit 0 going to bit 7.
RL A
Rotate left the accumulator. Each bit is shifted one location to the left, with bit 7 going to bit 0
RRC A
Rotate right through the carry. Each bit is shifted one location to the right, with bit 0 going into the carry bit in the
PSW, while the carry was at goes into bit 7
RLC A
Rotate left through the carry. Each bit is shifted one location to the left, with bit 7 going into the carry bit in the
PSW, while the carry goes into bit 0.
Branch (JUMP) Instructions
Relative Jump
Jump that replaces the PC (program counter) content with a new address that is greater than (the
address following the jump instruction by 127 or less) or less than (the address following the
jump by 128 or less) is called a relative jump. Schematically, the relative jump can be shown as
follows: -
00 0000 - 07FF
01 0800 - 0FFF
02 1000 - 17FF
03 1800 - 1FFF
.
.
1E F000 - F7FF
1F F800 - FFFF
It can be seen that the upper 5bits of the program counter (PC) hold the page number and the
lower 11bits of the PC hold the address within that page. Thus, an absolute address is formed by
taking page numbers of the instruction (from the program counter) following the jump and
attaching the specified 11bits to it to form the 16-bit address.
Applications that need to access the entire program memory from 0000H to FFFFH use long
absolute jump. Since the absolute address has to be specified in the op-code, the instruction
length is 3 bytes (except for JMP @ A+DPTR). This jump is not re-locatable.
Example: -
1. The unconditional jump is a jump in which control is transferred unconditionally to the target location.
a. LJMP (long jump). This is a 3-byte instruction. First byte is the op-code and second and third bytes
represent the 16-bit target address which is any memory location from 0000 to FFFFH
eg: LJMP 3000H
b. AJMP: this causes unconditional branch to the indicated address, by loading the 11 bit address to 0 -10
bits of the program counter. The destination must be therefore within the same 2K blocks.
c. SJMP (short jump). This is a 2-byte instruction. First byte is the op-code and second byte is the
relative target address, 00 to FFH (forward +127 and backward -128 bytes from the current PC value).
To calculate the target address of a short jump, the second byte is added to the PC value which is
address of the instruction immediately below the jump.
2. Conditional Jump instructions.
JBC Jump if bit = 1 and clear bit
JNB Jump if bit = 0
JB Jump if bit = 1
JNC Jump if CY = 0
JC Jump if CY = 1
CJNE reg,#data Jump if byte ≠ #data
CJNE A,byte Jump if A ≠ byte
DJNZ Decrement and Jump if A ≠ 0
JNZ Jump if A ≠ 0
JZ Jump if A = 0
Bit level JUMP instructions will check the conditions of the bit and if condition is true, it jumps to theaddress
specified in the instruction. All the bit jumps are relative jumps.
JB bit, rel ; jump if the direct bit is set to the relative address specified. JNB
bit, rel ; jump if the direct bit is clear to the relative address specified.
JBC bit, rel ; jump if the direct bit is set to the relative address specified and then clear the bit.
RET instruction
RET instruction pops top two contents from the stack and load it to PC.
g. [PC15-8] = [[SP]] ;content of current top of the stack will be moved to higher byte of PC.
h. [SP]=[SP]-1; (SP decrements)
i. [PC7-0] = [[SP]] ;content of bottom of the stack will be moved to lower byte of PC.
j. [SP]=[SP]-1; (SP decrements again)
8051 has 128 bit addressable memory. Bit addressable SFRs and bit addressable PORT pins. It is possible to perform
following bit wise operations for these bit addressable locations.
1. LOGICAL AND
a. ANL C,BIT(BIT ADDRESS) ; ‘LOGICALLY AND’ CARRY AND CONTENT OF BIT ADDRESS, STORE RESULT IN CARRY
b. ANL C, /BIT; ; ‘LOGICALLY AND’ CARRY AND COMPLEMENT OF CONTENT OF BIT ADDRESS, STORE RESULT IN CARRY
2. LOGICAL OR
a. ORL C,BIT(BIT ADDRESS) ; ‘LOGICALLY OR’ CARRY AND CONTENT OF BIT ADDRESS, STORE RESULT IN CARRY
b. ORL C, /BIT; ; ‘LOGICALLY OR’ CARRY AND COMPLEMENT OF CONTENT OF BIT ADDRESS, STORE RESULT IN CARRY
3. CLR bit
a. CLR bit ; CONTENT OF BIT ADDRESS SPECIFIED WILL BE CLEARED.
b. CLR C ; CONTENT OF CARRY WILL BE CLEARED.
4. CPL bit
a. CPL bit ; CONTENT OF BIT ADDRESS SPECIFIED WILL BE COMPLEMENTED.
b. CPL C ; CONTENT OF CARRY WILL BE COMPLEMENTED.
1. Write a program to add the values of locations 50H and 51H and store the result in locationsin 52h
and 53H.
2. Write a program to store data FFH into RAM memory locations 50H to 58H using direct
addressing mode
3. Write a program to subtract a 16 bit number stored at locations 51H-52H from 55H-56H and store
the result in locations 40H and 41H. Assume that the least significant byte of data or theresult is
stored in low address. If the result is positive, then store 00H, else store 01H in 42H. ORG 0000H
; Set program counter 0000H
MOV A, 55H ; Load the contents of memory location 55 into A
CLR C ; Clear the borrow flag
SUBB A,51H ; Sub the contents of memory 51H from contents of A
MOV 40H, A ; Save the LSByte of the result in location 40H
MOV A, 56H ; Load the contents of memory location 56H into A
SUBB A, 52H ; Subtract the content of memory 52H from the content A
MOV 41H, ; Save the MSbyte of the result in location 415.
MOV A, #00 ; Load 005 into A
ADDC A, #00 ; Add the immediate data and the carry flag to A MOV
42H, A ; If result is positive, store00H, else store 0lH in 42H
END
4. Write a program to add two 16 bit numbers stored at locations 51H-52H and 55H-56H and store the
result in locations 40H, 41H and 42H. Assume that the least significant byte of data and the result
is stored in low address and the most significant byte of data or the resultis stored in high address.
13. Write a program to exchange the lower nibble of data present in external memory 6000H and6001H
ORG 0000H ; S e t p r o g r a m c o u n t e r 0 0h
MOV DPTR, # 6000 H ; Copy address 6000 H to DPTR
MOVX A, @DPTR ; Copy contents of 60008 to A
MOV R0, #45H ; Load pointer, R0=45H
MOV @RO, A ; Copy cont of A to RAM pointed by 80
INC DPL ; Increment pointer
MOVX A, @DPTR ; Copy contents of 60018 to A
XCHD A, @R0 ; Excha nge lower nibble of A with RAM pointed by RO
MOVX @DPTR, A ; Copycontents of A to 60018
DEC DPL ; Decrement pointer
MOV A, @R0 ; C o p y c o n t of R A M p o i n t e d b y R 0 t o A
MOVX @DPTR, A ; Copy cont of A to RAM pointed by DPTR
END
14. Write a program to count the number of and o's of 8 bit data stored in location 6000H.
ORG 00008 ; Set program counter 00008
MOV DPTR, #6000h ; Copy address 6000H to DPTR
MOVX A, @DPTR ; Copy num be r t o A
MOV R0,#08 ; Copy 08 in RO
MOV R2,#00 ; C o py 00 in R 2
MOV R3,#00 ; C o py 00 in R 3
CLR C ; Clear carry flag
BACK: RLC A ; Rotate A through carry flag
JC NEXT ; If CF = 1, branch to next
INC R2 ; I f C F = 0 , i n c r e m e n t R 2 AJMP NEXT2
NEXT: INC R3 ; If CF = 1,increment R3
NEXT2: DJNZ RO,BACK ; Repeat until ROis zero
END
15. Write a program to shift a 24 bit number stored at 57H-55H to the left logically four places.
Assume that the least significant byte of data is stored in lower address.
ORG 0000H ; Set program counter 0000h
MOV R1,#04 ; Set up loop count to 4
again: MOV A,55H ; Place the least significant byte of data in A
CLR C ; Clear tne carry flag
RLC A ; Rotate contents of A (55h) left through carry
MOV 55H,A
MOV A,56H
RLC A ; Rotate contents of A (56H) left through carry
MOV 56H,A
MOV A,57H
RLC A ; Rotate contents of A (57H) left through carry
MOV 57H,A
DJNZ R1,again ; Repeat until R1 is zero
END
16. Two 8 bit numbers are stored in location 1000h and 1001h of external data memory.
Write a program to find the GCD of the numbers and store the result in 2000h.
ALGORITHM
• Step 1 :Initialize external data memory with data and DPTR with address
• Step 2 :Load A and TEMP with the operands
• Step 3 :Are the two operands equal? If yes, go to step 9
• Step 4 :Is (A) greater than (TEMP) ? If yes, go to step 6
• Step 5 :Exchange (A) with (TEMP) such that A contains the bigger number
• Step 6 :Perform division operation (contents of A with contents of TEMP)
• Step 7 :If the remainder is zero, go to step 9
• Step 8 :Move the remainder into A and go to step 4
• Step 9 :Save the contents 'of TEMP in memory and terminate the program
ORG 0000H ; Set program counter 0000H
TEMP EQU 70H
TEMPI EQU 71H
MOV DPTR, #1000H ; Copy address 100011 to DPTR
MOVX A, @DPTR ; Copy First number to A
MOV TEMP, A ; Copy First number to temp INC DPTR
MOVX A, @DPTR ; Copy Second number to A
LOOPS: CJNE A, TEMP, LOOP1 ; (A) /= (TEMP) branch to LOOP1
AJMP LOOP2 ; (A) = (TEMP) branch to L00P2
LOOP1: JNC LOOP3 ; (A) > (TEMP) branch to LOOP3
NOV TEMPI, A ; (A) < (TEMP) exchange (A) with (TEMP)
MOV A, TEMP
MOV TEMP, TEMPI
LOOP3: MOV B, TEMP
DIV AB ; Divide (A) by (TEMP)
MOV A, B ; Move remainder to A
CJNE A,#00, LOOPS ; (A)/=00 branch to LOOPS
LOOP2: MOV A, TEMP
MOV DPTR, #2000H
MOVX @DPTR, A ; Store the result in 2000H
END
UNIT V- Interfacing Microcontroller
Interfacing Microcontroller - Programming 8051 Timers - Serial Port Programming - Interrupts Programming – LCD &
Keyboard Interfacing - ADC, DAC & Sensor Interfacing - External Memory Interface- Stepper Motor and Waveform
generation - Comparison of Microprocessor, Microcontroller, PIC and ARM processors
Interfacing Microcontroller:
Every electrical and electronics project designed to develop electronic gadgets that are
frequently used in our day-to-day life utilizes microcontrollers with appropriate interfacing
devices. There are different types of applications that are designed using microcontroller-based
projects. In maximum number of applications, the microcontroller is connected with some
external devices called as interfacing devices for performing some specific tasks. For example,
consider security system with a user changeable password project, in which an interfacing
device, keypad is interfaced with microcontroller to enter the password.
In Intel 8051, there are two 16-bit timer registers. These registers are known as Timer0 andTimer1.
The timer registers can be used in two modes. These modes areTimer mode and the Counter mode.
The only difference between these two modes is the source for incrementing the timer registers.
Timer Mode
In the timer mode, the internal machine cycles are counted. So this register is incremented in each
machine cycle. So when the clock frequency is 12MHz, then the timer register is incremented in each
millisecond. In this mode it ignores the external timer input pin.
Counter Mode
In the counter mode, the external events are counted. In this mode, the timer register is incremented
for each 1 to 0 transition of the external input pin. This type of transitions is treated as events. The
external input pins are sampled once in each machine cycle, and to determine the 1or 0 transitions,
another machine cycle will be needed. So in this mode, at least two machine cycles are needed. When
the frequency is12MHz, then the maximum count frequency will be 12MHz/24 = 500KHz. So for
event counting the time duration is 2 µs.
There are four different modes of the Timer or Counter. The Mode 0 to Mode 2 are for both of the
Timer/Counter. Mode 3 has a different meaning for each timer register. There is a register called
TMOD. This register can be programmed to configure these timers or counters.
The Serial port is used for serial communication in mode 1 and 3. Timer1 is used for generating the
baud rate. So only Timer0 is available for timer or counter operations.
TMOD Register
TMOD(Timer Mode) is an SFR. The address of this register is 89H. This is not bit-addressable.
In the following table, we will see the bit details and their different operations for high or low value.
Bit Details 00 01 10 11
M1 M0 This is for Mode 0. This is Mode 1. This is Mode 3 This is Mode 3 (The
(8-bit timer/counter, (16-bit (8-bit auto function depends
with 5-bit pre- timer/counter) reload- on Timer0 or
scaler) timer/counter) Timer1)
The Gate bit will be high when the timer or counter is in mode 0 to 2.
Examples
To configure the Timer0 as 16-bit event counter and Timer1 as 8-bit auto reload counter, we can use
the bit pattern 0 0 1 0 0 1 0 1. It is equivalent to 25H. If we want to program the TMOD register with
this bit pattern, we can use this instruction:
MOVTMOD, #25H
The above instruction is executed, then the timer/counter will be controlled by the software. To
configure the system as hardware controlled mode, then the gate bits will be 1. So the bit patterns
will be 1 0 1 0 1 1 0 1 = ADH
we can use this instruction:
MOVTMOD, #0ADH
Mode 0 of Timer/Counter
The Mode 0 operation is the 8-bit timer or counter with a 5-bit pre-scaler. So it is a 13-bit
timer/counter. It uses 5 bits of TL0 or TL1 and all of the 8-bits of TH0 or TH1.
In this example the Timer1is selected, in this case, every 32 (25)event for counter operations or 32
machine cycles for timer operation, the TH1 register will be incremented by 1. When the
TH1overflows from FFH to 00H, then the TF1 of TCON register will be high, and it stops the
timer/counter. So for an example, we can say that if the TH1 is holding F0H, and it is in timer mode,
then TF1will be high after 10H * 32 = 512 machine cycles.
MOVTMOD, #00H
MOVTH1, #0F0H
MOVIE, #88H
SETB TR1
In the above program, the Timer1 is configured as timer mode 0. In this case Gate = 0. Then the TH1
will be loaded with F0H, then enable the Timer1 interrupt. At last set the TR1 of TCON register, and
start the timer.
Mode 1 of Timer/Counter
The Mode 1 operation is the 16-bit timer or counter. In the following diagram, we are using Mode 1
for Timer0.
In this case every event for counter operations or machine cycles for timer operation, the TH0– TL0
register-pair will be incremented by 1. When the register pair overflows from FFFFH to 0000H, then
the TF0 of TCON register will be high, and it stops the timer/counter. So for an example, we can say
that if the TH0 – TL0 register pair is holding FFF0H, and it is in timer mode, then TF0 will be high
after 10H = 16 machine cycles. When the clock frequency is 12MHz, then the following instructions
generate an interrupt 16 µs after Timer0 starts running.
MOVTMOD, #01H
MOVTL0, #0F0H
MOVTH0, #0FFH
MOVIE, #82H
SETB TR0
In the above program, the Timer0 is configured as timer mode 1. In this case Gate = 0. Then the TL0
will be loaded with F0H and TH0 is loaded with FFH, then enable the Timer0 interrupt. At last set
the TR0 of TCON register, and start the timer.
Mode 2 ofTimer/Counter
The Mode 2 operation is the 8-bit auto reload timer or counter. In the following diagram, we are using
Mode 2 for Timer1.
In this case every event for counter operations or machine cycles for timer operation, the TL1register
will be incremented by 1. When the register pair overflows from FFH to 00H, then the TF1 of TCON
register will be high, also theTL1 will be reloaded with the content of TH1 and starts the operation
again.
So for an example, we can say that if the TH1 and TL1 register both are holding F0H and it is in timer
mode, then TF1 will be high after 10H= 16 machine cycles. When the clock frequency is 12MHz this
happens after 16 µs, then the following instructions generate an interrupt once every 16 µs after
Timer1 starts running.
MOVTMOD, #20H
MOVTL1, #0F0H
MOVTH1, #0F0H
MOVIE, #88H
SETB TR1
In the above program, the Timer1 is configured as timer mode 2. In this case Gate = 0. Then the TL1
and TH1 are loaded with F0H. then enable the Timer1 interrupt. At last set the TR1 of TCON register,
and start the timer.
Timer1 in mode 2 generates the desired baud rate when the serial port is working on Mode 1 or 3.
Mode 3 of Timer/Counter
Mode 3 is different for Timer0 and Timer1. When the Timer0 is working in mode 3, the TL0 will be
used as an 8-bit timer/counter. It will be controlled by the standard Timer0 control bits, T0
and INT0 inputs. The TH0 is used as an 8-bit timer but not the counter. This is controlled by Timer1
Control bit TR1. When the TH0 overflows from FFH to 00H, then TF1 is set to 1. In the following
diagram, we can Timer0 in Mode 3.
When the Timer1 is working in Mode 3, it simply holds the count but does not run. When Timer0 is
in mode 3, the Timer1 is configured in one of the mode 0, 1 and 2. In this case, the Timer1 cannot
interrupt the microcontroller. When the TF1 is used by TH0 timer, the Timer1 is used as Baud Rate
Generator.
The meaning of gate bit in Timer0 and Timer1 for mode 3 is as follows
It controls the running of 8-bit timer/counter TL0 as like Mode 0, 1, or 2. The running of TH0 is
controlled by TR1 bit only. So the gate bit in this mode for Timer0 has no specific role.
The mode 3 is present for applications requiring an extra 8-bit timer/counter. In Mode 3 of Timer0,
the 8051 has three timers. One 8-bit timer by TH0, another8-bit timer/counter by TL0, and one 16-
bit timer/counter by Timer1.
If the Timer0 is in mode3, and Timer1 is working on either 0, 1 or 2, then the gun control of the Timer1
is activated when the gate bit is low or INT1 is high. The run control is deactivated when the gate is
high and INT1 is low.
Scanned by
Scanned by
Scanned by
Scanned by
Comparison of Microprocessor, Microcontroller
What is a Microprocessor?
A microprocessor is just a CPU combined with one or multiple Integrated Circuits (ICs). It has
not any ROM, RAM, and other instruments. The main operation center of a microprocessor
contains registers, ALU, and a control unit. Microprocessors are categorized based on the data
size in which ALU applies.
What is a Microcontroller?
A microcontroller is like a simple computer designed on a single IC. It includes CU, ALU, ROM,
timer, processor core, RAM, I/O connectors, register, and counters modeled to run several
tasks. Microcontrollers are normally employed in applications and projects that need direct
monitoring by users. Because it contains all the parts required in its simple chip, it does not
require any additional sections to apply its task.
As a result, microcontrollers are commonly used in fixed systems and the main companies of
manufacturing microcontrollers are using them in the embedded applications. The
microcontroller can be introduced as the center of an embedded circuit. Some common
examples of the popular and economic systems are AVR and 8051 series form.
PIC microcontroller was developed in the year 1993 by microchip technology. The term
PIC stands for Peripheral Interface Controller. Initially this was developed for supporting
PDP computers to control its peripheral devices, and therefore, named as a peripheral
interface device. These microcontrollers are very fast and easy to execute a program
compared with other microcontrollers. PIC Microcontroller architecture is based on
Harvard architecture. PIC microcontrollers are very popular due to their ease of
programming, wide availability, easy to interfacing with other peripherals, low cost, large
user base and serial programming capability (reprogramming with flash memory), etc.
We know that the microcontroller is an integrated chip which consists of CPU, RAM, ROM,
timers, and counters, etc. In the same way, PIC microcontroller architecture consists of
RAM, ROM, CPU, timers, counters and supports the protocols such as SPI, CAN, and UART
for interfacing with other peripherals. At present PIC microcontrollers are extensively
used for industrial purpose due to low power consumption, high performance ability and
easy of availability of its supporting hardware and software tools like compilers,
debuggers and simulators.
Every PIC microcontroller architecture consists of some registers and stack where registers
function as Random Access Memory( RAM) and stack saves the return addresses. The main
features of PIC microcontrollers are RAM, flash memory, Timers/Counters, EEPROM, I/O Ports,
USART, CCP (Capture/Compare/PWM module), SSP, Comparator, ADC (analog to digital
converter), PSP(parallel slave port), LCD and ICSP (in circuit serial programming) The 8-bit PIC
microcontroller is classified into four types on the basis of internal architecture such as Base Line
PIC, Mid Range PIC, Enhanced Mid Range PIC and PIC18
The PIC microcontroller architecture comprises of CPU, I/O ports, memory organization, A/D
converter, timers/counters, interrupts, serial communication, oscillator and CCP module which are
discussed in detailed below.
It is not different from other microcontrollers CPU and the PIC microcontroller CPU consists of
the ALU, CU, MU and accumulator, etc. Arithmetic logic unit is mainly used for arithmetic
operations and to take logical decisions. Memory is used for storing the instructions after
processing. To control the internal and external peripherals, control unit is used which are
connected to the CPU and the accumulator is used for storing the results and further process.
Memory Organization
The memory module in the PIC microcontroller architecture consists of RAM (Random Access
Memory), ROM (Read Only Memory) and STACK.
RAM is an unstable memory which is used to store the data temporarily in its registers. The RAM
memory is classified into two banks, and each bank consists of so many registers. The RAM
registers are classified into two types: Special Function Registers (SFR) and General Purpose
Registers (GPR).
These registers are used for general purpose only as the name implies. For example, if we want to
multiply two numbers by using the PIC microcontroller. Generally, we use registers for
multiplying and storing the numbers in other registers. So these registers don’t have any special
function,- CPU can easily access the data in the registers.
These registers are used for special purposes only as the name SFR implies. These registers will
perform according to the functions assigned to them , and they cannot be used as normal registers.
For example, if you cannot use the STATUS register for storing the data, these registers are used
for showing the operation or status of the program. So, user cannot change the function of the SFR;
the function is given by the retailer at the time of manufacturing.
Memory Organization
Read Only Memory (ROM)
Read only memory is a stable memory which is used to store the data permanently. In
PIC microcontroller architecture, the architecture ROM stores the instructions or program,
according to the program the microcontroller acts. The ROM is also called as program memory,
wherein the user will write the program for microcontroller and saves it permanently, and finally
the program is executed by the CPU. The microcontrollers performance depends on the
instruction, which is executed by the CPU.
In the normal ROM, we can write the program for only once we cannot use again
the microcontroller for multiple times. But, in the EEPROM, we can program the ROM multiple
times.
Flash Memory
Flash memory is also programmable read only memory (PROM) in which we can read, write and
erase the program thousands of times. Generally, the PIC microcontroller uses this type of ROM.
Stack
When an interrupt occurs, first the PIC microcontroller has to execute the interrupt and the existing
process address. Then that is being executed is stored in the stack. After completing the execution
of the interrupt, the microcontroller calls the process with the help of address, which is stored in
the stack and get executes the process.
I/O Ports
• The series of PIC16 consists of five ports such as Port A, Port B, Port C, Port D & Port E.
• Port A is an 16-bit port that can be used as input or output port based on the status of the TRISA
(Tradoc Intelligence Support Activity) register.
• Port B is an 8- bit port that can be used as both input and output port.
• Port C is an 8-bit and the input of output operation is decided by the status of the TRISC register.
• Port D is an 8-bit port acts as a slave port for connection to the microprocessor BUS.
• Port E is a 3-bit port which serves the additional function of the control signals to the analog to
digital converter.
BUS
BUS is used to transfer and receive the data from one peripheral to another. It is classified into two
types such as data bus and address.
Address Bus: Address bus is used to transmit the memory address from the peripherals to the CPU.
I/O pins are used to interface the external peripherals; UART and USART both are serial
communication protocols which are used for interfacing serial devices like GSM, GPS, Bluetooth,
IR , etc.
BUS
A/D converters
The main intention of this analog to digital converter is to convert analog voltage values to digital
voltage values. A/D module of PIC microcontroller consists of 5 inputs for 28 pin devices and 8
inputs for 40 pin devices. The operation of the analog to digital converter is controlled by
ADCON0 and ADCON1 special registers. The upper bits of the converter are stored in register
ADRESH and lower bits of the converter are stored in register ADRESL. For this operation, it
requires 5V of an analog reference voltage.
A/D CONVERTER
Timers/ Counters
PIC microcontroller has four timer/counters wherein the one 8-bit timer and the remaining timers
have the choice to select 8 or 16-bit mode. Timers are used for generating accuracy actions, for
example, creating specific time delays between two operations.
Interrupts
PIC microcontroller consists of 20 internal interrupts and three external interrupt sources which
are associated with different peripherals like ADC, USART, Timers, and so on.
Serial Communication
Serial communication is the method of transferring data one bit at a time sequentially over
a communication channel.
• USART: The name USART stands for Universal synchronous and Asynchronous Receiver and
Transmitter which is a serial communication for two protocols. It is used for transmitting and
receiving the data bit by bit over a single wire with respect to clock pulses. The PIC microcontroller
has two pins TXD and RXD. These pins are used for transmitting and receiving the data serially.
• SPI Protocol: The term SPI stands for Serial Peripheral Interface. This protocol is used to send data
between PIC microcontroller and other peripherals such as SD cards, sensors and shift registers.
PIC microcontroller support three wire SPI communications between two devices on a common
clock source. The data rate of SPI protocol is more than that of the USART.
• I2C Protocol: The term I2C stands for Inter Integrated Circuit , and it is a serial protocol which is
used to connect low speed devices such as EEPROMS, microcontrollers, A/D converters, etc.
PIC microcontroller support two wire Interface or I2C communication between two devices which
can work as both Master and Slave device.
Serial Communication
Oscillators
Oscillators are used for timing generation. Pic microcontroller consist of external oscillators like
RC oscillators or crystal oscillators. Where the crystal oscillator is connected between the two
oscillator pins. The value of the capacitor is connected to every pin that decides the mode of the
operation of the oscillator. The modes are crystal mode, high-speed mode and the low-power
mode. In case of RC oscillators, the value of the resistor & capacitor determine the clock frequency
and the range of clock frequency is 30KHz to 4MHz.
CCP module
The name CCP module stands for capture/compare/PWM where it works in three modes such
as capture mode, compare mode and PWM mode.
• Capture Mode: Capture mode captures the time of arrival of a signal, or in other words, when the
CCP pin goes high, it captures the value of the Timer1.
• Compare Mode: Compare mode acts as an analog comparator. When the timer1 value reaches a
certain reference value, then it generates an output.
• PWM Mode: PWM mode provides pulse width modulated output with a 10-bit resolution and
programmable duty cycle.
The PIC microcontroller projects can be used in different applications, such as peripherals, audio
accessories, video games, etc. For better understanding of this PIC microcontroller, the following
project demonstrates PIC microcontroller’s operations.
ARM Architecture
The ARM processor conjointly has other components like the Program status
register, which contains the processor flags (Z, S, V and C). The modes bits
conjointly exist within the program standing register, in addition to the interrupt and
quick interrupt disable bits; Some special registers: Some registers
are used like the instruction, memory data read and write registers and memory
address register.
Priority encoder: The encoder is used in the multiple load and store instruction
to point which register within the register file to be loaded or kept .
• USER Mode
• FIQ Mode
• IRQ Mode
• SVC Mode
• UNDEFINED Mode
• ABORT Mode
• Monitor Mode
USER Mode: The user mode is a normal mode, which has the least number of
registers. It doesn’t have SPSR and has limited access to the CPSR.
FIQ and IRQ: The FIQ and IRQ are the two interrupt caused modes of the CPU.
The FIQ is processing interrupt and IRQ is standard interrupt. The FIQ mode has
additional five banked registers to provide more flexibility and high performance
when critical interrupts are handled.
SVC Mode: The Supervisor mode is the software interrupt mode of the processor
to start up or reset.
Undefined Mode: The Undefined mode traps when illegal instructions are
executed. The ARM core consists of 32-bit data bus and faster data flow.
THUMB Mode: In THUMB mode 32-bit data is divided into 16-bits and increases
the processing speed.
THUMB-2 Mode: In THUMB-2 mode the instructions can be either 16-bit or 32-
bit and it increases the performance of the ARM cortex –M3 microcontroller. The
ARM cortex-m3 microcontroller uses only THUMB-2 instructions.
Some of the registers are reserved in each mode for the specific use of the core. The
reserved registers are
The reserved registers are used for specific functions. The SPSR and CPSR contain
the status control bits which are used to store the temporary data. The SPSR and
CPSR register have some properties that are defined operating modes, Interrupt
enable or disable flags and ALU status flag. The ARM core operates in two states
32-bit state or THUMBS state.
The ALU has two 32-bits inputs. The primary comes from the register file, whereas
the other comes from the shifter. Status registers flags modified by the ALU outputs.
The V-bit output goes to the V flag as well as the Count goes to the C flag. Whereas
the foremost significant bit really represents the
S flag, the ALU output operation is done by NORed to get the Z flag. The
ALU has a 4-bit function bus that permits up to 16 opcode to be implemented.
The multiplier factor has 3 32-bit inputs and the inputs return from the register file.
The multiplier output is barely 32-Least Significant Bits of the merchandise. The
entity representation of the multiplier factor is shown in the above block diagram.
The multiplication starts whenever the beginning 04 input goes active. Fin of the
output goes high when finishing.
Booth Algorithm
Barrel Shifter
The barrel shifter features a 32-bit input to be shifted. This input is coming back
from the register file or it might be immediate data. The shifter has different control
inputs coming back from the instruction register. The Shift field within the
instruction controls the operation of the barrel shifter. This field indicates the
kind of shift to be performed (logical left or right, arithmetic right or rotate
right). The quantity by which the register ought to be shifted is contained in an
immediate field within the instruction or it might be the lower 6 bits of a register
within the register file.
The shift_val input bus is 6-bits, permitting up to 32 bit shift. The shifttype indicates
the needed shift sort of 00, 01, 10, 11 are corresponding to shift left, shift right, an
arithmetic shift right and rotate right, respectively. The barrel shifter is especially
created with multiplexers.
Control Unit
For any microprocessor, control unit is the heart of the whole process and it is
responsible for the system operation,so the control unit design is the most important
part within the whole design. The control unit is sometimes a pure combinational
circuit design. Here, the control unit is implemented by easy state machine. The
processor timing is additionally included within the control unit. Signals from the
control unit are connected to each component within the processor to supervise its
operation.
8051 TIMERS
8051 has two timers/Counters(TIMER 0 and TIMER 1). They can be
used as timers to generate time delays or as event counters.
THx TLx
[Source: “The 8051Microcontroller and Embedded Systems: Using Assembly and C” by Mohamed Ali
Mazidi,Janice Gillispie Mazidi, Rolin McKinlay]
In upper or lower 4 bits, first bit is a GATE bit. Every timer has a
means ofstarting and stopping. Some timers do this by software, some by hardware,
and some haveboth software and hardware controls. The hardware way of starting
and stopping the timerby an external source is achieved by making GATE=1 in the
TMOD register and if GATE=0 then we do start and stop the timers by
programming.
The second bit is C/T bit and is used to decide whether a timer is used
as a time delay generator or an event counter. If this bit is 0 then it is used as a
timer and if itis 1 then it is used as a counter.
In upper or lower 4 bits, the last bits third and fourth are known as
M1 and M0 respectively. These are used to select the timer mode.
TIMER’S CLOCK FREQUENCY AND ITS PERIOD
In 8051-based system, the crystal oscillator has a frequency of 11.0592 MHz
whenC/T bit of TMOD is 0. Each machine cycle is made up of 12 clock cycles.
Hence for a single machine cycle, the frequency becomes 1/12 × 11.0529 MHz =
921.6 KHz. For a single machine cycle, the time taken is T = 1/921.6 KHz = 1.085
us, so the oscillator takes 1.085us for completing a single machine cycle.
MODES OF OPERATION:
MODE 1:
It is a 16-bit timer; therefore it allows values from 0000 to FFFFH
to be loaded into the timer’s registers TL and TH as shown in Figure 5.1.3. After
TH and TL are loaded with a 16-bit initial value, the timer must be started. We can
do it by “SETB TR0” for timer 0 and “SETB TR1” for timer 1. After the timer is
started, it starts count up until it reaches its limit of FFFFH. When it rolls over from
FFFF to 0000H, it sets higha flag bit called TFx (timer flag). This timer flag can
be monitored. When this timer flagis raised, one option would be stop the timer
with the instructions “CLR TR0“ or CLR TR1 for timer 0 and timer 1 respectively.
Again, it must be noted that each timer flag TF0for timer 0 and TF1 for timer1.
After the timer reaches its limit and rolls over, in order torepeat the process the
registers TH and TL must be reloaded with the original value and TF must be reset
to 0.
Figure 5.1.3 Timer in
Mode 1
[Source: “The 8051Microcontroller and Embedded Systems: Using Assembly and C” by Mohamed Ali
Mazidi,Janice Gillispie Mazidi, Rolin McKinlay, [Link].244]
MODE 0 :
Mode 0 is exactly same like mode 1 except that it is a 13-bit timer
instead
of 16-bit. The 13- bit counter can hold values between 0000 to 1FFFH in
TH-TL.
MODE 2:
It is an 8 bit timer that allows only values of 00 to FFH to be loaded
into the
timer’s register TH as shown in Figure 5.1.4. After THx is loaded with 8 bit value,
the 8051 gives a copy of it to TLx. Then the timer must be started. It is done by the
instruction“SETB TR0” for timer 0 and “SETB TR1” for timer1. This is like mode
1.
After timer is started, it starts to count up by incrementing the TLx
[Link] counts up until it reaches its limit of FFH. When it rolls over from FFH
to 00, it sets high the TFx (timer flag). If we are using timer 0, TF0 goes high; if
using TF1 then TF1is raised. When TLx register rolls from FFH to 00 and TF is
set to 1, TLx is reloaded automatically with the original value kept by the THx
register. To repeat the process, wemust simply clear TFx and let it go without any
need by the programmer to reload the original value. This makes mode 2 auto
reload, in contrast in mode 1 in which programmer has to reload THx and TLx.
Figure 5.1.4 Timer in
Mode 2
[Source: “The 8051Microcontroller and Embedded Systems: Using Assembly and C” by Mohamed Ali
Mazidi,Janice Gillispie Mazidi, Rolin McKinlay, [Link].251]
MODE 3:
Mode 3 is also known as a split timer mode. Timer 0 and 1
may be
programmed to be in mode 0, 1 and 2 independently of similar mode for other timer.
Thisis not true for mode 3; timers do not operate independently if mode 3 is chosen
for timer 0. Placing timer 1 in mode 3 causes it to stop counting; the control bit
TR1 and the timer1 flag TF1 are then used by timer 0.
TIMER
PROGRAMMING
MODE 1
PROGRAMMING:
It is a 16 bit Timer mode.
STEPS TO PROGRAM IN MODE 1:
1. Load the TMOD value register with mode and timer0 or 1.
2. Load registers TLx and THx with initial count corresponding to delay.
3. Start the timer.
4. Continuously monitor the timer flag (TFx) with the “JNB TFx,target”
instruction tosee if it is raised, if it is raised(TFx=1) then get out of the loop.
5. Stop the timer.
6. Clear the TFx flag for the next round.
7. Go back to Step 2 to load THx and TLx again.
Given:
Square wave frequency=5
kHz Clock
frequency=11.0592 MHz
Step 1: Calculate the
Time delayT=1/f=1/5 kHz
=0.2 ms
T=0.2 ms which is the period of
square waveT/2 =0.2/2=0.1 ms delay
for high and low
Step 2: Divide the desired time delay by
1.085 usCount=0.1ms/1.085 us = 921
Step 3: Perform 65536 – n
TH0-TL0= 65536-921=64615=FC67H
Step 4: Set TL = xx and TH = yy
Here xx=FC and yy=67. Hence,TH0=FCh,TL0=67h
MOV TMOD,#01
AGAIN: MOV TL1,#67H
MOV TH1,#0FCH
SETB TR1 Timer 0, mode 1, 16-bitmode
;TL1=67, low byte of timer
;TH1=FC, the high byte
;Start timer 1 BACK: JNB TF1,BACK ;until
timer rolls over
CPL P1.0 ; compliment P1.0
CLR TR1 ;Stop the timer 1
CLR TF1 ;Clear timer 1 flag
SJMP AGAIN ;Reload timer
Interfacing Devices
Interfacing can be defined as transferring data between microcontrollers and
interfacing peripherals such as sensors, keypads, microprocessors, analog to
digital converters or ADC, LCD displays, motors, external memories, even with
other microcontrollers, some other interfacing peripheral devices and so on or
input devices and output devices. These devices that are interfacing with 8051
microcontroller are used for performing special tasks or functions are called as
interfacing devices.
Interfacing is a technique that has been developed and being used to solve
many composite problems in circuit designing with appropriate features,
reliability, availability, cost, power consumption, size, weight, and so on. To
facilitate multiple features with simple circuits, microcontroller is interfaced with
devices such as ADC, keypad, LCD display and so on.
Major Electronic Peripherals
Interfacing to Microcontroller 8051
Interfacing is one of the important concepts in microcontroller 8051 because
the microcontroller is a CPU that can perform some operation on a data and
gives the output. However to perform the operation we need an input device to
enter the data and in turn output device displays the results of the operation.
Here we are using keyboard and LCD display as input and output devices along
with the microcontroller.
Circuit Diagram
7-Segment Display
The 7-segment displays are used in a number of systems to display the numeric
information. They can display one digit at a time. Thus the number of segments
used depends on the number of digits to display. Here the digits 0 to 9 are
displayed continuously at a predefined time delay.
The 7-segment displays are available in two configurations which are common
anode and common cathode. Here common anode configuration is used
because output current of the microcontroller is not sufficient enough to drive
the LEDs. The 7-segment display works on negative logic, we have to provide
logic 0 to the corresponding pin to make on LED glow.
LCD Display
LCD is very important device which is used for almost all automated devices
such as washing machines, an autonomous robot, power control systems and
other devices. This is achieved by displaying their status on small display
modules like 7-seven segment displays, multi segment LEDs etc. The reasons
being, LCDs are reasonably priced, easily programmable and they have a no
limitations of displaying special characters.
It consists of two registers such as command/instruction register and data
register.
The data register stores the data to be displayed on LCD. The data is an ASCII
value of the characters to be displayed on the LCD.
Circuit Diagram
Matrix keypad interfacing to 8051
We hope we have been able to provide ample knowledge about the basic yet
important interfacing circuits of microcontroller 8051. These are the most basic
circuits required in any embedded system application and we hope we have
provided you with a good revision.
A further query or feedback related to this topic is welcome to be mentioned in
the comment section below.
Photo Credits
• Microcontroller 8051 Peripheral devices by aninditadhikary
• 7-Segment Display by electronicsteacher
• 7-Segment Display Configurations by thelearningpit
• LCD Display by [Link]
• Unipolar &Bipolar Steppers by engineersgarage
• Matrix Keypad by vetco
• Keypad Internal Diagram by [Link]