8051 Microcontroller


The 8051 Microcontroller was designed in the 1980s by Intel. Its foundation was on Harvard Architecture and was developed principally for bringing into play in Embedded Systems. At first, it was created by means of NMOS technology but as NMOS technology needs more power to function therefore Intel re-intended Microcontroller 8051 employing CMOS technology and a new edition came into existence with a letter ‘C’ in the title name, for illustration: 80C51. These most modern Microcontrollers need a fewer amount of power to function in comparison to their forerunners.

  • An embedded system is a computer system designed to perform one or a few dedicated functions often with real-time computing constraints. An embedded system means the combination of hardware & software.
  • The 8051 microcontrollers are designed by Intel in 1981. It is an 8 – bit Microcontroller i.e. it can read, write and process 8 – bit Data. There are a bunch of manufacturers like Atmel, NXP, & TI, etc. who manufacture their own versions of 8051 Microcontroller by getting the patent license from Intel. It is built with 40 pins DIP (dual inline package), 4kb of ROM storage, and 128 bytes of RAM storage, 2 16-bit timers. It consists of are four parallel 8-bit ports, which are programmable as well as addressable as per the requirement.

Microcontroller vs Microprocessor

General –Purpose microprocessorsCPU (Microprocessor)
The microprocessor has NO –RAMThe microcontroller has on-chip RAM
The microprocessor has NO – ROMThe microcontroller has on-chip ROM
The microprocessor has No I/O PortThe microcontroller has on-chip I/O Ports
The microprocessor has No on-chip timerThe microcontroller has on-chip Timer
Microprocessor and Microcontroller Difference

ADC and other peripherals

8051 Microcontroller Architecture
8051 Microcontroller Architecture

8051 Microcontroller Features

  • The 8051 is an 8-bit processor
  • The CPU can work on only 8 bits of data at the time
  • It has128 bytes of RAM
  • It has 4k bytes of on-chip ROM
  • It has Two timers
  • It has one serial port
  • It has Four I/O Ports, each 8 bits wide
  • It has 6 interrupt sources
8051 Microcontroller  address data
8051 address data
  • The 8051 microcontroller is a subset of 8052 microcontrollers.
  • The 8031 microcontroller is a ROM-less 8051 microcontroller.
  • Add external ROM to 8031 microcontrollers to use in an embedded system.
  • By using the external ROM you lose 2 ports and leave only 2 ports for I/O operations.
ROM(on-chip program space in bytes)4K8K0K
RAM (bytes)128256128
I/O pins323232
Serial port111
Interrupt sources686
Difference Between 8051 8052 8053 Microcontroller

8051 Microcontroller Assembly Language Programming


  • The register is used to storing 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 registers are 8 – bit registers.
  • There is an only data type, 8bits.
  • The 8 bits of a register are shown from MSB D7 to the LSB D0
8051 Microcontroller register 8-bit data
8051 Microcontroller register 8-bit data

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 of 8051 Microcontrollers are:                                                                                                                                                                                         

  • An Accumulator (ACC) register for all arithmetic and logical instructions.
  • B,R0,R1,R2,R3,R4,R5,R6,R7 registers for any opcode and operand storage.
  • DPTR (data pointer),and PC (program counter)
8051 Microcontroller MCU Registers
8051 MCU Registers


  • The instruction tells the CPU to move ( in reality, copy) the sources operand to the destination operand

MOV A,#55H ;load value 55H into reg. A

MOV R0,A ;copy contents of A into R0;(now A=R0=55H)

MOV R1,A ;copy contents of A into R1;(now A=R0=R1=55H)

MOV R2,A ;copy contents of A into R2;(now A=R0=R1=R2=55H)

MOV R3,#95H ;load value 95H into R3;(now R3=95H)

MOV A,R3 ;copy contents of R3 into A;now A=R3=95H


Add A, source; ADD the source operand; to the accumulator

  • The ADD instruction tells the CPU to add the source byte to register A and put the result in register A
  • The source operand can be either a register or immediate data, but the destination must always register A
  • ADD R4, A” and “ADD, R2,#12H” are invalid since A must be the destination of any arithmetic operation

MOV A, #25H ;load 25H into A

MOV R2, #34H ;load 34H into R2

ADD A, R2 ;add R2 to Accumulator ;(A = A + R2)

ADD A, #34H ;add the second ;operand 34H to A

8051 Microcontroller Program Counter

The Program counter points to the address of the next instruction to be executed

  • As CPU fetches the opcode from the program ROM, the program counter is increased 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

8051 Microcontroller Program status word (PSW )Register

The 8051 Microcontroller program status word register, also referred to as the flag register, is an 8-bit register

  • Only 6 bits are used These four are CY (carry), AC (auxiliary carry), P(parity), and OV(overflow)
  • They are called conditional flags, meaning that they indicate some conditions  that resulted after  an instruction was executed
  • The PSW3 and PSW4 are designed as RS0 and RS1 and are used to change the bank
  • The two unused bits are user-definable        
8051 Microcontroller MCU PSW Register
8051 MCU PSW Register
Carry FlagPSWDescription
CYPEW.7Carry flag
ACPSW.6Auxiliary Carry the flag
– –PSW.5Available to the user for general purpose
RS1PSW.4Register bank selector bit 1.
RS0PSW.3Register bank selector bit 0.
OVPSW.2Overflow flag
– –PSW.1User-definable
RS1 RS0Register BankAddress


This flag is set whenever there is a carryout from the D7 bit. This flag bit affected after an 8-bit addition and subtraction.


If there is a carry from D3 to D4 during an  ADD or SUB operation, this bit is set, otherwise, it is cleared.

P The parity flag

The parity flag reflects the number of 1s in the A (accumulator) register only .if the A register contains an odd number of 1s, then P=1; Otherwise P=0.

OV The Overflow Flag

This flag bit is set whenever the result of a signed number operation s too large, causing the high-order bit to overflow into the sign bit.

8051 Microcontroller Register Banks and Stack

  • There are 128 bytes of RAM in the 8051 Microcontroller
  • Assigned addresses 00 to 7FH
  • The 128 bytes are divided into three different groups as follows
  1.  A total of 32 bytes from locations 00 to 1F hex are set aside for register banks and the stack.
  2.  A total of 16 bytes from locations 20H to 2FH are set aside for bit-addressable read/write memory
  3. A total of 80 bytes from locations 30H to 7FH are used to reading and write storage, called scratchpad
8051 Microcontroller Register Bank
8051 Register Bank
  • These 32 bytes are divided into 4 banks of registers in which each bank has 8 Registers, R0 – R7
  • RAM location from 0 to 7 are set aside for bank 0 of R0-R7 where R0 is RAM location 0, R1 is RAM location 1, R2 is RAM location 2, and so on, until memory location 7 which belongs to R7 of bank 0
  • It is much easier to refer to these RAM location with names such as R0, R1 and so on, than by their memory locations

Register bank 0 is the default when 8051 Microcontroller is powered up

8051 Microcontroller register bank and ARM address
8051 register bank and ARM address

We can switch to other banks by use of the PSW register in 8051 Microcontroller

  • Bits D4 to D3 of the PSW are used to select the desired register bank
  • Use the bit –addressable instructions SETB and CLR to access PSW.4 and PSW.3
8051 Microcontroller power bank
8051 power bank


  • MOV R0 ,#99H   (load R0 with 99H)
  • MOV R1 ,#85H  (load  R1 with 85H)


  • MOV 00,  #99H  (RAM location 00H has 99H)
  • MOV 01, #85H (RAM location 01H has 85H)


  • SETB  PSW.4  (select bank 2)
  • MOV R0 , #99H  (RAM location 10H has 99H)
  • MOV R1 , #85H (RAM location 11H has 85H)

JUMP, LOOP and CALL Instruction of 8051 Microcontroller

Looping Control in 8051 Microcontroller

Repeating a sequence of instructions a certain number of times is called a loop

  • Loop action is performed byDJNZ reg, Lable 1
  • 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 the loop, the register is loaded with the counter for the number of repetitions
  • The counter can be R0-R7 or RAM location

This program adds  value 3 to the ACC ten times

MOV  A ,#0   (A=0, clear ACC)

MOV R2, #10   (load counter R2=10)

AGAIN: ADD A, #03   (add 03 to ACC)

DJNZ R2, AGAIN   (repeat until R2=0, 10 times)

MOV R5, A   (save A in R5)

CONDITIONAL JUMPS in 8051 Microcontroller

Jump only if a certain condition is met

JZ label ;jump if A = 0

MOV A , R0 ;( A = R0 )

JZ OVER ;( Jump if A = 0 )

MOV A, R1 ;(A=R1)

JZ OVER ;( jump if A =0 )


Determine if R5 contains the value 0. if so, put 55H in it.

MOV A, R5  ( copy R5 to A )

JNZ  NEXT  ( jump if A is not Zero )

MOV  R5 # 55H


JNC label ( jump if no carry, CY=0 )

  • If CY = 0, the CPU starts to fetch and execute an instruction from the address of the label
  • If CY = 1, it will not jump but will execute the next instruction below JNC

Find the sum of values 79H, F5H, E2H. Put the sum in registers R0 (low byte) and R5 (high byte).

MOV A ,#0 ;( A=0 )

MOV R5, A ;( clear R5 )

ADD A, #79H ;(A=0+79H=79H)

JNC N_1 ;(if CY=0 ,add next number)

INC R5 ;(if CY=1,increment R5)

N_1 : ADD A , #0F5H ;(A=79+F5=6E and CY=1)

JNC N_2 ;(jump if CY=0)

INC R5 ;(if CY=1,increment R5,(R5=1))

N_2 : ADD A ,#0E2H ;(A=6E+E2=50 and CY=1)

JNC OVER ;(jump if CY=0)

JNC R5 ;(if CY=1,increment 5)

OVER : MOV R0 , A ;(now R0=50H,and R5=02)

8051 Microcontroller conditional jump instruction
8051 conditional jump instruction

All conditional  jumps are short jumps:

  • The address of the target must within -128 to +127 bytes of the contents of PC .

UNCONDITIONAL JUMP in 8051 Microcontroller

The unconditional jump is a jump in which control is transferred unconditionally  to the target location

LjMP(long jump)

  •  3-byte instruction
  • The first byte is the opcode
  • Second and third bytes represent the 16-bit target address
  • Any memory location from 0000 to FFFFH

SJMP (short jump)

  • 2-byte instruction
  • The first byte is the opcode
  • The second byte is the relative target address
  • – 00 to FFH(Forward +127 and backward -128 bytes from the current PC)

CALL Instruction in 8051 Microcontroller

The call instruction is used to call a subroutine

  • Subroutines are often used to perform tasks that need to be performed frequently
  • This makes a program more structured in addition to saving memory space

LCALL (long call)

  • 3 – byte instruction
  • The first byte is the opcode
  • Second and third bytes are used for the address of target subroutine

– the subroutine is located anywhere within 64K byte address space

ACALL (absolute call)

  • 2- byte instruction.
  • 11 bits are used for address within the 2K-bytes range.

When a subroutine is called, control is transferred to that subroutine, the processer

  • Saves on the stack the address of the instruction immediately below the LCALL.
  • Begins to fetch instructions from the new location.

After finishing execution of the subroutine

  • The instruction RET transfers control back to the caller
  • Every subroutine needs RET as the last instruction

The  only difference between ACALL and LCALL is

  • The target address for LCALL can be anywhere within the 64K byte address
  • The target address of ACALL must be within a 2 K – byte range

The use of ACALL instead of LCALL can save a number of bytes a program ROM space

Addressing Modes of 8051 Microcontroller

The CPU can access data in various ways, which are called addressing modes

  • Immediate
  • Register
  • Direct
  • Register indirect
  • Indexed

Immediate Addressing Mode of 8051 Microcontroller

The source operand is a constant

  • The immediate data must be preceded by the pound sign, “#”
  • Can load information into any registers, including 16-bit DPTR register
  • DPTR can also be accessed as two 8-bit registers, the high byte DPH and low byte DPL

MOV A,#25H ;load 25H into A

MOV R4,#62 ;load 62 into R4

MOV B,#40H ;load 40H into B

MOV DPTR,#4521H ;DPTR=4512H

MOV DPL,#21H ;This is the same

MOV DPH,#45H ;as above

;illegal!! Value > 65535 (FFFFH)

MOV DPTR,#68975

Register Addressing Mode of 8051 Microcontroller

Use registers to hold the data to be manipulated

MOV A,R0 ;copy contents of R0 into A

MOV R2,A ;copy contents of A into R2

ADD A,R5 ;add contents of R5 to A

ADD A,R7 ;add contents of R7 to A

MOV R6,A ;save accumulator in R6

  • The source and destination registers must watch in size

MOV DPTR, A  will give an error




The movement of data between Rn registers is not allowed

  • MOV R4, R7  is invalid

Direct Addressing Mode of 8051 Microcontroller

It is most often used the direct addressing mode to access RAM locations 30-7FH

  • The entire 128 bytes of RAM can be accessed
  • The register bank locations are accessed by the register names

MOV  A, 4  (Is same as)

MOV A, R4  (which means copy R4 into A)

Contrast this with immediate addressing mode

  • There is no “#” sign in the operand

MOV  R0,40H          (save the content of 40H in R0)

MOV 56H, A             (save content of A in 56H)

Register Indirect Addressing Mode in 8051 Microcontroller

A register is used as a pointer to the data

  • Only register R0 and R1 are used for this purpose
  • R2-R7 cannot be used to hold the address of an operand located in RAM

When R0 and R1 hold the addresses of RAM location, they must be preceded by the “@” sign

MOV  A, @R0    (move contents of RAM whose; the address is held by R0 into A)

MOV @R1, B     (move contents of B into RAM; whose address is held by R1)

The advantage is that it makes   accessing data dynamic rather than static as indirect addressing mode

  • Looping is not possible in direct addressing mode

Example: Write a program to clear 16 RAM locations starting at RAM address 60H


CLR A ;A=0

MOV R1,#60H ;load pointer. R1=60H

MOV R7,#16 ;load counter, R7=16

AGAIN: MOV @R1,A ;clear RAM R1 points to

INC R1 ;increment R1 pointer

DJNZ R7, AGAIN ; loop until counter=zero

Indexed Addressing Mode and on-chip ROM Access

Indexed addressing mode is widely used in accessing data elements of look-up table entries located in the program ROM

The instruction used for this purpose is


  • Use instruction MOVC, “C” means code
  • The contents of A are added to the 16- bit register DPTR to from the 16-bit address of the needed data

Example: In this 8051 Microcontroller program, assume that the word “USA” is burned into ROM location starting at 200H. And that the program is burned into ROM location starting at 0.Analyze how the program works and state, where “PES” is stored after this program, is run.


ORG 0000H ;burn into ROM starting at 0

MOV DPTR,#200H ;DPTR=200H look-up table addr

CLR A ;clear A(A=0)

MOVC A,@A+DPTR ;get the char from code space

MOV R0,A ;save it in R0

INC DPTR ;DPTR=201 point to next char

CLR A ;clear A(A=0)

MOVC A,@A+DPTR ;get the next char

MOV R1,A ;save it in R1

INC DPTR ;DPTR=202 point to next char

CLR A ;clear A(A=0)

MOVC A,@A+DPTR ;get the next char

MOV R2,A ;save it in R2

Here: SJMP HERE ;stay here

;Data is burned into code space starting at 200H

ORG 200H


END ;end of program

Arithmetic & Logic Instructions of 8051 Microcontroller

ADD Opcode with Example

ADD A,source ;A = A + source

The instruction ADD is used to add two operands

  • The destination operand is always in register A
  • The Source operand can be a register, immediate data, or in memory
  • Memory-to-memory arithmetic operations are never allowed in 8051 Microcontroller Assembly language

Show how the flag register is affected by the following instruction.

MOV A, #0F5H (A=F5 Hex)

ADD A, #0BH (A=F5+0B=00)

      F5H       1111 0101    
+     0BH     + 0000 1011  
----------   -------------------
     100H      0000  0000
  • CY = 1, since there is a carryout from D7 bit.
  • PF = 1, because the number of 1’s is zero which is an even number hence PF is set to 1.
  • AC = 1, since there is a carry from D3 to D4.

SUB Opcode With Example

In any microprocessor there are two different instructions for subtraction :

SUB and SUBB  (subtract with borrow)

  • In 8051 Microcontroller, we have only SUBB Opcode.
  • The 8051 uses adder circuitry to perform the subtraction

SUBB A, source       (A = A-SOURCE-CY)

  • To make SUB out of SUBB, we have to make CY=0 prior to the execution of the instruction
  • Notice that we use the CY flag for the borrow
  • SUBB when CY=0
    1. Take the 2’s complement of the subtrahend (source operand)
    2. Add it to the minuend (A)
    3. Invert the carry


MOV A,#4C ;load A with value 4CH

SUBB A,#6EH ;subtract 6E from A

JNC NEXT ;if CY=0 jump to NEXT

CPL A ;if CY=1, take 1’s complement

INC A ;and increment to get 2’s comp

NEXT: MOV R1,A ;save A in R1

8051 Substraction Assembly Code
8051 Substraction Assembly Code

SUBB when CY=1

This instruction is used for multi-byte numbers and will take care of the borrow of the lower operand


MOV A, #62H ;A=62H

SUBB A, #96H ;A=62H-96H=CCH with CY=1

MOV R7,A ;Save the result

MOV A,#27H ;A=27H

SUBB A,#12H ;A=27H-12H-1=14H CY=0


We have 2762H-1296H=14CCH.

AND Operation With Example

ANL destination ,source ; dest=dest AND source

  • This instruction will perform a logic AND on the two operands and place the result in the destination
    1. The destination is normally the accumulator
    2. The source operand can be a register, in memory or immediate

AND Gate Truth Table

XYX and Y

Show the results of the following

MOV A,#35H ;A=35H


35H 0 0 1 1 0 1 0 1

0FH 0 0 0 0 1 1 1 1

05H 0 0 0 0 0 1 0 1

ANL is often used to mask (set to 0) certain bits of an operand

OR Operation Example in 8051 Microcontroller

ORL destination ,source ;dest = dest  or source

  • The destination and source operands are executed with OR operation and the result is placed in the destination.
    1. The destination is normally the accumulator
    2. The source operand can be a register, in memory, or immediate

Show the results of the following.

MOV A,#04H ;A=04

ORL A,#68H ;A=6C

04H 0 0 0 0 0 1 0 0

68H 0 1 1 0 1 0 0 0

6CH 0 1 1 0 1 1 0 0

ORL Instruction can be used to set certain bits of an operand to 1

XOR Operation Example

XRL destination,source; dest = dest XOR source

  • This instruction will perform XOR operation on the two operands and place the result in the destination
    1. The destination is normally the accumulator
    2. The source operand can be a register, in memory, or immediate

Show the results of the following.

MOV A, #54H

XRL A, #78H

54H 0 1 0 1 0 1 0 0

78H 0 1 1 1 1 0 0 0

2CH 0 0 1 0 1 1 0 0

XRL instruction can be used to toggle certain bits of an operand

Complement ACC

CPL  A; Complements  the  register A

  • This is called 1’s complement

MOV A, #55H

CPL A ;now A=AAH

;0101 0101(55H)

; becomes 1010 1010 (AAH)

  • To get the 2’s complement, all we have to do is to add 1 to the 1’s complement

Compare Instruction in 8051 Microcontroller

CJNE destination , source; rel.addr.

  • The actions of comparing and jumping are combined into a single instruction called CJNE (compare and jump if not equal) in 8051 Microcontroller.
    1. The CJNE instruction compares two operands and jumps if they are not equal
    2. The destination operand can be in the accumulator or in one of the Rn registers
    3. The sources operand can be in a register, in memory; or immediate
    4. The operands themselves remain unchanged
    5. It changes the CY flag to indicate if the destination  operand is larger or smaller

CJNE R5,#80,NOT_EQUAL ;check R5 for 80

… ;R5 = 80


JNC NEXT ;jump if R5 > 80

… ;R5 < 80


CompareCarry flag
Destination >= SourceCY = 0
Destination < SourceCY = 1


  • Notice in the CJNE instruction that any Rn register can be compared with an immediate value
    1. There is no need to register A to be involved
  • The compare instruction is really a subtraction, except that the operands remain unchanged
    1. Flags are changed according to the execution of the SUBB instruction

Write a program to read the temperature and test it for the value 75. According to the test results, place the temperature value into the registers indicated by the following.

If T = 75 then A=75

If T < 75 then R1=T

If T > 75 then R2=T


MOV P1,#0FFH ;make P1 an input port

MOV A,P1 ; read P1 port

CJNE A,#75,OVER ;jump if A is not 75

SJMP EXIT ;A=75, exit

OVER: JNC NEXT ;if CY=0 then A>75

MOV R1,A ;CY=1,A<75,save in R1

SJMP EXIT ; and exit

NEXT: MOV R2,A ;A>75,save it in R2



RR  A   ;rotate  right A

  • In Rotate right
    1. The 8 bits of the accumulator are rotated  right one bit, and
    2. Bit DO exits from the LSB and enters into MSB, D7
8051 Microcontroller Rotate Right
8051 Rotate Right

MOV A,#36H ;A= 0011 0110

RR A ;A= 0001 1011

RR A ;A= 1000 1101

RR A ;A= 1100 0110

RR A ;A= 0110 0011

RL A; rotate left   A

  • In rotate left
    1. The 8 bits of the accumulator are rotated left one bit, and
    2. Bit D7 exits from the MSB and enters into LSB, D0
8051 Microcontroller in Rotate Left
8051 in Rotate Left

MOV A,#27 ;A= 0111 0010

RL A ;A= 1110 0100

RL A ;A= 1100 1001

Rotating Through Carrying

RRC A; right rotate through carrying

  • In RRC A
    1. Bits are rotated from left to right
    2. They exit the LSB to the carry flag, and the carry flag enters the MSB
8051 Microcontroller in RRC A
8051 in RRC A

CLR C ;make CY = 0

MOV A,#26H ;A = 0010 0110

RRC A ;A = 0001 0011 CY = 0

RRC A ;A = 0000 1001 CY = 1

RRC A ;A = 1000 0100 CY = 1

RLC A ; rotate  left through carry

  • In RLC A
    1. Bits are shifted from right to left
    2. They exit the MSB and enter the carry flag, and the carry flag enters the LSB 
8051 Microcontroller IN RLC A
8051 IN RLC A

Write a program that finds the number of 1s in a given byte.

MOV R1,#0

MOV R7,#8 ;count = 08

MOV A,#97H


JNC NEXT ;check for CY

INC R1 ;if CY=1 add to count




  • It swaps the lower nibble and the higher nibble
    1. In other words, the lower 4 bits are put into the higher 4 bits and the higher 4 bits are put into the lower 4 bits.
  • SWAP works only on the accumulator (A) 
LabelMSB NibbleLSB Nibble
Swapping Of Nibble
  • Find the contents of register A in the following code of 8051 Microcontroller.
  • In the absence of a SWAP instruction, how would you exchange the nibbles? Write a simple program to show the process.


MOV A,#72H ;A = 72H

SWAP A ;A = 27H

MOV A#27H ;A = 0111 0010

RL A ;A = 0111 0010

RL A ;A = 0111 0010

RL A ;A = 0111 0010

RL A ;A = 0111 0010


8051 Microcontroller Hardware Conection
8051 Hardware Conection

Total 40 pins are there in 8051

  • 32 I/O pins (4 ports,8 pins each)
  • 2 power supply pins (Vcc, GND)
  • 1 Reset pin (RST)
  • 2 Crystal pins (XTAL1,XTAL2)
  • 3 Other pins (PSEN, ALE, EA)

The 8051 Microcontroller has an on-chip oscillator but requires an external clock to run it

  • A quartz crystal oscillator is connected to inputs XTAL1 (pin 19) and XTAL2 ( pin 18)
  • The quartz crystal oscillator also needs two capacitors of 30 pF value
8051 Microcontroller MCU XTAL Diagram
8051 MCU XTAL Diagram

The RESET pin is an input and is active high (normally low)

  • Upon applying a high pulse to this pin, the microcontroller will reset and terminate all activities
  • This is often referred to as a power-on reset
  • Activating a power-on reset will cause all values in the registers to be lost

In order for the RESET input to be effective, it must have a minimum duration of 2 machine cycles.

  • In other words, the high pulse must be high for a minimum of 2 machine cycles before it is allowed to go low
8051 MCU with XTAL Conection
8051 MCU with XTAL Conection

EA, “external access” , is an input pin and must be connected to Vcc or GND

  • The 8051 Microcontroller family members all come with on-chip ROM to store programs
  • -EA pin is connected to Vcc
  • The 8031 and 8032 family members do no have on-chip ROM, so code is stored on an external ROM and is fetched by 8031/32
  • -EA pin must be connected to GND to indicate that the code is stored externally

The following two pins are used mainly in 8031-based systems

  • PSEN, “program store enable”, is an output pin
    1. This pin is connected to the OE pin of the ROM
  • ALE, “Address latch enable “, is an output pin and is active high
    1. Port 0 provides both address and data
    2. The 8031 multiplexes address and data through port 0 to save pins
    3. ALE pin is used for demultiplexing the address and data by connecting to the G pin of the 74LS373 chip
  • The four 8-bit I/O ports P0, P1, P2 and P3 each uses 8 pins
  • All the ports upon RESET are configured as an output, ready to be used as input ports
  • Port 0 is also designated as  AD0 – AD7, allowing it to be used for both address and data
    1. When connecting an 8051/31 to external memory, port 0 provides both address and data
    2. The 8051 multiplexes address and data through port 0 to save pins
    3. ALE indicates if P0 has address or data
    4. When ALE = 0, it provides data D0-D7
    5. When ALE =1, it has address A0 – A7
  • It can be used for input or output, each pin must be connected externally to a 10K ohm pull-up resistor.
    1. This is due to the fact that P0 is an open drain, unlike P1, P2, and P3
    2. Open-drain is a term used for MOS chips in the same way that open collector is used for TTL chips.
8051 Microcontroller Port Diagram
8051 Port Diagram
  • In 8051 – based systems with an external memory connection
    1. Both P1 and P2 are used as simple I/O
  • In  8031/51- based systems with external memory connections
    1. Port 2 must be used along with P0 to provide the 16 – bit address  for the external memory
    2. P0 provides the lower 8 bits via A0 – A7
    3. P2 is used for the upper 8 bits of the 16 – bit address, designated as A8 – A15, and it cannot be used for I/O
  • Port 3 can be used as  input or output
    1. Port 3 does not need any pull-up resistors
  • Port 3 has the additional function of providing some extremely important signals
8051 Microcontroller Pin Function
8051 Pin Function

TIMER Programming of 8051 Microcontroller

The 8051 has two timers/counters, they can be used either as

  • Timers to generate a time delay or as
  • Event counters to count events happening outside the microcontroller

Both timer 0 and timer 1 are 16 bits wide

  • Since 8051 Microcontroller has an 8-bit architecture, each 16 – bits timer is accessed as two separate registers of low light and high light

Accessed  as low byte  and high byte

  • The low byte register is called TL0 /TL1 and
  • The high byte register is called TH0/TH1
  • Accessed like any other register



8051 Microcontroller Timer programing
8051 Timer programing

Both timers 0 and 1 use the same register, called TMOD (timer mode), to set the various timer operations modes

  • TMOD  is an 8-bit register
    1. The lower 4-bits are for timer 0
    2. The upper 4-bits are for timer 1 in each case
    3. The lower 2-bits are used to set the timer mode
    4. The upper 2bits to specify the operation.
8051 Microcontroller Operating mode
8051 Operating mode

Example: Indicate which mode and which timer are selected for each of the following:




Solution: We convert the value from hex to binary.from fig 9-3 we have:

  • TMOD = 00000001, mode 1 of timer 0 is selected.
  • TMOD = 00100000, mode 2 of timer 1 is selected.
  • TMOD = 00010010, mode 2 of timer 0, and mode 1 of timer 1 are selected.
  • Timers of 8051 Microcontroller does start and stopping by either software or hardware control:
    1. in using software  to start and stop the timer where GATE = 0
    2. The start and stop of the timer are controlled  by way of software by the TR (Timer start) bits TR0 and TR1-The SETB  instruction  starts it, and it is stopped by the CLR instruction-These instructions  start and stop the timer as long as GATE = 0 in the TMOD  register
    3. The hardware  way of starting and  stopping  the timer by an external  source  achieved  by making  GATE = 1 in the TMOD register

MODE  1 Programming in 8051 Microcontroller

The following are the characteristics and operations of mode 1:

  1. It is a 16 – bit timer; therefore, it allows the value of 0000 to FFFFH to be loaded into the timer’s register TL and TH.
  2. After TH and TL are loaded with a 16-bit initial value, the timer must be started.
    • This is done by SETB TR0 for timer 0 and SETB  TR1 for timer 1
  3. After the timer is started, it starts to count up
    • It counts up until it reaches its limit of FFFFH
    • when it rolls over from  FFFFH  to 0000, it sets high a flag bit called TF (timer flag)
    • Each timer has its own timer flag: TF0 for timer 0, TF1 for timer 1
    • This timer flag can be monitored
    • When this timer flag is raised, one option would be to stop the timer with the instructions CLR TR0 or CLR TR1, for timer 0 and timer1 respectively
  4. After the timer  reaches  its limit and rolls over, in order to repeat the process
    • TH and TL must be reloaded with the original value, and
    • TF must be reloaded 0

STEPS  FOR MODE 1 Programming of 8051 Microcontroller

  1. Load the TMOD value register indicating which timer (timer 0 and timer 1) is to be used and which timer mode ( 0 or 1) is selected
  2. Load registers TL and TH with an initial count value
  3. Start the timer
  4. 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 becomes high
  5. Stop the timer
  6. Clear the TF flag for the next round
  7. Go back to step 2 to load TH and TL again

Example: In the following program, we create a square wave of  50% duty cycle (with equal portions high and low) on the P1.5 bit. Timer 0 is used to generate the time delay. analyze the program

MOV TMOD,#01 ;Timer 0, mode 1(16-bit mode)

HERE: MOV TL0,#0F2H ;TL0=F2H, the low byte

MOV TH0,#0FFH ;TH0=FFH, the high byte

CPL P1.5 ;toggle P1.5



In the above program notice the following step.

  1. TMOD is Loaded.
  2. FFF2H is loaded into TH0 –TL0.
  3. P1.5 is toggled for the high and low portions of the pulse.


SETB TR0 ;start the timer 0

AGAIN: JNB TF0,AGAIN ;monitor timer flag 0

;until it rolls over

CLR TR0 ;stop timer 0

CLR TF0 ;clear timer 0 flag


  1. The DELAY subroutine using the timer is called.
  2. In the DELAY subroutine, timer 0 is started by the SETB TR0 instruction.
  3. Timer 0 counts up with the passing of each clock, which is provided by the crystal oscillator.

As the timer counts up, it goes through the states of FFF3,FFF4,FFF5,FFF6,FFF7,FFF8,FFF9,FFFA, FFFB, and so on until it reaches FFFFH. One more clock rolls it to 0, raising the timer flag (TF0 = 1). At that point, the JNB instruction falls through.

8051 Microcontroller MODE 1 Timer Reset
MODE 1 Timer Reset

Timer 0 is stopped by the instruction CLR   TR0. The DELAY subroutine ends, and the process is repeated. Notice that to repeat the process, we must reload the TL and TH registers, and start the process is repeated.

Finding The Loaded Timer Values

To calculate the values to be loaded into the TL and TH  registers, look at the following example

  • Assume the 8051 Microcontroller XTAL = 11.0592 MHz, we can the using following steps for finding the TH, TL registers value
    1. Divide the desired time delay by 1.085 us.
    2. Perform 65536 – n, where n is the decimal value we got in step 1.
    3. Convert the result of step 2 hex, where “yyxx” is the initial hex value to be loaded into the timer’s register.
    4. Set TL = xx and TH = yy .


Assume that XTAL = 11.0592 MHz, what value do we need to load the timer’s registers if we want to have a time delay of 5 ms (milliseconds)? show the program for timer 0 to create a pulse width of 5 ms on P2.3.


Since XTAL = 11.0592 MHz , the counter counts up every 1.085 us . this means that out of many 1.085 us intervals we must make a 5 ms pulse . to get that, we divide one by the other. we need 5 ms / 1.085 us = 4608 clocks . to achieve that  we need to load into TL and TH the value 65536 – 4608 = EE00HH. therefore , we have TH = EE  and TL = 00 .

CLR P2.3 ;Clear P2.3

MOV TMOD,#01 ;Timer 0, 16-bitmode

HERE: MOV TL0,#0 ;TL0=0, the low byte

MOV TH0,#0EEH ;TH0=EE, the high byte

SETB P2.3 ;SET high P2.3

SETB TR0 ;Start timer 0

AGAIN: JNB TF0,AGAIN ;Monitor timer flag 0

CLR TR0 ;Stop the timer 0

CLR TF0 ;Clear timer 0 flag

MODE 2 Programming of 8051 Microcontroller

The following are the characteristics and operations of mode 2 :

It is an 8 – bit timer; therefore, it allows only values of 00 to FFH to be loaded into the timer’s register  TH.

  • After TH is loaded with the 8 – bit value, the 8051 gives a copy of it to TL
    1. Then the timer must be started.
    2. This is done by the instruction  SETB  TR0 for timer 0 and SETB  TR1 for timer 1
  • After the timer is started, it starts to count up by incrementing  the TL register:
    1. It counts up until it reaches its limit of FFH
    2. When it rolls over from FFH to 00, it sets high the TF (timer flag )
  • When the TL register rolls from FFH to 0 and TF is set to 1, TL is reloaded automatically with the original value kept by the TH register.
    1. To repeat the process, we must simply clear TF and let it go without any need by the programmer to reload the original value
    2. This makes mode 2 an auto-reload, in contrast with mode 1 in which the programmer has to reload TH  and  TL

STEPS TO MODE  2  Program

To generate a time delay

  • Load the TMOD value  register indicating which timer (timer 0 and timer 1 ) is to be used, and the timer mode ( mode 2 ) is selected
  • Load the TH registers with the initial count value
  • Start timer
  • Keep monitoring the timer flag (TF) with the JNB  TFx, target instruction to see whether it is raised.
    1. Get out of the loop when TF goes high.
  • Clear the TF flag
  • Go back to step 4, since mode 2 is auto-reload

EXAMPLE: Assume that the 8051 Microcontroller XTAL = 11.0592 MHz, find the frequency of the square wave generated on pin P1 .0 in the following program.

MOV TMOD,#20H ;T1/8-bit/auto reload

MOV TH1,#5 ;TH1 = 5

SETB TR1 ;start the timer 1

BACK: JNB TF1,BACK ;till timer rolls over

CPL P1.0 ;P1.0 to hi, lo

CLR TF1 ;clear Timer 1 flag

SJMP BACK ;mode 2 is auto-reload

SOLUTION: First, notice the target address of SJMP . in mode 2 we do not need to reload TH since it is auto-reload. now (256-05)*1.085 us = 251 * 1.085 us = 272.33 us is the high portion of the pulse . since it is a 50% duty cycle square wave, the period T is twice that; as a result, T = 2 * 272.33 us = 544.67 us and the frequency 1. 83597 kHz

SERIAL Communication in 8051 Microcontroller

Computers transfer  data in two ways :

  • Parallel ;
    1. Often 8 or more lines (wire conductors) are used to transfer data to a device that is only a few feet away
  • Serial ;
    1. To transfer to a device located many meters away, the serial method is used
    2. The data is sent one bit at a time
8051 Microcontroller Serial Communication
Serial Communication
  • At the transmitting end, the byte of data must be converted to serial bits using parallel – in – serial-out shift register
  • At the receiving end, there is a serial in-parallel-out shift register to receive the serial data and pack them into a byte
  • when the distance is short, the digital signal can be transferred as it is on a simple wire and requires no modulation
  • If data is to be transferred on the telephone line, it must be converted from 0s and 1s to audio tones.
    1. This conversion is performed by a device called a modem, “modulator/demodulator”
  • Serial data communication use two methods
    1. The synchronous method transfers a block of data at a time
    2. The asynchronous method transfers a single byte at a time
  • It is possible to write software to use either of these methods, but the programs can be tedious and long.
    1. There are special IC chips made by many manufacturers for serial communications
    2. UART (universal asynchronous Receiver-transmitter)
    3. USART  (Universal synchronous – asynchronous Receiver-transmitter)
  • If data can be transmitted received, it is a duplex transmission
    1. If data transmitted one-way time, it is referred to as half-duplex
    2. If data can go both ways at a time, it is full-duplex
  • This is in contrast to simplex transmission
8051 Microcontroller Communication Type
8051 Communication Type
  • A protocol is a set of rules agreed by both the sender and receiver on
    1. How the data is packed
    2. How many bits constitute a character
    3. when the data begins and ends
  • Asynchronous serial data communication is widely used for character-oriented transmissions.
    1. Each character is placed in between the start and stops bits, This is called framing.
    2. Block-oriented data transfers use synchronous methods.
  • The start bit is always one bit, but the stop bit can be one or two bits
  • The start bit is always a 0 (low)  and the stop bit (s) is 1 (high)
8051 Microcontroller ASCII Character
8051 ASCII Character

RS232 Standards

  • An interfacing standard RS232 was set by the Electronics Industries Association (EIA) in 1960
  • The standard was set long before the advent of the TTL logic family, its input and output voltage levels are not TTL compatible.
    1. In RS232 , a 1 is represented by- 3 ~ – 25 V , while a 0 bit is +3 ~ +25V , making -3 to +3 undefined
8051 Microcontroller RS232 Pin Description
RS232 Pin Description

8051 Microcontroller Connection TO RS232

  • A line driver such as the MAX232 chip is required to convert RS232 voltage levels to TTL levels, and vice versa
  • 8051 Microcontroller has pins that are used specifically for transferring and receiving data serially.
    1. These two pins are called TxD and RxD  and are part of the port 3 group (P3 .0 and P3 .1)
    2. These pins are TTL compatible; therefore, they require a line driver to make them RS232  compatible
  • we need  a line driver (voltage converter) to convert the R232’s signals to TTL voltage levels that will be acceptable to 8051’s TxD and RxD pins
8051 Microcontroller Interface with MAX232
8051 Interface with MAX232
  •  To save board space, some designers use MAX233 chip from Maxim.
    1. MAX233 performs the same job as MAX232 but eliminates the need for capacitors.
    2. Notice that MAX233 and MAX232 are not pinned compatible
8051 Microcontroller Interface With MAX233
8051 Interface With MAX233
  • To allow data transfer between the PC and an 8051 Microcontroller system without any error, we must make sure that the baud rate of 8051 system matches the baud rate of the PC’s COM port
  • The hyper terminal function supports baud rates much higher than listed below
Serial NoPC Baud Rates

SERIAL Communication Programming in 8051 Microcontroller

SBUF Register: SBUF  is an 8 – bit register used solely for serial communication.

  • For a byte data to be transferred via the TxD line, it must be placed in the SBUF register
  • The moment a byte is written into SBUF, it is framed with the start and stop bits transferred serially  via the TxD  line
  • SBUF holds the byte of data when it is received  by 8051 RxD line
  • when the bits are received serially via RxD, the 8051 de-frames it by eliminating  the stop and start bits, making a bite out of the data received, and then placing it in SBUF

MOV SBUF,#’D’ ;load SBUF=44h, ASCII for ‘D’

MOV SBUF,A ;copy accumulator into SBUF

MOV A,SBUF ;copy SBUF into accumulator

Serial Control (SCON) Register

SCON is an 8 – bit  Register used to program the start bit, stop bit, and data bits of data framing, among other things.

B7SM0SCON.7Serial Port Mode Specifier
B6SM1SCON.6Serial Port Mode Specifier
B5SM2SCON.5Used For Multiprocessor Communication
B4RENSCON.4Set/Cleared By Software to Enable/Disable Reception
B3TB8SCON.3Not Widely Used
B2RB8SCON.2Not Widely Used
B1TISCON.1Transmit Interrupt flag. Set by HW at the begin of the stop bit mode 1.And cleared by SW.
B0RISCON.0Receive interrupt flag. set by HW at the begin of the stop bit mode 1. and cleared by SW

NOTE: Make SM2,TB8 and RB8=0

  • SM0, SM1
    1. They determine the framing of data by specifying the number of bits per character, and the start and stop bits
00Serial Mode 0
01Serial Mode 1, 8-bit data, 1 stop bit,1 start bit
10Serial Mode 2
11Serial Mode 3
  • SM2
    1. This enables the multiprocessing capability of the 8051 Microcontroller
  • REM (receive enable)
    1. It is a bit – addressable register
    2. when it is high, it allows 8051 Microcontroller to receive data on RxD pin
    3. If low, the receiver is disabled
  • TI  (Transmit interrupt)
    1. when 8051 finishes the transfer of 8 – bit character
    2. It raises the TI flag to indicate  that it is ready to transfer another byte
    3. TI bit is raised  at the beginning of the stop bit
  • R1 (receive interrupt)
    1. when 8051 Microcontroller receives data serially via RxD, it gets rid of the start and stop bits and places the byte in SBUF register
    2. It raises the R1 flag bit to indicate that a byte has been received and should be picked up before it is lost
    3. R1 is raised halfway through the stop bit

Programming SERIAL Data Transmitting in 8051 Microcontroller

In programming of 8051 Microcontroller to transfer the character bytes serially

  1. TMOD register is loaded with the value 20H, indicating the use of timer 1 in mode 2 (8 – bit auto-reload) to set the baud rate
  2. The TH1 is loaded with one of the values to set the baud rate for serial data  transfer
  3. The SCON register is loaded with the value 50H, indicating serial mode 1, when an 8 – bit data is framed with start and stop bits
  4. TR1 is set to 1 to start timer 1
  5. T1 is cleared by CLR TI instruction
  6. The character byte to be transferred serially is written into SBUF register
  7. The TI flag bit is monitored with the use of instruction JNB TI, xx to see if  the character has been transferred completely
  8. To transfer the next byte, go to step 5

Write a program for the 8051 Microcontroller to transfer letter “A” serially at 4800 baud, continuously.

Solution :

MOV TMOD,#20H ;timer 1,mode 2(auto reload)

MOV TH1,#-6 ;4800 baud rate

MOV SCON,#50H ;8-bit, 1 stop, REN enabled

SETB TR1 ;start timer 1

AGAIN: MOV SBUF,#”A” ;letter “A” to transfer

HERE: JNB TI,HERE ;wait for the last bit

CLR TI ;clear TI for next char

SJMP AGAIN ;keep sending A

Write a program for the 8051 Microcontroller to transfer “yes” serially at 9600 baud, 8 – bit data, 1 stop bit, do this continuously

Solution :

MOV TMOD,#20H ;timer 1,mode 2(auto reload)

MOV TH1,#-3 ;9600 baud rate

MOV SCON,#50H ;8-bit, 1 stop, REN enabled

SETB TR1 ;start timer 1

AGAIN: MOV A,#”Y” ;transfer “Y”


MOV A,#”E” ;transfer “E”


MOV A,#”S” ;transfer “S”


SJMP AGAIN ;keep doing it

;serial data transfer subroutine


HERE: JNB TI,HERE ;wait for the last bit

CLR TI ;get ready for next byte


Importance of TI FLAG in 8051 Microcontroller

The steps that 8051 goes through in transmitting a character via TxD

  • The byte character to be transmitted is written into the SBUF register
  • The start bit is transferred
  • The 8 – bit character transferred on a bit at a time
  • The stop bit is transferred
    1. It is during the transfer of the stop bit that 8051 raise the TI flag, indicating that the last character was transmitted
  • By monitoring the TI flag, we make sure that we are not overloading the SBUF
    1. If we write another byte into the SBUF before TI is raised, the untransmitted portion of the previous byte will be lost
  • After SBUF is loaded with a new byte, the TI flag bit must be forced to 0 by CLR TI  in order for this new byte to be transferred

By checking the TI flag bit, we know whether or not the 8051 is ready to transfer another byte

  • it must be noted that TI flag bit is raised by 8051 itself when it finishes the data transfer
  • It must be cleared by the programmer with instruction CLR TI
  • If we write a byte into SBUF before the TI flag bit is raised, we risk the loss of a portion of the byte being  transferred
  • The TI bit can be checked by
    1. The instruction  JNB TI, xx
    2. Using an interrupt

Programming of SERIAL Data Receive in 8051 Microcontroller

In programming the 8051 to receive character bytes serially

  • TMOD register is loaded with the value 20H, indicating the use of timer 1 in mode 2 (8 – bit auto-reload) to set the baud rate
  • TH1 is loaded to set the baud rate
  • The SCON register is loaded with the value 50H, indicating serial mode 1, when an 8 – bit data is framed with start and stop bits
  • TR1 is set to 1 to start timer 1
  • R1 is cleared by CLR R1 instruction
  • The R1 flag bit is monitored with the use of instruction JNB R1, xx to see if an entire character has been received yet
  • when R1 is raised, SBUF has the byte, its contents are moved into a safe place
  • To receive the next character, go to step 5

Write a program for the 8051 Microcontroller to receive bytes of data serially, and put them in P1, set the baud rate at 4800, 8 -bit data, and 1 stop bit


MOV TMOD,#20H ;timer 1,mode 2(auto-reload)

MOV TH1,#-6 ;4800 baud rate

MOV SCON,#50H ;8-bit, 1 stop, REN enabled

SETB TR1 ;start timer 1

HERE: JNB RI, HERE ; wait for char to come in

MOV A, SBUF ; saving incoming byte in A

MOV P1, A ; send to port 1

CLR RI ;get ready to receive next byte

SJMP HERE ;keep getting data

Importance of RI Flag

In receiving bit via its RxD pin, 8051 goes through the following steps

  • It receives the start bit
    1. Indicating that the next bit is the first bit of the character byte it is about to receive
  • The 8 – bit character is received one bit at a time.
  • The stop bit is received
    1. when receiving the stop bit 8051 makes RI = 1, indicating that an entire character byte has been received and must be picked up before it gets overwritten by an incoming character
  • By checking the RI flag bit when it is raised, we know that a character has been received and is set in the SBUF register
    1. We copy the SBUF contents to a safe  place in some other register or memory before it is lost
  • After the SBUF contents are copied into a safe place, the RI flag bit must be forced to 0 by CLR RI in order to allow the next received character byte to be placed in SBUF.
    1. Failure to do this causes loss of the received character
  • By checking the RI flag it, we know whether or not the 8051 received the character byte.
    1. if we failed to copy SBUF into a safe place, we risk the loss of the received  byte
    2. It must be noted that the RI flag bit is raised by 8051 when it finishes receive data.
    3. It must be cleared by the programmer with instruction CLR RI.
    4. If we copy SBUF into a safe place before the RI flag bit is raised, we risk copying garbage.
  • The RI bit can be checked by:
    1. The instruction JNB R1, xx
    2. Using an Interrupt

INTERRUPTS Programming in 8051 Microcontroller

Interrupts vs. polling

  • An interrupt is an external or internal event that interrupts the microcontroller to inform it that a device needs its service
  • A single microcontroller can serve several devices in two ways

What is an Interrupt and how does it works?

  • whenever any device needs its service, the device notifies the microcontroller by  sending it an interrupt signal
  • upon receiving an interrupt signal, the microcontroller interrupts whatever it is doing  and serves the device
  • The program which is associated with the interrupt is called the interrupt service routine (ISR) or interrupt handler

What is Polling and how does it works?

  • The microcontroller continuously monitors the status of a given device
  • when the conditions met, it performs the service
  • After that, it moves on to monitor the next device until everyone is serviced
  • Polling can monitor the status of several devices and serve each of them as certain conditions are met.
    1. The polling method is not efficient since it wastes much of the microcontroller ‘s time by polling devices that do not need service
    2. ex. JNB   TF, target
  • The advantage of interrupts is that the microcontroller can serve many devices (not all at the same time).
    1. Each device can get the attention of the microcontroller based on the assigned priority
    2. For the polling method, it is not possible to assigned priority since it checks  all device in a round-robin fashion
  • The microcontroller can also ignore (mask) a device request for service.
    1. This is not possible for the polling method

Interrupt Service Routine

For every interrupt, the must be an interrupt service routine (ISR) , or interrupt handller

  • when an interrupt is invoked, the microcontroller runs the interrupt service routine
  • For every interrupt, there is a fixed location in memory that holds the address of its ISR
  • The group of memory locations set aside to hold the address of ISRs is called interrupt vector table

Steps in Executing an interrupt

Upon activation of an interrupt , the microcontroller goes through the following steps

  • It finishes the instruction it is executing and  saves the address of the next instruction (PC) on the stack
  • it also saves the current status of all the interrupts internally (i.e: not on the stack)
  • It jumps to a fixed location in memory, called the interrupt vector table, that holds the address of the ISR
  • The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it.
    1. it starts to execute the interrupt service subroutine until it reaches the last instruction of the subroutine which is RITE (return from interrupt)
  • Upon executing the RITE instruction, the microcontroller returns to the place where it was interrupted
    1. First, it gets the program counter (PC) address from the stack by popping the top two bytes of the stack into the pc.
    2. Then it starts to execute from that address.

Six interrupts in 8051 Microcontroller

Six interrupts are collected as follows

  • Reset – power-up reset
  • Two interrupts are set aside for the timers: one of  timer 0 and one for timer 1
  • Two interrupts are set aside for hardware external interrupts.
    1. P3.2 and P3.3 are for the external hardware interrupt INT0 (or EX1), and INT1 (or EX2).
  • Serial communication has a single interrupt that belongs to both receive and transfer.
InterruptROM Location(Hex)Pin
External HW (INT0)0003P3.2(12)
Timer 0 (TF0)000B
External HW (INT1)0013P3.3(13)
Timer 1(TF1)001B
Serial COM (RI and TI)0023

Enabling and disabling an Interrupt

  • Upon reset, all interrupts are disabled (masked), meaning that none will be responded to by the microcontroller if they are activated
  • The interrupts must be enabled by software in order for the microcontroller to respond to them.
    • There is a register called IE (Interrupt Enable) that is responsible for enabling (unmasking) and disabling (masking) the interrupts
8051 Microcontroller Interrupt Enable Register
Interrupt Enable Register
  • To enable an interrupt, we take the following steps:
  • Bit D7 of the IE register (EA) must be set to high to allow the reset of the register to take effect.
  • The value of EA.
    1. If EA = 1, interrupts are enabled and will be responded to if their corresponding bits in IE are high.
    2.  If EA = 0, no interrupt will be responded to, even if the associated bit in the IE register is high.

EXAMPLE: Show the instructions to (a) enable the serial interrupt, timer 0 interrupts, and external hardware interrupt 1 (EX1) and (b) disable (mask) the timer 0 interrupt, then (c) show how to disable all the interrupts with a single instruction.


MOV IE,#10010110B ;enable serial,

;timer 0, EX1

Another way to perform the same manipulation is

SETB IE.7 ;EA=1, global enable

SETB IE.4 ;enable serial interrupt

SETB IE.1 ;enable Timer 0 interrupt

SETB IE.2 ;enable EX1

CLR IE.1 ;mask (disable) timer 0

;interrupt only

CLR IE.7 ;disable all interrupts

Timer Interrupts in 8051 Microcontroller

The timer flag (TF) is raised when the timer rolls over

  • In polling TF, we have to wait until the TF is raised.
    1. The problem with this method is that the microcontroller is tied down while waiting for TF to be raised, and can not do anything else.
  • Using interrupts solves this problem and, avoids tying down the controller.
    1. If the timer interrupts in the IE register is enabled, whenever the timer rolls over, TF is raised, and the microcontroller is interrupted in whatever it is doing and jumps to the interrupt vector table to service the ISR.
    2. In this way, the microcontroller can do other until it is notified that the timer has rolled over.
8051 Microcontroller Timer Interrupt
8051 Timer Interrupt

Example: write a program that continuously gets 8 – Bit data from P0 and sends it to P1 while simultaneously creating a square wave of 200 us period on pin P2.1. use timer 0 to create the square wave. Assume that XTAL = 11.0592 MHz

Solution :

We will use timer 0 in mode 2 (auto reload) . TH0 = 100/1.085 us = 92

; – – upon  wake – up go to main , avoid using.

; memory allocated to interrupt vector table

ORG 0000H

LJMP MAIN ;by-pass interrupt vector table

;– ISR for timer 0 to generate square wave

ORG 000BH ;Timer 0 interrupt vector table

CPL P2.1 ;toggle P2.1 pin

RETI ;return from ISR

;–The main program for initialization

ORG 0030H ;after vector table space

MAIN: MOV TMOD,#02H ;Timer 0, mode 2

MOV P0,#0FFH ;make P0 an input port

MOV TH0,#-92 ;TH0=A4H for -92

MOV IE,#82H ;IE=10000010 (bin) enable

;Timer 0

SETB TR0 ;Start Timer 0

BACK: MOV A,P0 ;get data from P0

MOV P1,A ;issue it to P1

SJMP BACK ;keep doing it loop

;unless interrupted by TF0


External Hardware Interrupts in 8051 Microcontroller

The 8051 has two external hardware interrupts

  • Pin 12 (P3.2) and P3 (P3.3)  of the 8051, designated as INT0 and INT1, are used as external hardware interrupts
  • The interrupt vector table locations 0003H and 0013H are set aside for INT0 and INT1
  • There are two activation levels for the external hardware interrupts
    1. Level trigged
    2. Edge trigged


  • In the level-triggered mode, INT0 and INT1 pins are normally high.
    1. If a low – level signal is applied to them, it triggers the interrupt
    2. Then the microcontroller stops whatever it is doing and jumps to the interrupt vector table to service that interrupt
    3. The low – level signal at the INT pin must be removed before the execution of the last instruction of the ISR, RETI; otherwise, another interrupt will be generated

This is called a level-triggered or level activated to interrupt and is the default mode upon reset of the 8051 Microcontroller.

Example 11-5: Assume that the INT1 Pin is connected to a switch that is normally high. Whenever it goes low, it should turn on an LED. The LED is connected to P1.3 and is normally off. When it is turned on it should stay on for a fraction of a second. As long as the switch is pressed low, the LED should stay on.

8051 Microcontroller Level-Triggered Interrupt
Level-Triggered Interrupt
ORG		0000H
		LJMP	MAIN		; by-pass inter-vector table
	;--     ISR for INT1 to run one LED	
		ORG	0013H		;INT1 ISR
	       SETB	P1.3		; turn on LED
	        MOV	R3, #255
BACK:	        DJNZ	R3, BACK	; keep LED on for a while
	        CLR 	P1.3		; Turn off the LED
		RET1			; return from ISR
;-- MAIN program for initialization
	ORG 	30H
MAIN: 	MOV	IE, #10000100B	        ;Enable external INT1
HERE:	SJMP 	HERE		        ; Stay here until get interrupted

Edge – Triggered Interrupt

To make INT0 and INT1 edge-triggered interrupts, we must program the bits of the TCON register

  • The TCON register holds, among other bits, the IT0 and IT1 flag bits that determine level – or edge-triggered mode of the hardware interrupt.
    1. IT0 and IT1 are bits D0 and D2 of the TCON register.
    2. They are also referred to as TCON.0 and TCON.2 since the TCON register is bit addressable

Assume that the pin 3.3 (INT1) of 8051 Microcontroller is connected to a pulse generator, write a program in which the falling edge of the pulse will send a high to P1.3, which is connected to an led (or buzzer). in other words, the LED is turned on and off at the same rate as the pulses are applied to the INT1 pin.


          ORG 0000H
          LJMP MAIN
;--ISR  for hardware interrupt INT1 to turn on LED
         ORG 0013H              ;INT1 ISR
         SETB P1.3              ;turn on LED
         MOV R3,#255
BACK:    DJNZ R3,BACK           ;keep the buzzer on for a while
         CLR P1.3               ;turn off the buzzer
         RETI                   ;return from ISR
;------MAIN program for initialization
        ORG 30H
MAIN:   SETB TCON.2             ;make INT1 edge-triggered int.
        MOV IE,#10000100B       ;enable External INT 1
HERE:   SJMP HERE               ;stay here until get interrupted

Serial Communication Interrupts in 8051 Microcontroller

  • TI (transfer interrupt) is raised when the last bit of the framed data, the stop bit, is transferred, indicating that the SBUF register is ready to transfer the next byte
  • RI (received interrupt) is raised when the entire frame of data, including the stop bit, is received.
    1. In other words, when the SBUF register has a byte, RI is raised to indicate that the received byte needs to the picked up before it is lost (overrun) by new incoming serial data.

RI and TI Flags and Interrupts

In the 8051 there is only one interrupt set aside for serial communication

  • This interrupt is used to both send and receives data
  • If the interrupt bit in the IE register (IE.4) is enabled when RI OR TI is raised the 8051 gets interrupted and jumps to memory location 0023H to execute the ISR
  • In that ISR we must examine the TI and RI flags to see which one caused the interrupt and respond accordingly
8051 Microcontroller RI and TI Flag Interrupts
RI and TI Flag Interrupts

Use of Serial COM in 8051 Microcontroller

The serial interrupt is used mainly for receiving data and is never used for sending data serially

  • This is like getting a telephone call in which we need a ring to be notified
  • If we need to make a phone call there are other ways to remind ourselves and there is no need for ringing
  • However, in receiving the phone call, we must respond immediately no matter what we are doing or we will miss the call

Example: Write a program in which the 8051 Microcontroller reads data from P1 and writes it to P2 continuously while giving a copy of it to the serial COM port to be transferred serially. Assume that XTAL = 11.0592. set the baud rate at 9600.


         ORG 0000H
         LJMP MAIN
         ORG 23H
         LJMP SERIAL             ;jump to serial int ISR
         ORG 30H
MAIN:    MOV P1,#0FFH            ;make P1 an input port
         MOV TMOD,#20H           ;timer 1, auto reload
         MOV TH1,#0FDH           ;9600 baud rate
         MOV SCON,#50H           ;8-bit,1 stop, ren enabled
         MOV IE,10010000B        ;enable serial int.
         SETB TR1                ;start timer 1
BACK:    MOV A,P1                ;read data from port 1
         MOV SBUF,A              ;give a copy to SBUF
         MOV P2,A                ;send it to P2
         SJMP BACK               ;stay in loop indefinitely
;-----------------SERIAL PORT ISR
         ORG 100H
SERIAL:  JB TI,TRANS             ;jump if TI is high
         MOV A,SBUF              ;otherwise due to receive
         CLR RI                  ;clear RI since CPU doesn’t
        RETI                     ;return from ISR
TRANS:  CLR TI                   ;clear TI since CPU doesn’t
        RETI                     ;return from ISR

The moment a byte is written into SBUF it is framed and transferred serially. As a result, when the last bit (Stop bit) is transferred the TI is raised, and that causes the serial interrupt to be invoked since the corresponding bit in the IE register is high. in the serial ISR, we check for both TI and RI since both could have invoked interrupt.

LCD Interfacing in 8051 Microcontroller

LCD is finding widespread use of replacing LEDs

  • The declining prices of LCD
  • The ability to display numbers, characters, and graphics
  • Incorporation of a refreshing controller into the LCD, thereby relieving the CPU of the task of refreshing the LCD
  • Ease of programming for characters and graphics
8051 Microcontroller LCD Interfacing
LCD Interfacing
CODE (Hex)Command to LCD Instruction Register
1Clear Display Screen
2Return Home
4Decrement Cursor (shift cursor to left)
6Increment Cursor (shift cursor to right)
5Shift display right
7Shift display left
8Display off, Cursor off
ADisplay off, Cursor on
CDisplay on, Cursor off
EDisplay on, Cursor blinking
FDisplay on, Cursor blinking
10Shift cursor position to left
14Shift cursor position to right
18Shift the entire display to the left
1CShift the entire display to the right
80Force cursor to beginning to 1st line
C0Force cursor to beginning to 2nd line
382 lines and 5×7 matrix
LCD Command Codes
8051 Microcontroller Interface With LCD
8051 Interface With LCD

To send any of the commands of the LCD, make the pin RS = 0. for data, make RS = 1. Then send a high – to – low pulse to the E pin to enable the internal latch of the LCD. This is shown in the code below.

;calls a time delay before sending next data/command

;P1.0-P1.7 are connected to LCD data pins D0-D7

;P2.0 is connected to RS pin of LCD

;P2.1 is connected to R/W pin of LCD

;P2.2 is connected to E pin of LCD

        ORG 0H
        MOV A,#38H                   ;INIT. LCD 2 LINES, 5X7 MATRIX
        ACALL COMNWRT                ;call command subroutine
        ACALL DELAY                  ;give LCD some time
        MOV A,#0EH                   ;display on, cursor on
        ACALL COMNWRT                ;call command subroutine
        ACALL DELAY                  ;give LCD some time
        MOV A,#01                    ;clear LCD
        ACALL COMNWRT                ;call command subroutine
        ACALL DELAY                  ;give LCD some time
        MOV A,#06H                   ;shift cursor right
        ACALL COMNWRT                ;call command subroutine
        ACALL DELAY                  ;give LCD some time
        MOV A,#84H                   ;cursor at line 1, pos. 4
        ACALL COMNWRT                ;call command subroutine
        ACALL DELAY                  ;give LCD some time
        MOV A,#’N’                   ;display letter N
        ACALL DATAWRT                ;call display subroutine
        ACALL DELAY                  ;give LCD some time
        MOV A,#’O’                   ;display letter O
        ACALL DATAWRT                ;call display subroutine
AGAIN:  SJMP AGAIN                   ;stay here
COMNWRT:                             ;send command to LCD
        MOV P1,A                     ;copy reg A to port 1
        CLR P2.0                     ;RS=0 for command
        CLR P2.1                     ;R/W=0 for write
        SETB P2.2                    ;E=1 for high pulse
        ACALL DELAY                  ;give LCD some time
        CLR P2.2                     ;E=0 for H-to-L pulse
DATAWRT:                             ;write data to LCD
         MOV P1,A                    ;copy reg A to port 1
         SETB P2.0                   ;RS=1 for data
         CLR P2.1                    ;R/W=0 for write
         SETB P2.2                   ;E=1 for high pulse
         ACALL DELAY                 ;give LCD some time
         CLR P2.2                    ;E=0 for H-to-L pulse
DELAY:   MOV R3,#50                  ;50 or higher for fast CPUs
HERE2:   MOV R4,#255                 ;R4 = 255
HERE:    DJNZ R4,HERE                ;stay until R4 becomes 0
         DJNZ R3,HERE2

IR Sensor (TSOP 1738)

8051 Microcontroller IR Sensor
8051 IR Sensor

The TSOP17. – Series are miniaturized receivers for infrared remote control systems. PIN diode and preamplifier are assembled on lead frame, the epoxy package is designed as IR filter. The demodulated output signal can directly the decoded by a microprocessor. TSOP17. is the standard IR remote control receiver series, supporting all major transmission codes.

Connection with 8051 Microcontroller

8051 Microcontroller Connection
8051 Connection

Notify of
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Scroll to Top