0% found this document useful (0 votes)
151 views61 pages

UNIT 5 MP&MC (Final)

This document discusses Chapter 5 of the textbook on assembly programming and instructions for the 8051 microcontroller. It covers various topics related to 8051 assembly programming including introduction, assembling and running programs, data types, assembler directives, arithmetic and logic instructions, jump and call instructions, I/O port programming, timer programming, serial port programming, interrupt programming, and interfacing with devices like LCD, keyboard, ADC, DAC, and sensors. It provides examples of assembly language code and explains the steps taken by the processor in executing a simple program.

Uploaded by

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

UNIT 5 MP&MC (Final)

This document discusses Chapter 5 of the textbook on assembly programming and instructions for the 8051 microcontroller. It covers various topics related to 8051 assembly programming including introduction, assembling and running programs, data types, assembler directives, arithmetic and logic instructions, jump and call instructions, I/O port programming, timer programming, serial port programming, interrupt programming, and interfacing with devices like LCD, keyboard, ADC, DAC, and sensors. It provides examples of assembly language code and explains the steps taken by the processor in executing a simple program.

Uploaded by

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

UNIT 5

SUBJECT NAME: Microprocessor & Microcontroller


SUBJECT CODE : KEC-502
BRANCH/SEM : ECE/5th

FACULTY MENTOR: Dr. Sanjay Kr. Singh

TEAM MEMBERS : Ms. Ranjeeta Yadav


Ms. Tania Gupta
Mr. Rajeev Kumar Pandey
CHAPTER-5: ASSEMBLY PROGRAMMING AND
INSTRUCTION OF 8051
5.1 Introduction to 8051 Assembly Programming
5.2 Assembling and running an 8051 Program
5.3 Data Types and Assembler Directives
5.3.1 Data Type
5.3.2 Assembler Directives
5.4 Arithmetic, Logic Instructions And Programs
5.5 JUMP, LOOP AND CALL Instructions
5.5.1 Jump and Call Program Range
5.5.2. Relative Jump
5.5.3 Short Absolute Jump
5.5.4 Long Absolute Jump/Call
5.5.5 Bit level jump instructions
5.5.6 Subroutine CALL and RETURN
5.5.7 RET instruction

5.6. Io Port Programming


5.6.1 I/O Ports and their Functions
5.6.2 Dual Role of Port 0 and Port 2
5.6.3 Hardware Connection of Pins
5.6.4 I/O Ports and Bit Addressability
5.7 Programming 8051 Timers
5.7. 1 Timer/ Counter Control Logic
5.7.2 Timer Modes
5.7.3 Programming 8051 Timers In Assembly
5.7.4 Steps for programming timers in 8051
5.8 Serial Port Programming
5.8.1 Data communication
5.8.2 Basics of Serial Data Communication
5.8.3 Types of Serial communication
5.8.4 8051 Serial communication
5.8.5 Serial Communication Modes
5.8.6 Connectiontors-232
5.9 Interrupt Programming
5.9.1 Basics of Interrupts
5.9.2 Steps taken by processor while processing an interrupt:
5.9.3 Classification of interrupts
5.10 Interfacing
5.11 LCD & Keyboard Interfacing
5.11.1 LCD Display
5.11.2 Keyboard Interfacing
5.12 ADC, DAC & Sensor Interfacing
5.12.1 What is an ADC?
5.12.2 Logic to communicate between 8051 and ADC 0808
5.12.3 Interfacing With Digital To Analog Converter
5.13 Sensor Interfacing with 8051
5.13.1 Classifications of Sensors:
5.14 Stepper Motor and Waveform Generation
5.14.1 Stepper motor interfacing circuit
5.14.2 Stepper motor interfacing circuit
5.15 University Questions Related To the Topic
CHAPTER 5:- ASSEMBLY PROGRAMMING AND INSTRUCTION
OF 8051

5.2 Introduction to 8051 Assembly Programming


Register are used to store information temporarily, while the information could be a byte of data to be
processed, or an address pointing to the data to be fetched ‰.The vast majority of 8051 register are 8-bit
registers There is only one data type i.e.8 bits.

The 8 bits of a register are shown from MSB D7 to the LSB D0 With an 8-bit data type, any data larger
than 8 bits must be broken into 8-bit chunks before it is processed.

The most widely used registers :- A (Accumulator) For all arithmetic and logic instructions ,B, R0, R1,
R2, R3, R4, R5, R6, R7 ,DPTR (data pointer), and PC (program counter).

Important Terms

Label:. The label is a symbolic address for the instruction. When the program is assembled, the label will
be given specific address in which that instruction is stored. Unless that specific line of instruction is
needed by a branching instruction in the program, it is not necessary to label that line.

Opcode: Opcode is the symbolic representation of the operation. The assembler converts the opcode
to a unique binary code (machine language).

Operand: While opcode specifies what operation to perform, operand specifies where to perform that
action. The operand field generally contains the source and destination of the data. In somecases only
source or destination will be available instead of both. The operand will be either address of the data,
or data itself.

Comment:-Always comment will begin with ;or // symbol. To improve the program quality,
programmer may always use comments in the program.

In the early days of the computer, programmers coded in machine language, consisting of 0 s and
1s which is Tedious, slow and prone to error. Assembly languages, which provided mnemonics for the
machine code instructions, plus other features, were developed. An Assembly language program consist
of a series of lines of Assembly language instructions .Assembly language is referred to as a low level
language It deals directly with the internal structure of the CPU.

Assembly language instruction includes a mnemonic (abbreviation easy to remember) , the


commands to the CPU, telling it what those to do with those items , optionally followed by one or two
operands, the data items being manipulated . A given Assembly language program is a series of
statements, or lines .Assembly language instructions which tell the CPU what to do Directives (or
pseudo-instructions) ,give directions to the assemble.

5.3 Assembling, And Running An 8051 Program

The step of assembly language program are outlines as follows:-


1) First we use an editor to type a program, many excellent editors or word processors are available that
can be used to create and/or edit the program. Notice that the editor must be able to produce an ASCII
file . For many assemblers, the file names follow the usual DOS conventions, but the source file has the
extension “asm“ or “src”, depending on which assembly you are using.
2) The “asm” source file containing the program code created in step 1 is fed to an 8051 assembler. The
assembler converts the instructions into machine code ƒ The assembler will produce an object file and a
list file ƒ The extension for the object file is “obj” while the extension for the list file is “lst” .

3) Assembler require a third step called linking .The linker program takes one or more object code files
and produce an absolute object file with the extension “abs” .This abs file is used by 8051 trainers that
have a monitor program.
4) Next the “abs” file is fed into a program called “OH” (object to hex converter) which creates a file
with extension “hex” that is ready to burn into ROM. This program comes with all 8051 assemblers.
Recent Windows-based assemblers combine step 2 through 4 into one step.
Following figure shows the steps required in programming:-
Fig 1 – Step for programming
Lst file:- The lst (list) file, which is optional, is very useful to the programmer .It lists all the opcodes and
addresses as well as errors that the assembler detected. The programmer uses the lst file to find the syntax
errors or debug.
Program Counter:- The program counter points to the address of the next instruction to be executed .As
the CPU fetches the opcode from the program ROM, the program counter is increasing to point to the
next instruction ‰ The program counter is 16 bits wide . This means that it can access program addresses
0000 to FFFFH, a total of 64K bytes of code.
Power up:- All 8051 members start at memory address 0000 when they’re powered up . Program
Counter has the value of 0000 .The first opcode is burned into ROM address 0000H, since this is where
the 8051 looks for the first instruction when it is booted. We achieve this by the ORG statement in the
source program.
Executing Program
Consider following example. A step-by-step description of the action of the 8051 upon applying power
on it:-

1. 0000 ORG 0H ;start (origin) at 0


2. 0000 7D25 MOV R5,#25H ;load 25H into R5
3. 0002 7F34 MOV R7,#34H ;load 34H into R7
4. 0004 7400 MOV A,#0 ;load 0 into A
5. 0006 2D ADD A,R ;add contents of R5 to A ;now A = A + R5
6. 0007 2F ADD A,R7 ;add contents of R7 to A ;now A = A + R7
7. 0008 2412 ADD A,#12H ;add to A value 12H ;now A = A + 12H
8. 000A 80EF HERE: SJMP HERE ;stay in this loop
9. 000C END ;end of asm source file

1. When 8051 is powered up, the PC has 0000 and starts to fetch the first opcode from
location 0000 of program ROM. Upon executing the opcode 7D, the CPU fetches the
value 25 and places it in R5. Now one instruction is finished, and then the PC is
incremented to point to 0002, containing opcode 7F 2. Upon executing the opcode 7F, the
value 34H is moved into R7 . The PC is incremented to 0004.
2. Upon executing the opcode 7F, the value 34H is moved into R7 .The PC is incremented to
0004
3. The instruction at location 0004 is executed and now PC = 0006
4. After the execution of the 1-byte instruction at location 0006, PC = 0007
5. Upon execution of this 1-byte instruction at 0007, PC is incremented to 0008.

This process goes on until all the instructions are fetched and executed. The fact that program counter
points at the next instruction to be executed explains some microprocessors call it the instruction pointer.

5.3 Data Types and Assembler Directives


5.3.1 Data Type
8051 microcontroller has only one data type - 8 bits. The size of each register is also 8 bits. It is the job of the
programmer to break down data larger than 8 bits (00 to FFH, or 0 to 255 in decimal) .The data types can be
positive or negative.
5.3.2 Assembler Directives
Assembler directives tell the assembler to do something other than creating the machine code for an
instruction. In assembly language programming, the assembler directives instruct the assembler to
1. Process subsequent assembly language instructions
2. Define program constants
3. Reserve space for variables

The following are the widely used 8051 assembler directives.


ORG (Origin):-
The ORG directive is used to indicate the starting address. It can be used only when the program
counter needs to be changed. The number that comes after ORG can be either in hex or in decimal.
Ex: ORG 0000H ;Set PC to 0000.

EQU and SET:-

EQU and SET directives assign numerical value or register name to the specified symbol name. EQU
is used to define a constant without storing information in the memory. The symbol defined with
EQU should not be redefined. SET directive allows redefinition of symbols at a later stage.

DB (Define Byte):-
The DB directive is used to define an 8 bit data. DB directive initializes memory with 8 bit values. The
numbers can be in decimal, binary, hex or in ASCII formats. For decimal, the 'D' after the decimal
number is optional, but for binary and hexadecimal, 'B' and ‘H’ are required. For ASCII, the number is
written in quotation marks (‘LIKE This).

DATA1 DB 40H ; hex


DATA DB 01011100B ;b i n a r y
DATA DB 48 ; decimal
DATA DB ' HELLO W’ ; ASCII
END:-
The END directive signals the end of the assembly module. It indicates the end of the program to
the assembler. Any text in the assembly file that appears after the END directive is ignored. If the
END statement is missing, the assembler will generate an error message.

5.5 Arithmetic, Logic Instructions And Programs


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

Explanation:-
1. Data transfer instructions

In this group, the instructions perform data transfer operations of the following types.
In this group, the instructions perform data transfer operations of the following types.
a. Move the contents of a register Rn toA
i. MOVA,R2
ii. MOVA,R7
b. Move the contents of a register A toRn
i. MOVR4,A
ii. MOVR1,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 MOV @R0, #0E8H
ii. MOV R6,#51H iv. MOV DPTR,#0F5A2H
iii. MOV 30H,#44H v. 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
ii. MOV A,@R0
iii. MOV 45H,A
iv. MOV @R1,A
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. MOVXA,@R1
ii. MOVX@R0,A
h. Move the contents of program memory to A
1. MOVC A,@A+PC
2. MOVC A,@A+DPTR
3. MOVXA,@DPTR
4. MOVX@DPTR,A
Exchange Instructions
The content of source ie., register, direct memory or indirect memory will be
exchanged with the contents of destination ie., accumulator.
i. XCHA,R3
ii. XCHA,@R1
iii. XCHA,54h
j. Exchange digit. Exchange the lower order nibble of Accumulator (A0-A3) with lower order
nibble of the internal RAM location which is indirectly addressed by theregister.
i. XCHDA,@R1
ii. XCHDA,@R0

2.Arithmetic Instructions:-
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 withoutcarry.
i. ADD A,#45H
ii. ADDC A,#OB4H
ii. Add the contents of A with register Rn with or withoutcarry.
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

CY AC and OV flags will be affected by this operation.

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
CY AC and OV flags will be affected by this operation.

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]=45xF5=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. MOVA, #45H ;[A]=0E8H
MOV B,#0F5H ;[B]=1BH

DIVAB ;[A]/[B]=E8/1B=08Hwithremainder10H

;[A] = 08H, [B]=10H

DAA (Decimal Adjust After Addition).

When two BCD numbers are added, the answer is a non-BCD number. To get the result in BCD, we
use 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.

Eg1: MOV A,#23H

MOV R1,#55H
ADDA,R1 //[A]=78
DA A // [A]=78 no changes in the accumulator after DAA.

Eg2: MOV A,#53H

MOV R1,#58H

ADDA,R1 //[A]=ABh

DA A //[A]=11,C=1.ANSWERIS111.AccumulatordataischangedafterDAA

Increment:

Increments the operand by one.

INC A
INC Rn
INC DIRECT
INC @RiINCDPTR
INC increments the value of source by1. 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.

Decrement:
Decrements the operand by one.
DEC A
DEC Rn
DEC DIRECT
DEC@Ri
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
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.
ORLA,#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.
XRLA,#DATA
XRL A,Rn
XRL A,DIRECT
XRLA,@Ri
XRL DIRECT,A
XRL DIRECT, #DATA
CPL complements operand, leaving the result in operand. If operand is a single bit the state of the bit
will be reversed. If operand is the Accumulator then all the bits in the Accumulator will be reversed.

CPL A,
CPL C,
CPL bit address
SWAP A – Swap the upper nibble and lower nibble of A.

Rotate Instructions
RRA
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.
5.5 JUMP, LOOP AND CALL Instructions
Repeating a sequence of instructions a certain number of times is called a loop. Loop action is performed
by
DJNZ Reg, Label
The register is decremented If it is not zero, it jumps to the target address referred to by the label .Prior to
the start of loop the register is loaded with the counter for the number of repetitions ƒ, Counter can be R0
– R7 or RAM location.
Nested Loop- If we want to repeat an action more times than 256, we use a loop inside a loop, which is called
nested loop .We use multiple registers to hold the count.

5.5.1 Jump and Call Program Range


There are 3 types of jump instructions. They are:-
1. Relative Jump
2. Short Absolute Jump
3. Long Absolute Jump

5.5.2. 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: -

The advantages of the relative jump are as follows:-

1. Only 1 byte of jump address needs to be specified in the 2's complement form, ie. For
jumping ahead, the range is 0 to 127 and for jumping back, the range is -1 to-128.
2. Specifying only one byte reduces the size of the instruction and speeds up program
execution.
3. The program with relative jumps can be relocated without reassembling to generate
absolute jump addresses.

Disadvantages of the absolute jump: -


1. Short jump range (-128 to 127 from the instruction following the jump instruction)

Instructions that use Relative Jump


SJMP <relative address>; this is unconditional jump

The remaining relative jumps are conditional jumps

JC <relative address> JNC <relative address> JB bit, <relativeaddress>

JNB bit, <relative address> JBC bit, <relative address>

CJNE <destination byte>, <source byte>, <relative address>

DJNZ <byte>, <relative address>

JZ <relative address>

JNZ <relative address>

5.5.3 Short Absolute Jump


In this case only 11 bits of the absolute jump address are needed. The absolute jump address is
calculated in the following manner.
In 8051, 64 kbyte of program memory space is divided into 32 pages of 2 kbyte each. The
hexadecimal addresses of the pages are given as follows:-

Page(Hex) Address (Hex)

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 5 bits 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.

Advantage: The instruction length becomes 2 bytes. Example of short absolute jump: -

ACALL <address11>
AJMP <address11>
5.5.4 Long Absolute Jump/Call
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: -
LCALL <address 16>
LJMP <address 16>
JMP @A+DPTR

Another classification of jump instructions is


1. Unconditional Jump
2. Conditional Jump

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 toFFFFH
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 there for
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
CJNEreg,#data Jump if byte ≠ #data
CJNEA,byte Jump if A ≠byte
DJNZ Decrement and Jump if A ≠0
JNZ Jump if A ≠0
JZ Jump if A =0

All conditional jumps are short jumps.


5.5.5 Bit level jump instructions:

Bit level JUMP instructions will check the conditions of the bit and if condition is true, it jumps to the
address specified in the instruction. All the bit jumps are relative jumps.
JBbit, rel ; jump if the direct bit is set to the relative address specified.
JNBbit,rel ;jump if the direct bit is clear to the relative address specified.
JBCbit,rel ; jump if the direct bit is set to the relative address specified and then clear the
bit.

5.5.6 Subroutine CALL And RETURN Instructions

Subroutines are handled by CALL and RET instructions. There are two types of CALL instructions
1. LCALL address(16bit)
This is long call instruction which unconditionally calls the subroutine located at the
indicated 16 bit address. This is a 3 byte instruction. The LCALL instruction works as
follows.

a. During execution of LCALL, [PC]=[PC]+3 ;(if address where LCALL resides


is say,0x3254; during execution of this instruction [PC] = 3254h + 3h =3257h.
b. [SP]=[SP]+1; (if SP contains default value 07, then SP increments and[SP]=08
c. [[SP]] = [PC7-0]; (lower byte of PC content ie.,57 will be stored in memory
location08.
d. [SP]=[SP]+1; (SP increments again and[SP]=09)
e. [[SP]] = [PC15-8]; (higher byte of PC content ie., 32 will be stored in memory
location09.

With these the address (0x3254) which was in PC is stored in stack.

f. [PC]=address (16 bit);the new address of subroutine is loaded to PC. No flags are
affected.

2. ACALL address(11bit)
This is absolute call instruction which unconditionally calls the subroutine located at the
indicated 11 bit address. This is a 2 byte instruction. The SCALL instruction works as
follows.

a. During execution of SCALL,[PC]=[PC]+2;(if address where LCALL resides is


say,0x8549; during execution of this instruction [PC] = 8549h + 2h =854Bh
b. [SP]=[SP]+1; (if SP contains default value 07, then SP increments and[SP]=08
c. [[SP]] = [PC7-0]; (lower byte of PC content ie., 4B will be stored in memory
location08.
d. [SP]=[SP]+1; (SP increments again and[SP]=09)
e. [[SP]] = [PC15-8]; (higher byte of PC content ie., 85 will be stored in memory
location09.

With these the address (0x854B) which was in PC is stored in stack.


f. [PC10-0]= address (11bit); the new address of subroutine is loaded to PC. No
flags are affected.

5.5.7 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)

5.6 IO PORT PROGRAMMING

8051 can be interfaced with the processor by two methods


 Isolated I/O, I/O mapped I/O.
In this addressing method, IN,OUT instructions (microprocessors) are used to access the
input/output devices.
 Memory mapped I/O.
The instructions used to access the memory itself will be used for accessing I/O devices.
The I/O devices are connected to the addresses where it can be accessed using simple
memory accessing mechanism.

5.6.1 I/O Ports and their Functions


The four ports P0, P1, P2, and P3, each use 8 pins, making them 8-bit ports. Upon RESET, all the ports
are configured as inputs, ready to be used as input ports. When the first 0 is written to a port, it becomes
an output. To reconfigure it as an input, a 1 must be sent to a port.
Port 0 (Pin No 32 – Pin No 39)
It has 8 pins (32 to 39). It can be used for input or output. Unlike P1, P2, and P3 ports, we normally
connect P0 to 10K-ohm pull-up resistors to use it as an input or output port being an open drain.
It is also designated as AD0-AD7, allowing it to be used as both address and data. In case of 8031 (i.e.
ROM less Chip), when we need to access the external ROM, then P0 will be used for both Address and
Data Bus. ALE (Pin no 31) indicates if P0 has address or data. When ALE = 0, it provides data D0-D7,
but when ALE = 1, it has address A0-A7. In case no external memory connection is available, P0 must be
connected externally to a 10K-ohm pull-up resistor.
Fig 2- Port 0 with pull up register

MOV A,#0FFH ;(comments: A=FFH(Hexadecimal i.e. A=1111 1111)


MOV P0,A ;(Port0 have 1's on every pin so that it works as Input)

Port 1 (Pin 1 through 8)


It is an 8-bit port (pin 1 through 8) and can be used either as input or output. It doesn't require pull-up
resistors because they are already connected internally. Upon reset, Port 1 is configured as an input port.
The following code can be used to send alternating values of 55H and AAH to Port 1.
;Toggle all bits of continuously
MOV A,#55
BACK:
MOV P2,A
ACALL DELAY
CPL A ;complement(invert) reg. A
SJMP BACK
If Port 1 is configured to be used as an output port, then to use it as an input port again, program it by
writing 1 to all of its bits as in the following code.
;Toggle all bits of continuously

MOV A ,#0FFH ;A = FF hex


MOV P1,A ;Make P1 an input port
MOV A,P1 ;get data from P1
MOV R7,A ;save it in Reg R7
ACALL DELAY ;wait
MOV A,P1 ;get another data from P1
MOV R6,A ;save it in R6
ACALL DELAY ;wait

MOV A,P1 ;get another data from P1


MOV R5,A ;save it in R5

Port 2 (Pins 21 through 28)


Port 2 occupies a total of 8 pins (pins 21 through 28) and can be used for both input and output
operations. Just as P1 (Port 1), P2 also doesn't require external Pull-up resistors because they are already
connected internally. It must be used along with P0 to provide the 16-bit address for the external
memory. So it is also designated as (A0–A7), as shown in the pin diagram. When the 8051 is connected
to an external memory, it provides path for upper 8-bits of 16-bits address, and it cannot be used as I/O.
Upon reset, Port 2 is configured as an input port. The following code can be used to send alternating
values of 55H and AAH to port 2.
;Toggle all bits of continuously
MOV A,#55
BACK:
MOV P2,A
ACALL DELAY
CPL A ; complement (invert) reg. A
SJMP BACK
If Port 2 is configured to be used as an output port, then to use it as an input port again, program it by
writing 1 to all of its bits as in the following code.
;Get a byte from P2 and send it to P1
MOV A,#0FFH ;A = FF hex
MOV P2,A ;make P2 an input port
BACK:
MOV A,P2 ;get data from P2
MOV P1,A ;send it to Port 1
SJMP BACK ;keep doing that

Port 3 (Pins 10 through 17)


It is also of 8 bits and can be used as Input/Output. This port provides some extremely important signals.
P3.0 and P3.1 are RxD (Receiver) and TxD (Transmitter) respectively and are collectively used for Serial
Communication. P3.2 and P3.3 pins are used for external interrupts. P3.4 and P3.5 are used for timers T0
and T1 respectively. P3.6 and P3.7 are Write (WR) and Read (RD) pins. These are active low pins,
means they will be active when 0 is given to them and these are used to provide Read and Write
operations to External ROM in 8031 based systems.

P3 Bit Function Pin


P3.0 RxD 10

P3.1 < TxD 11

P3.2 < Complement of 12


INT0

P3.3 < INT1 13

P3.4 < T0 14

P3.5 < T1 15

P3.6 < WR 16

P3.7 < Complement of 17


RD

5.6.2 Dual Role of Port 0 and Port 2

 Dual role of Port 0 − Port 0 is also designated as AD0–AD7, as it can be used for both data and
address handling. While connecting an 8051 to external memory, Port 0 can provide both address
and data. The 8051 microcontroller then multiplexes the input as address or data in order to save
pins.
 Dual role of Port 2 − Besides working as I/O, Port P2 is also used to provide 16-bit address bus for
external memory along with Port 0. Port P2 is also designated as (A8– A15), while Port 0 provides
the lower 8-bits via A0–A7. In other words, we can say that when an 8051 is connected to an
external memory (ROM) which can be maximum up to 64KB and this is possible by 16 bit address
bus because we know 216 = 64KB. Port2 is used for the upper 8-bit of the 16 bits address, and it
cannot be used for I/O and this is the way any Program code of external ROM is addressed.

5.6.3 Hardware Connection of Pins


 Vcc − Pin 40 provides supply to the Chip and it is +5 V.
 Gnd − Pin 20 provides ground for the Reference.
 XTAL1, XTAL2 (Pin no 18 & Pin no 19) − 8051 has on-chip oscillator but requires external clock
to run it. A quartz crystal is connected between the XTAL1 & XTAL2 pin of the chip. This crystal
also needs two capacitors of 30pF for generating a signal of desired frequency. One side of each
capacitor is connected to ground. 8051 IC is available in various speeds and it all depends on this
Quartz crystal, for example, a 20 MHz microcontroller requires a crystal with a frequency no more
than 20 MHz.
Fig 3 – Crystal frequency connection
 RST (Pin No. 9) − It is an Input pin and active High pin. Upon applying a high pulse on this pin,
that is 1, the microcontroller will reset and terminate all activities. This process is known as Power-
On Reset. Activating a power-on reset will cause all values in the register to be lost. It will set a
program counter to all 0's. To ensure a valid input of Reset, the high pulse must be high for a
minimum of two machine cycles before it is allowed to go low, which depends on the capacitor
value and the rate at which it charges. (Machine Cycle is the minimum amount of frequency a
single instruction requires in execution).
 EA or External Access (Pin No. 31) − It is an input pin. This pin is an active low pin; upon
applying a low pulse, it gets activated. In case of microcontroller (8051/52) having on-chip ROM,
the EA (bar) pin is connected to Vcc. But in an 8031 microcontroller which does not have an on-chip
ROM, the code is stored in an external ROM and then fetched by the microcontroller. In this case,
we must connect the (pin no 31) EA to Gnd to indicate that the program code is stored externally.
Fig 4- EA connection

 PSEN or Program store Enable (Pin No 29) − This is also an active low pin, i.e., it gets activated
after applying a low pulse. It is an output pin and used along with the EA pin in 8031 based (i.e.
ROMLESS) Systems to allow storage of program code in external ROM.
 ALE or (Address Latch Enable) − This is an Output Pin and is active high. It is especially used for
8031 IC to connect it to the external memory. It can be used while deciding whether P0 pins will be
used as Address bus or Data bus. When ALE = 1, then the P0 pins work as Data bus and when ALE
= 0, then the P0 pins act as Address bus.

5.6.4 I/O Ports and Bit Addressability


It is a most widely used feature of 8051 while writing code for 8051. Sometimes we need to access only
1 or 2 bits of the port instead of the entire 8-bits. 8051 provides the capability to access individual bits of
the ports.
While accessing a port in a single-bit manner, we use the syntax "SETB X. Y" where X is the port
number (0 to 3), and Y is a bit number (0 to 7) for data bits D0-D7 where D0 is the LSB and D7 is the
MSB. For example, "SETB P1.5" sets high bit 5 of port 1.
The following code shows how we can toggle the bit P1.2 continuously.
AGAIN:
SETB P1.2
ACALL DELAY
CLR P1.2
ACALL DELAY
SJMP AGAIN
Single-Bit Instructions

Instructions Function

SETB bit Set the bit (bit = 1)

CLR bit clear the bit (bit = 0)

CPL bit complement the bit (bit = NOT bit)

JB bit, target jump to target if bit = 1 (jump if bit)

JNB bit, jump to target if bit = 0 (jump if no bit)


target

JBC bit, jump to target if bit = 1, clear bit (jump if


target bit, then clear)

5.7 Programming 8051 Timers

Timers/Counters are used generally for


 Time reference
 Creating delay
 Wave form properties measurement
 Periodic interrupt generation
 Waveform generation

8051 has two timers, Timer 0 and Timer 1.

Timer in 8051 is used as timer, counter and baud rate generator. Timer always counts up
irrespective of whether it is used as timer, counter, or baud rate generator: Timer is always
incremented by the microcontroller. The time taken to count one digit up is based on master
clock frequency.
If Master CLK=12 MHz,
Timer Clock frequency=Master CLK/12=1MHz
Timer Clock Period=1microsecond
This indicates that one increment in count will take 1 micro second.
The two timers in 8051 share two SFRs (TMOD and TCON) which control the timers, and each
timer also has two SFRs dedicated solely to itself (TH0/TL0 and TH1/TL1).

The following are timer related SFRs in 8051.


SFR Name Description SFR
Address
TH0 Timer 0 High Byte 8Ch
TL0 Timer 0 Low Byte 8Ah
TH1 Timer 1 High Byte 8Dh
TL1 Timer 1 Low Byte 8Bh
TCON Timer Control 88h
TMOD Timer Mode 89h
TMOD Register

TCON Register
5.7. 1 Timer/ Counter Control Logic.

Fig 5- Counter Control Logic

5.7.2 Timer Modes

Timers can operate in four different modes. They are as follows


Timer Mode-0: In this mode, the timer is used as a 13-bit UP counters as follows.

Fig. Operation of Timer on Mode-0

The lower 5 bits of TLX and 8 bits of THX are used for the 13 bit count. Upper 3 bits of TLX are
ignored. When the counter rolls over from all 0's to all 1's, TFX flag is set and an interrupt is
generated. The input pulse is obtained from the previous stage. If TR1/0 bit is 1 and Gate bit is 0, the
counter continues counting up. If TR1/0 bit is 1 and Gate bit is 1, then the operation of the counter is
controlled by input. This mode is useful to measure the width of a given pulse fed to input.

TimerMode-1:This mode is similar to mode-0 except for the fact that the Timer operates in16-bit
mode.
Fig: Operation of Timer in Mode 1

Timer Mode-2: (Auto-Reload Mode): This is a 8 bit counter/timer operation. Counting is performed
in TLX while THX store a constant value. In this mode when the timer overflows i.e. TLX becomes
FFH, it is fed with the value stored in THX. For example if we load THX with 50H then the timer in
mode 2 will count from 50H to FFH. After that 50H is again reloaded. This mode is useful in
applications like fixed time sampling.

Fig: Operation of Timer in Mode 2

Timer Mode-3: Timer 1 in mode-3 simply holds its count. The effect is same as setting TR1=0. Timer0
in mode-3 establishes TL0 and TH0 as two separate counters.

Fig: Operation of Timer in Mode 3

Control bits TR1 and TF1 are used by Timer-0 (higher 8 bits) (TH0) in Mode-3 while TR0 and TF0
are available to Timer-0 lower 8 bits(TL0).
5.7.3 Programming 8051 Timers In Assembly
In order to program 8051 timers, it is important to know the calculation of initial count value to be
stored in the timer register. The calculations are as follows.
In any mode, Timer Clock period = 1/Timer Clock Frequency.
= 1/(Master Clock Frequency/12)

a. Mode 1 (16 bit timer/counter)


Value to be loaded in decimal = 65536 – (Delay required /Timer clock
period) Convert the answer into hexadecimal and load onto THx and TLx
register. (65536D = FFFFH+1)
b. Mode 0 (13 bit timer/counter)
Value to be loaded in decimal = 8192 – (Delay required/Timer clock
period) Convert the answer into hexadecimal and load onto THx and TLx
register. (8192D = 1FFFH+1)
c. Mode 2 (8 bit auto reload)
Value to be loaded in decimal = 256 – (Delay required/Timer clock period) Convert
the answer into hexadecimal and load onto THx register. Upon starting the timer this
value from THx will be reloaded to TLx register.
(256D = FFH+1)

5.7.4 Steps for programming timers in 8051

Mode 1:
 Load the TMOD value register indicating which timer (0 or 1) is to be used
and which timer mode is selected.
 Load registers TL and TH with initial count values.
 Start the timer by the instruction “SETB TR0” for timer 0 and “SETB TR1” for
timer1.
 Keep monitoring the timer flag (TF) with the “JNB TFx,target” instruction to see
if it is raised. Get out of the loop when TF becomeshigh.
 Stop the timer with the instructions “CLR TR0” or “CLR TR1”, for timer 0 and
timer 1, respectively.
 Clear the TF flag for the next round with the instruction “CLR TF0” or “CLR
TF1”,for timer 0 and timer 1,respectively.
 Go back to step 2 to load TH and TL again.
Mode 0:
The programming techniques mentioned here are also applicable to counter/timer
mode 0. The only difference is in the number of bits of the initialization value.
Mode 2:
 Load the TMOD value register indicating which timer (0 or 1) is to be used;
select timer mode2.
 Load TH register with the initial count value. As it is an 8-bit timer, the valid
range is from 00 toFFH.
 Start the timer.
 Keep monitoring the timer flag (TFx) with the “JNB TFx,target” instruction to see
if it is raised. Get out of the loop when TFx goeshigh.
 Clear the TFx flag.
 Go back to step 4, since mode 2 is auto-reload.

5.8 SERIAL PORT PROGRAMMING


5.8.1 Data communication
The 8051 microcontroller is parallel device that transfers eight bits of data simultaneously over eight
data lines to parallel I/O devices. Parallel data transfer over a long is very expensive. Hence, a serial
communication is widely used in long distance communication. In serial data communication, 8-bit
data is converted to serial bits using a parallel in serial out shift register and then it is transmitted over
a single data line. The data byte is always transmitted with least significant bit first.

5.8.2 Basics of Serial Data Communication,

Communication Links

1. Simplex communication link: In simplex transmission, the line is dedicated for transmission.
The transmitter sends and the receiver receives the data.
Transmitter Receiver

2. Half duplex communication link: In half duplex,the communication link can be used for either
transmission or reception. Data is transmitted in only one direction at a time.

Transmitter Receiver

Receiver Transmitter

3. Full duplex communication link: If the data is transmitted in both ways at the same time, it
is a full duplex i.e. transmission and reception can proceed simultaneously. This communication
link requires two wires for data, one for transmission and one for reception.
Transmitter Receiver

Receiver Transmitter

5.8.3 Types of Serial communication:


Serial data communication uses two types of communication.
1. Synchronous serial data communication: In this transmitter and receiver are synchronized. It
uses a common clock to synchronize the receiver and the transmitter. First the synch character is
sent and then the data is transmitted. This format is generally used for high speed transmission.
In Synchronous serial data communication a block of data is transmitted at a time.
Transmitter Sync Receiver

Data
Clock

2. Asynchronous Serial data transmission: In this, different clock sources are used for transmitter
and receiver. In this mode, data is transmitted with start and stop bits. A transmission begins with
start bit, followed by data and then stop bit. For error checking purpose parity bit is included just
prior to top bit. In Asynchronous serial data communication a single byte is transmitted at a time.
Transmitter Start D0 D1 D2 D3 D4 D5 D6 D7 D8 Stop Receiver

Data

Clock1 Clock2

Baud rate:
The rate at which the data is transmitted is called baud or transfer rate. The baud rate is the
reciprocal of the time to send one bit. In asynchronous transmission, baud rate is not equal to
number of bits per second. This is because; each byte is preceded by a start bit and followed by
parity and stop bit. For example, in synchronous transmission, if data is transmitted with 9600
baud, it means that 9600 bits are transmitted in one second. For bit transmission time = 1 second/
9600 = 0.104 ms.

5.8.4 8051 Serial communication

The 8051 supports a full duplex serial port.


Three special function registers support serial communication.
1. SBUF Register: Serial Buffer (SBUF) register is an 8-bit register. It has separate SBUF
registers for data transmission and for data reception. For a byte of data to be transferred
via the TXD line, it must be placed in SBUF register. Similarly, SBUF holds the 8-bit
data received by the RXD pin and read to accept the received data.
2. SCON register: The contents of the Serial Control (SCON) register are shown below.
This register contains mode selection bits, serial port interrupt bit (TI and RI) and also the
ninth data bit for transmission and reception (TB8 andRB8).
3. PCON register: The SMOD bit (bit 7) of PCON register controls the baud rate in
asynchronous mode transmission.

5.8.6 Serial Communication Modes


4. Mode0
In this mode serial port runs in synchronous mode. The data is transmitted and received
through RXD pin and TXD is used for clock output. In this mode the baud rate is 1/12 of
clock frequency.
5. Mode1
In this mode SBUF becomes a 10 bit full duplex transceiver. The ten bits are 1 start bit, 8
data bit and 1 stop bit. The interrupt flag TI/RI will be set once transmission or reception
is over. In this mode the baud rate is variable and is determined by the timer 1 overflow
rate. Baud rate = [2smod/32] x Timer 1 overflowRate
= [2smod/32] x [Oscillator Clock Frequency] / [12 x [256 –[TH1]]]
6. Mode2
This is similar to mode 1 except 11 bits are transmitted or received. The 11 bits are, 1
start bit, 8 data bit, a programmable 9th data bit, 1 stop bit.
Baudrate = [2smod/64] x Oscillator Clock Frequency
7. Mode3
This is similar to mode 2 except baud rate is calculated as in mode 1

5.8.6 Connectiontors-232
RS-232 Standards:
To allow compatibility among data communication equipment made by various manufactures, an
interfacing standard called RS232 was set by the Electronics Industries Association (EIA) in 1960.
Since the standard was set long before the advent of logic family, its input and output voltage levels
are not TTL compatible.
In RS232, a logic one (1) is represented by -3 to -25V and referred as MARK while logic zero (0) is
represented by +3 to +25V and referred as SPACE. For this reason to connect any RS232 to a
microcontroller system we must use voltage converters such as MAX232 to convert the TTL logic level
to RS232 voltage levels and vice-versa. MAX232 IC chips are commonly referred as line drivers.
In RS232 standard we use two types of connectors. DB9 connector or DB25 connector.

DB9 Male Connector DB25 Male Connector

The pin description of DB9 and DB25 Connectors are as follows

The 8051 connection to MAX232 is as follows

The 8051 has two pins that are used specifically for transferring and receiving data serially. These two
pins are called TXD, RXD. Pin 11 of the 8051 (P3.1) assigned to TXD and pin 10 (P3.0) is designated
as RXD. These pins TTL compatible; therefore they require line driver (MAX 232) to make them
RS232 compatible. MAX 232 converts RS232 voltage levels to TTL voltage levels and vice versa.
One advantage of the MAX232 is that it uses a +5V power source which is the same as the source
voltage for the 8051. The typical connection diagram between MAX 232 and 8051 is shown below.

Serial Communication Programming In Assembly And C.

Steps to programming the 8051 to transfer data serially


1. The TMOD register is loaded with the value 20H, indicating the use of the Timer 1 in mode 2
(8-bit auto reload) to set the baudrate.
2. The TH1 is loaded with one of the values in table 5.1 to set the baud rate for serial data transfer.
3. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8-bit data
is framed with start and stopbits.
4. TR1 is set to 1 start timer1.
5. TI is cleared by the “CLR TI”instruction.
6. The character byte to be transferred serially is written into the SBUFregister.
7. The TI flag bit is monitored with the use of the instruction JNB TI, target to see if the character
has been transferredcompletely.
8. To transfer the next character, go to step5.

Example1. Write a program for the 8051 to transfer letter ‘A’ serially at4800-baudrate, 8 bit data, 1
stop bit continuously.

ORG
0000H LJMP START ORG
0030H
START: MOVTMOD,#20H ; select timer 1 mode2
MOVTH1,#0FAH ; load count to get baud rate of
4800 MOVSCON,#50H ; initialize UART in mode2
; 8 bit data and 1 stop bit
SETBTR1 ; starttimer
AGAIN: MOVSBUF,#'A' ; load char ‘A’ inSBUF
BACK: JNB TI, BACK ; Check for transmit
interrupt flag CLRTI ; Clear transmit interrupt flag
SJMPAGAIN
END
Example2.Write a program for the 8051 to transfer the message ‘EARTH’ serially at 9600 baud,
8 bit data, 1 stop bit continuously.

ORG
0000H
LJMP
START
ORG 0030H
START: MOVTMOD,#20H ; select timer 1 mode2
MOVTH1,#0FDH ; load count to get reqd. baud rate of9600
MOVSCON,#50H ; initialise uart in mode2
; 8 bit data and 1 stopbit
SETBTR1 ; starttimer
LOOP: MOVA,#'E' ; load 1st letter ‘E’ in a
ACALLLOAD ; call load
subroutine MOVA, #'A' ; load 2nd letter ‘A’ in a
ACALLLOAD ; call load
subroutine MOVA,#'R' ; load 3rd letter ‘R’ in a
ACALLLOAD ; call load
subroutine MOVA,#'T' ; load 4th letter ‘T’ in a
ACALLLOAD ; call load
subroutine MOVA,#'H' ; load 4th letter ‘H’ in a
ACALLLOAD ; call loadsubroutine
SJMPLOOP ; repeatsteps

LOAD: MOV SBUF, A


HERE: JNB TI, HERE ; Check for transmit interrupt
flag CLRTI ; Clear transmit interrupt
flag RET

END
5.9 Interrupt Programming
5.9.1 Basics of Interrupts
During program execution if peripheral devices needs service from microcontroller, device will
generate interrupt and gets the service from microcontroller. When peripheral device activate the
interrupt signal, the processor branches to a program called interrupt service routine. After executing
the interrupt service routine the processor returns to the main program.

5.9.2 Steps taken by processor while processing an interrupt:


1. It completes the execution of the current instruction.
2. PSW is pushed to stack.
3. PC content is pushed to stack.
4. Interrupt flag is reset.
5. PC is loaded with ISR address.

ISR will always ends with RETI instruction. The execution of RETI instruction results in the following.

1. POP the current stack top to the PC.


2. POP the current stack top to PSW.

5.9.3 Classification of interrupts

1. External and internal interrupts.


External interrupts are those initiated by peripheral devices through the external pins of
the microcontroller.
Internal interrupts are those activated by the internal peripherals of the microcontroller
like timers, serial controller etc.)
2. Maskable and non-maskable interrupts.
The category of interrupts which can be disabled by the processor using program is called
maskable interrupts.
Non-maskable interrupts are those category by which the programmer cannot disable it
using program.
3. Vectored and non-vectored interrupt.
Starting address of the ISR is called interrupt vector. In vectored interrupts the starting
address is predefined. In non-vectored interrupts, the starting address is provided by the
peripheral as follows.
 Microcontroller receives an interrupt request from external device.
 Controller sends an acknowledgement (INTA) after completing the execution of
current instruction.
 The peripheral device sends the interrupt vector to the microcontroller.
8051 Interrupt structure
8051 has five interrupts. They are maskable and vectored interrupts. Out of these five,
two are external interrupt and three are internal interrupts.

Interrupt source Type Vector address Priority


External interrupt 0 External 0003 Highest
Timer 0 interrupt Internal 000B
External interrupt 1 External 0013
Timer 1 interrupt Internal 001B
Serial interrupt Internal 0023 Lowest

8051 makes use of two registers to deal with interrupts.

IE Register
This is an 8 bit register used for enabling or disabling the interrupts. The structure of IE register
is shown below.

IP Register.
This is an 8 bit register used for setting the priority of the interrupts.
UNIVERSITY QUESTIONS RELATED TO THE TOPIC
Two-mark questions
Q-1. Define the term bit, byte, nibble, and word.
Q-2. What is the difference between microprocessor and microcomputer?
Q-3. Draw the block diagram of Microcomputer.
Q-4. What is the heart of computer system?
Q-5. What is Microprocessor?

Five-mark questions
Q-6. Explain the evolution of Microprocessor.
Q-7. Give the difference between machine language and assembly language.
Q-8. What is the Difference between RISC and CISC architecture?
Q-9. What is the difference between Von-Newman and Harvard architecture?
Q-10.Explain the characteristics of Microprocessor.

Ten-mark questions
Q-11. Explain the five applications of Microprocessor.

GATE questions

Q-12.In a microcomputer, wait states are used to


Q-13.In a microprocessor, when a CPU is interrupted, it
Q-14.In an 8085μP system, the RST instruction will cause an interrupt

5.10 INTERFACING

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.
Interfacing is the process of connecting devices together so that they can exchange the
information and that proves to be easier to write the programs. There are different type of input
and output devices as for our requirement such as LEDs, LCDs, 7segment, keypad, motors and
other devices.
Here is given some important modules interfaced with microcontroller 8051.
5.11 LCD & KEYBOARD INTERFACING

LCD stands for liquid crystal display which can display the characters per line. Here 16 by 2
LCD display can display 16 characters per line and there are 2 lines. In this LCD each character
is displayed in 5*7 pixel matrix.

5.11.1 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.
a. The command/instruction register stores the command instructions given to the
LCD. A command is an instruction which is given to the LCD that perform a set
of predefined tasks like initializing, clearing the screen, setting the cursor posing,
controlling display etc.

b. 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.

Operation of LCD is controlled by two commands. When RS=0, R/W=1 it reads the data and
when RS=1, R/W=0, it writes (print) the data.

LCD uses following command codes:


LCD Display Commands

Circuit Diagram:

LCD Interfacing to Microcontroller

Source code:
#include<reg51.h>
#define kam P0

sbit rs= P2^0;


sbit rw= P2^1;
sbit en= P2^2;

void lcd_initi();
void lcd_dat(unsigned char );
void lcd_cmd (unsigned char );
void delay(unsigned int );
void display(unsigned char *s, unsigned char r);
void main()
{

lcd_initi();
lcd_cmd(0x80);
delay(100);
display(“EDGEFX TECHLNGS”, 15);
lcd_cmd(0xc0);
display(“KITS & SOLTIONS”,15);
while(1);
}

void display(unsigned char *s, unsigned char r)


{
unsigned int w;
for(w=0;w<r;w++)
{
lcd_dat(s[w]);
}
}

void lcd_initi()
{
lcd_cmd(0x01);
delay(100);
lcd_cmd(0x38);
delay(100);
lcd_cmd(0x06);
delay(100);
lcd_cmd(0x0c);
delay(100);
}
void lcd_dat(unsigned char dat)
{
kam = dat;
rs=1;
rw=0;

en=1;
delay(100);
en=0;
}
void lcd_cmd(unsigned char cmd)
{
kam=cmd;
rs=0;
rw=0;

en=1;
delay(100);
en=0;
}
void delay( unsigned int n)
{

unsigned int a;
for(a=0;a<n;a++);
}

5.11.2 Keyboard Interfacing

Description:
Keyboard is a widely used input device with lot of applications such as telephone, computer,
ATM, electronic lock etc. A keypad is used to take input from the user for further processing.
Here a 4 by 3 matrix keypad consisting of switches arranged in rows and columns is interfaced
to the microcontroller. A 16 by 2 LCD is also interfaced for displaying the output.
The interfacing concept of keypad is very simple. Every number of keypad is assigned two
unique parameters that are row and column (R, C). Hence every time a key is pressed the
number is identifying by detecting the row and column numbers of keypad.

Keypad Internal Diagram

Initially all the rows are set to zero (‘0’) by the controller and columns are scanned to check if
any key is pressed. In case of no key is pressed the output of all columns will be high (‘1’).

Circuit Diagram

Matrix keypad interfacing to 8051

Source Code:
#include<reg51.h>
#define kam P0
sbit rs=P2^0;
sbit rw=P2^1;
sbit en=P2^2;
sbit c1=P1^4;
sbit c2=P1^5;
sbit c3=P1^6;
sbit r1=P1^0;
sbit r2=P1^1;
sbit r3=P1^2;
sbit r4=P1^3;
void lcd_initi();
void lcd_dat(unsigned char );
void lcd_cmd (unsigned char );
void delay(unsigned int );
void display(unsigned char *s, unsigned char r);

void main()
{
lcd_initi();
lcd_cmd(0x80);
delay(100);
display(“0987654321”, 10);
while(1);
}

void display(unsigned char *s, unsigned char r)


{

unsigned int w;
for(w=0;w<r;w++)
{

lcd_dat(s[w]);
}
}
void lcd_initi()
{
lcd_cmd(0x01);
delay(100);
lcd_cmd(0x38);
delay(100);
lcd_cmd(0x06);
delay(100);
lcd_cmd(0x0c);
delay(100);
}

void lcd_dat(unsigned char dat)


{
kam = dat;
rs=1;
rw=0;
en=1;
delay(100);
en=0;
}
void lcd_cmd(unsigned char cmd)
{
kam=cmd;
rs=0;
rw=0;

en=1;
delay(100);
en=0;

}
void delay( unsigned int n)
{

unsigned int a;
for(a=0;a<n;a++);
}
}

5.12 ADC, DAC & SENSOR INTERFACING

5.12.1 What is an ADC?


An analog to digital converter or ADC, as the name suggests, converts an analog signal to a
digital signal. An analog signal has a continuously changing amplitude with respect to time. A
digital signal, on the contrary, is a stream of 0s and 1s. An ADC maps analog signals to their
binary equivalents. To do this, ADCs use various methods like Flash conversion, slope
integration, or successive approximation.
To understand the ADC in a better way, let us look at an example. Let us say we have an input
signal which varies from 0 to 8 volt, and we use a 3-bit ADC to convert this signal to binary
data. A 3-bit ADC can represent 2^3 or 8 different voltage levels using 3 bits of data. How
convenient! In this case, the ADC maps the data in the following manner.

Input voltage Binary equivalent

0-1 volt 000B

1-2 volt 001B

2-3volt 010B

3-4 volt 011B


4-5 volt 100B

5-6 volt 101B

6-7 volt 110B

7-8 volt 111B

If you look at the table above, you will understand how the ADC maps analog data to digital
values. In the case mentioned above, we can see that the tiniest change we can detect is that of 1
volt. If the change is smaller than 1 volt, the ADC can’t detect it. This minimum change that an
ADC can detect is known as the step size of the ADC. To calculate it, we can use the formula:
Step size=Vmax-Vmin/2n (where n is the number of bits(resolution) of an ADC)

The step size of an ADC is inversely proportional to the number of bits of an ADC. So using an
ADC with higher bits can detect smaller changes, but this increases the cost of production. Due
to this reason, most on-chip ADCs’ have an 8-bit/10-bit resolution. Given below is the resolution
vs. step size for various configurations with a range of 0-5v input signal.

Number of bits Number of steps step size(mV)

8 256 5/256=19.53

10 1024 5/1024=4.88

12 4096 5/4096=1.2

16 65536 0.076 (precise conversion)

Where is an Analog-to-Digital Converter (ADC) used?


ADCs’ are everywhere. You are using one when you talk on the phone or when you listen to
music. An ADC is required whenever a computer needs to understand physical parameters like
sound, pressure, velocity using a transducer.
Are external ADCs still used?
With the advancement in technology, most modern microcontrollers have built-in ADCs. You
might wonder then as to what is the point of learning how to interface an external ADC.
Well, for starters, it will help you understand how an ADC works with a microcontroller.
Additionally, some IoT applications require an external ADC as they provide better accuracy
and higher speeds compared to internal ADCs.
Now that we have a basic idea of what an ADC is and where they are used, we will dive into
interfacing the 0808 ADC with 8051.
ADC 0808
The ADC 0808 is a popular 8-bit ADC with a step size of 19.53 millivolts. It does not have an
internal clock. Therefore, it requires a clock signal from an external source. It has eight input
pins, but only one of them can be selected at a time because it has eight digital output pins. It
uses the principle of successive approximation for calculating digital values, which is very
accurate for performing 8-bit analog to digital conversions. Let us look at the pin description to
get more insights into ADC 0808.

Input pins (INT0-INT7)


The ADC 0808 has eight input analog pins. These pins are multiplexed together, and only one of
them can be selected using three select lines.
Select lines and ALE
It has three select lines, namely A, B, and C, that are used to select the desired input lines. The
ALE pin also needs to be activated by a low to high pulse to select a particular input. The input
lines are selected as follows:

A B C Selected analog channel ALE pin

0 0 0 INT0 Low to High pulse

0 0 1 INT1 Low to High pulse

0 1 0 INT2 Low to High pulse

0 1 1 INT3 Low to High pulse

1 0 0 INT4 Low to High pulse

1 0 1 INT5 Low to High pulse

1 1 0 INT6 Low to High pulse

1 1 1 INT7 Low to High pulse

Output pins (D0-D7)


The ADC has eight output pins that give the binary equivalent of a given analog value.
VCC and Ground
These two pins are used to provide the required voltage to power the microcontroller. In most
cases, the ADC uses 5V DC to power up.
Clock
As mentioned earlier, the 0808 does not have an internal clock and needs an external clock
signal to operate. It uses a clock frequency of 20 Mhz, and using this clock frequency it can
perform one conversion in 100 microseconds.
VREF (+) and VREF (-)
These two pins are used to provide the upper and the lower limit of voltages which determine the
step size for the conversion. Here Vref(+) has a higher voltage, and Vref(-) has the lower
voltage. If Vref(+) has an input voltage 5v and Vref(-) has a voltage of 0v then the step size will
be 5v-0v/28= 15.53 mv.
Start conversion
This pin is used to tell the ADC to start the conversion. When the ADC receives a low to high
pulse on this pin, it starts converting the analog voltage on the selected pin to its 8-bit digital
equivalent.
End of conversion
Once the conversion is complete, the ADC sends low to high signal to tell a microcontroller that
the conversion is complete and that it can extract the data from the 8 data pins.
Output enable
This pin is used to extract the data from the ADC. A microcontroller sends a low to high pulse to
the ADC to extract the data from its data buffers
Components required

 8051 Microcontroller – AT89C51/Any other compatible variants


 ADC 0808
 LEDs (forward voltage 2.2v)
 5V DC Power Supply
 12Mhz Oscillator Crystal
 Capacitor 22pF (2 units) and 10uF (1 unit)
 Resistor/Pot 10KΩ
 Connecting wires – As per the requirement

Interfacing 8051 with 0808


Most modern microcontrollers with 8051 IP cores have an inbuilt ADC. Older versions of 8051
like the MCS-51 and A789C51 do not have an on-chip ADC. Therefore to connect these
microcontrollers to analog sensors like temperature sensors, the microcontroller needs to be
hooked to an ADC. It converts the analog values to digital values, which the microcontroller can
process and understand. Here is how we can interface the 8051 with 0808.
To interface the ADC to 8051, follow these steps. In our case, we are using Proteus as the
simulation software and the AT89C51 microcontroller.

 Connect the oscillator circuit to pins 19 and 20. This includes a crystal oscillator and two
capacitors of 22uF each. Connect them to the pins, as shown in the diagram.
 Connect one end of the capacitor to the EA’ pin and the other to the resister. Connect this
resistor to the RST pin, as shown in the diagram.
 We are using port 1 as the input port, so we have connected the output ports of the ADC
to port 1.
 As mentioned earlier, the 0808 does not have an internal clock; therefore, we have to
connect an external clock. Connect the external clock to pin 10.
 Connect Vref (+) to a voltage source according to the step size you need.
 Ground Vref (-) and connect the analog sensor to any one of the analog input pins on the
ADC. We have connected a variable resistor to INT2 for getting a variable voltage at the
pin.
 Connect ADD A, ADD B, ADD C, and ALE pins to the microcontroller for selecting the
input analog port. We have connected ADD A- P2.0; ADD B- P2.1; ADD C- P2.2 and
the ALE pin to port 2.4.
 Connect the control pins Start, OE, and Start to the microcontroller. These pins are
connected as follows in our case Start-Port-2.6; OE-Port-2.5 and EOC-Port-2.7.

With this, you have successfully interfaced the 8051 to the ADC. Now let us look at the logic to
use the ADC with the microcontroller.
5.12.2 Logic to communicate between 8051 and ADC 0808
Several control signals need to be sent to the ADC to extract the required data from it.

 Step 1: Set the port you connected to the output lines of the ADC as an input port. You
can learn more about the Ports in 8051 here.
 Step 2: Make the Port connected to EOC pin high. The reason for doing this is that the
ADC sends a high to low signal when the conversion of data is complete. So this line
needs to be high so that the microcontroller can detect the change.
 Step 3: Clear the data lines which are connected to pins ALE, START, and OE as all
these pins require a Low to High pulse to get activated.
 Step 4: Select the data lines according to the input port you want to select. To do this,
select the data lines and send a High to Low pulse at the ALE pin to select the address.
 Step 5: Now that we have selected the analog input pin, we can tell the ADC to start the
conversion by sending a pulse to the START pin.
 Step 6: Wait for the High to low signal by polling the EOC pin.
 Step 7: Wait for the signal to get high again.
 Step 8: Extract the converted data by sending a High to low signal to the OE pin.

Assembly language program to interface ADC 0808 with 8051


Here is how the assembly code for the same looks like
ORG 0000H; Starting address
MOV P1,#0FFH; Makes port 1 input port
SETB P2.7; Makes EOC pin high
CLR P2.4; Clears ALE pin
CLR P2.6; Clears Start pin
CLR P2.5; Clears OE pin
BACK: CLR P2.2; Clears ADD C
SETB P2.1; Sets ADD B
CLR P2.0; Clears ADD A (this selects the second address line)
ACALL DELAY
SETB P2.4; Sets ALE high
ACALL DELAY
SETB P2.6; sends a command to start conversion
ACALL DELAY
CLR P2.4; makes ALE low
CLR P2.6; makes Start pin low
HERE: JB P2.7,HERE; waits for low pulse at EOC
HERE1: JNB P2.7,HERE1; waits for low pulse to finish
SETB P2.5; enables OE pin to extract data from ADC
ACALL DELAY
MOV A,P1; moves acquired data to accumulator
CLR P2.5; clears OE
SJMP BACK; repeatedly gets data from ADC
DELAY: MOV R3,#50
HERE2: MOV R4,#255
HERE3: DJNZ R4,HERE3
DJNZ R3,HERE2
RET
END

Now that we have a basic understanding of how to interface an ADC with the 8051, let us look
at an example in which we connect LEDs to 8051 to see the data conversion.
C program to interface ADC 0808 with 8051

Seeing data conversion using LEDs


To see the data conversion of an ADC, we will extract the data using the code shown above.
Then we will transfer the binary data to port 3 to see the data.
The C code for the same is given below:
#include <reg51.h>
sbit ALE = P2^4;
sbit OE = P2^5;
sbit SC = P2^6;
sbit EOC = P2^7;
sbit ADDR_A = P2^0;
sbit ADDR_B = P2^1;
sbit ADDR_C = P2^2;
sfr MYDATA =P1;
sfr SENDDATA =P3;
void MSDelay(unsighned int) // Function to generate time delay
{
unsighned int i,j;
for(i=0;i<delay;i++)
for(j=0;j<1275;j++);
}
void main()
{
unsigned char value;
MYDATA = 0xFF;
EOC = 1;
ALE = 0;
OE = 0;
SC = 0;
while(1)
{
ADDR_C = 0;
ADDR_B = 0;
ADDR_A = 0;
MSDelay(1);
ALE = 1;
MSDelay(1);
SC = 1;
MSDelay(1);
ALE = 0;
SC = 0;
while(EOC==1);
while(EOC==0);
OE=1;
MSDelay(1);
value = MYDATA;
SENDDATA = value;
OE = 0 ;
}
}

5.12.3 Interfacing With Digital To Analog Converter

The Digital to Analog converter (DAC) is a device, that is widely used for converting digital
pulses to analog signals. There are two methods of converting digital signals to analog signals.
These two methods are binary weighted method and R/2R ladder method. In this article we will
use the MC1408 (DAC0808) Digital to Analog Converter. This chip uses R/2R ladder method.
This method can achieve a much higher degree of precision. DACs are judged by its resolution.
The resolution is a function of the number of binary inputs. The most common input counts are
8, 10, 12 etc. Number of data inputs decides the resolution of DAC. So if there are n digital
input pin, there are 2n analog levels. So 8 input DAC has 256 discrete voltage levels.
The MC1408 DAC (or DAC0808)
In this chip the digital inputs are converted to current. The output current is known as Iout by
connecting a resistor to the output to convert into voltage. The total current provided by
the Iout pin is basically a function of the binary numbers at the input pins D0 - D7 (D0 is the LSB
and D7 is the MSB) of DAC0808 and the reference current Iref.
The Iref is the input current. This must be provided into the pin 14. Generally 2.0mA is used as
Iref
We connect the Iout pin to the resistor to convert the current to voltage. But in real life it may
cause inaccuracy since the input resistance of the load will also affect the output voltage. So
practically Iref current input is isolated by connecting it to an Op-Amp with Rf = 5KΩ as
feedback resistor. The feedback resistor value can be changed as per requirement.
Generating Sinewave using DAC and 8051 Microcontroller
For generating sinewave, at first we need a look-up table to represent the magnitude of the sine
value of angles between 0° to 360°. The sine function varies from -1 to +1. In the table only
integer values are applicable for DAC input. In this example we will consider 30° increments
and calculate the values from degree to DAC input. We are assuming full-scale voltage of 10V
for DAC output. We can follow this formula to get the voltage ranges.
Vout = 5V + (5 ×sinθ)
Let us see the lookup table according to the angle and other parameters for DAC.
Angle(in sinθ Vout (Voltage Values sent
θ) Magnitude) to DAC

0 0 5 128

30 0.5 7.5 192

60 0.866 9.33 238

90 1.0 10 255

120 0.866 9.33 238

150 0.5 7.5 192

180 0 5 128

210 -0.5 2.5 64

240 -0.866 0.669 17

270 -1.0 0 0

300 -0.866 0.669 17

330 -0.5 2.5 64

360 0 5 128

Circuit Diagram −
Source Code
#include<reg51.h>
sfr DAC = 0x80; //Port P0 address
void main(){
int sin_value[12] = {128,192,238,255,238,192,128,64,17,0,17,64};
int i;
while(1){
//infinite loop for LED blinking
for(i = 0; i<12; i++){
DAC = sin_value[i];
}
}
}

Output
The output will look like this −
5.13 Sensor Interfacing with 8051

Sensors are the electro-mechanical devices which converts the physical world parameters (air,
wind, speed, light, color..) into its corresponding electrical signals. Using sensors many
developments is been done. Mostly all the micro controllers are interfaced with sensors for a
particular task.

For example lets consider a visitor counter.

This is built around the IR-sensor and 8051 MCU and a 7-segment LED display, this will. Here
the IR-sensor detects the change in the variations in the light and gives a ON/OFF pulse. These
pulses are fed to the MCU and counts the number of pulses. Displays the count on 7-segment
LED display.

5.13.1 Classifications of Sensors:


Sensors are classified into two types they are,

 Digital sensors.
 Analog Sensors.
Digital sensors:
This kind of sensors gives the ON/OFF pulses at the output side, which means 0V and 5V.
Basically, all the digital sensors are Analog in nature but in the back end these are interfaced to
comparators.
Examples:

 IR-Sensor.
 Ultrasonic sensor.
 PIR sensor.
 Proximity sensors.
 Metal detectors.

Many more sensors are getting manufactured as per the requirements of users.
Analog Sensors:
These are not like digital sensors that is they could not give ON/OFF signals as output
instead they will produce a sinusoidal wave as output. These signals need some analog to digital
converters (ADC) for interfacing with MCU. Now a days mostly all the MCUs has its own ADC
channels, except for 8051 families there is no ADC block internally so analog sensors are to be
interfaced with ADC for 8051.
Examples:

 Current sensor.
 MEMS
 Humidity sensor
 Temperature sensor etc..

Caution:
While interfacing a sensor to 8051 the power supply should not exceed the ratings of the
sensor, this may damage the sensor.
“Note: Before using any sensor calibrate and check it, if it is working properly or not.”
Source code:

Digtial sensor interfacing with 8051:


As in the previous code lets do a simple visitor counter, using IR-sensor.
#include <regx51.h>
sbit sen = P1^0;
void delay(int time){
int i,j;
for(i=0;i<=time;i++)
for(j=0;j<=1275;j++);
}
void main()
{
int c,d,count;
char num[]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x98};
sen = 0;
sen = 1;
P2=P3=0x00;
P2=0xC0;
P3=0xC0;
c=0;
d=0;
while(1)
{
while(sen==0)
{
if(d>=10)
d=0;
P2 = num[d++];
count = 0;
c=0;
delay(1);
while(count++>=0)
{
P3=num[c++];
delay(45);
if(count>=10)
break;
while(sen==1);
delay(10);
}
}
}
}
Fig a: 8051 circuit diagram interfacing with IR sensor

5.14 STEPPER MOTOR AND WAVEFORM GENERATION.

5.14.1 Stepper motor interfacing circuit

Unipolar Stepper Motor

A stepper motor is one of the most commonly used motor for precise angular movement. The
advantage of using a stepper motor is that the angular position of the motor can be controlled
without any feedback mechanism. The stepper motors are widely used in industrial and
commercial applications. They are also commonly used as in drive systems such as robots,
washing machines etc.

Fig- Bipolar Stepper Motor

Stepper motors can be unipolar or bipolar and here we are using unipolar stepper motor. The
unipolar stepper motor consists of six wires out of which four are connected to coil of the motor
and two are common wires. Each common wire is connected to a voltage source and remaining
wires are connected to the microcontroller.

Circuit Diagram:

5.14.2 Stepper motor interfacing circuit

Source code:
#include<reg51.h>
sbit a=P3^0;
sbit b=P3^1;
sbit c=P3^2;
sbit d=P3^3;

void delay();

void main()
{

while(1)
{

a=0;
b=1;
c=1;
d=1;
delay();
a=1;
b=0;
c=1;
d=1;
delay();
a=1;
b=1;
c=0;
d=1;
delay();
a=1;
b=1;
c=1;
d=0;

}
}

void delay()
{

unsigned char i,j,k;


for(i=0;i<6;i++)
for(j=0;j<255;j++)
for(k=0;k<255;k++);

5.15 UNIVERSITY QUESTIONS RELATED TO THE TOPIC


Two-mark questions
Q-1. What do you mean by interfacing?
Q-2. Define baud rate.
Q-3. Enlist assembler directives.
Q-4. Write steps for running a program.

Five-mark questions
Q-5. Explain in detail the assembler directives in 8051 along with suitable examples.
Q-6. What do you mean by logical operation in 8051?
Q-7. Explain the data manipulation instructions along with examples.
Q-8. Explain subroutine in 8051.
Q-9. Different between call and jump instruction by using suitable examples.

Ten -mark questions


Q-10. Explain timer in 8051 along with timers modes used in 8051.
Q-11. How interrupt controller works in 8051.
Q-12. Explain in detail IO programming in 8051.
Q-13. Draw and explain 4x4 matrix keyboard interfacing with 8051.
Q-14. What is sensor? What are different types of sensors? Explain how sensor is interfaced
with 8051?
Q-15. Explain LCD interfacing with 8051 microcontroller.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy