You are on page 1of 157

Introduction to Microcontroller

Syllabus

04/30/18 2
References

• Muhammad Ali Mazidi., “The 8051 Microcontroller


And Embedded Systems Using Assembly And C” ,
Pearson , 2nd edition

• Kenneth J. Ayala , “The 8051 Microcontroller” ,


Thomson Delmar

04/30/18 3
What is a microcontroller ?

A microcontroller is a small and low-cost microcomputer,


which is designed to perform the specific tasks of
embedded systems like displaying microwave’s
information, receiving remote signals, etc.

The general microcontroller consists of the processor,


the memory , Serial ports, peripherals (timers,
counters), etc.

04/30/18 4
Types of Microcontrollers
Microcontrollers are divided into various categories based
on :

– Bits

– memory,

– architecture,

– instruction sets.

04/30/18 5
Based on bits
Based on bit configuration, the microcontroller is 8-bit ,16-
bit , 32-bit microcontroller

Based on the memory


External memory microcontroller: This type of microcontroller
is designed in such a way that they do not have a program
memory on the chip. Hence, it is named as external memory
microcontroller. For example: Intel 8031microcontroller.

Embedded memory microcontroller: The microcontroller has all


programs and data memory, counters and timers, interrupts,
I/O ports embedded on the chip. For example: Intel 8051
microcontroller.

04/30/18 6
Based on architecture

04/30/18 7
Based on instruction set

04/30/18 8
RISC processor

RISC stands for Reduced Instruction Set Computer. It is


designed to reduce the execution time by simplifying the
instruction set of the computer.

RISC microprocessor architecture uses highly-optimized


set of instructions. It is used in portable devices like
Apple iPod due to its power efficiency.

04/30/18 9
Characteristics of RISC

The major characteristics of a RISC processor are :


– It consists of simple instructions.
– It supports various data-type formats.
– It utilizes simple addressing modes and fixed length
instructions for pipelining.
– It supports register to use in any context.
– One cycle execution time.
– “LOAD” and “STORE” instructions are used to access
the memory location.
– It consists of larger number of registers.

04/30/18 10
CISC Processor

CISC stands for Complex Instruction Set Computer. It is


designed to minimize the number of instructions per
program, ignoring the number of cycles per instruction.

The emphasis is on building complex instructions directly


into the hardware.

The compiler has to do very little work to translate a


high-level language into assembly level language/machine
code because the length of the code is relatively short, so
very little RAM is required to store the instructions.

04/30/18 11
Characteristics of CISC

• Variety of addressing modes.


• Larger number of instructions.
• Variable length of instruction formats.
• Several cycles may be required to execute one
instruction.
• Instruction-decoding logic is complex.
• One instruction is required to support multiple
addressing modes.

04/30/18 12
Special processor
These are the processors which are designed for some special
purposes. Few of the special processors are :

• Coprocessor
A coprocessor is a specially designed microprocessor,
which can handle its particular function many times faster
than the ordinary microprocessor. For example: Math
Coprocessor.

• Input/Output Processor
It is a specially designed microprocessor having a local
memory of its own, which is used to control I/O devices
with minimum CPU involvement. For example: DMA (direct
Memory Access) controller , Keyboard / mouse controller

04/30/18 13
Special processor

• Transputer (Transistor Computer)


A transputer is a specially designed microprocessor with
its own local memory and having links to connect one
transputer to another transputer for inter-processor
communications. For example:16-bit T212processors.

• DSP (Digital Signal Processor)


This processor is specially designed to process the analog
signals into a digital form. Its applications are:Sound and
music synthesis , Audio and video compression etc

04/30/18 14
Types of Microcontrollers

04/30/18 15
Microprocessor Vs Microcontroller
Microprocessor is heart of Micro Controller is a heart of
Computer system. embedded system
Microprocessors are used for Microcontrollers are used to
Multiple applications. execute a single task within an
application.
It is just a processor. Memory Micro controller has a processor
and I/O components have to be along with internal memory and
connected externally i/O components

Circuit is large Circuit is small

Cannot be used in compact Can be used in compact systems


systems and hence inefficient and hence it is an efficient
technique
04/30/18 16
Microprocessor Vs Microcontroller
Cost of the entire system is high Cost of the entire system is low

Since memory and I/O


Since components are internal,
components are all external,
most of the operations are
each instruction will need
internal instruction, hence speed
external operation, hence it is
is fast.
relatively slower.

04/30/18 17
Major Microcontroller Families
There are several major “families” of microcontrollers
available from different manufacturers.

– A family is defined as a group of products that share


the same basic internal architectures and are code-
compatible.

– Manufacturers usually define an architecture and then


make variants of that design producing a family of
products.

– Code written for a member of the family should be


compatible with all other members of the same family.

04/30/18 18
The MCS-51 Family of Microcontrollers
• Originally introduced by Intel in 1981.
– the most widely used microcontroller.
– 8-bit processor.
– 2 distinct separately addressable memory areas.
• Maximum of 64K on-chip ROM.
– Usually 0 to 4K.
• Maximum of 64K external data memory.
• Maximum of 64K external code memory.
• Basic version (8051) contains:
– 4K Bytes of on-chip ROM instruction memory.
– 128 Bytes of on-chip RAM for temporary data storage
and the stack.
– 2 timers, one serial port, and four 8-bit parallel I/O ports.
– Speeds starting from 12 MHz.

04/30/18 19
8051 architecture

04/30/18 20
Other 8051 featurs

• only 1 On chip oscillator (external crystal)


• 6 interrupt sources (2 external , 3 internal, Reset)
• 64K external code (program) memory(only read) PSEN
• 64K external data memory(can be read and write) by
RD,WR
• Code memory is selectable by EA (internal or external)
• We may have External memory as data and code

04/30/18 21
Pins of 8051
P1.0 1 40 Vcc
P1.1 2 39 P0.0(AD0)
P1.2 3 38 P0.1(AD1)
P1.3 4 8051 37 P0.2(AD2)
P1.4 5 36 P0.3(AD3)
P1.5 6 35 P0.4(AD4)
P1.6 7 34 P0.5(AD5)
P1.7 8 33 P0.6(AD6)
RST 9 32 P0.7(AD7)
(RXD)P3.0 10 31 EA/VPP
(TXD)P3.1 11 30 ALE/PROG
(INT0)P3.2 12 29 PSEN
(INT1)P3.3 13 28 P2.7(A15)
(T0)P3.4 14 27 P2.6(A14)
(T1)P3.5 15 26 P2.5(A13)
(WR)P3.6 16 25 P2.4(A12)
(RD)P3.7 17 24 P2.3(A11)
XTAL2 18 23 P2.2(A10)
XTAL1 19 22 P2.1(A9)
GND 20 21

P2.0(A8)

04/30/18 22
Pins of 8051
• Vcc ( pin 40 ):
– Provides supply voltage (+5V DC) to the chip.

• GND ( pin 20 ): ground

• XTAL1 and XTAL2 ( pins 19,18 ):


– These 2 pins provide external clock.

• RST ( pin 9 ): reset


– It is an input pin and is active high.
– Upon applying a high pulse to RST, the
microcontroller will reset and all values in
registers will be lost.
04/30/18 23
Pins of 8051
• EA’ / VPP ( pin 31 ): External Access
– It is used to enable/disable the external
memory interfacing.

• PSEN’ ( pin 29 ): Program Store Enable


– This is an output pin and is connected to the OE pin
of the ROM. When PSEN’= 0, then external
program memory becomes enabled and
microcontroller reads content of external memory
location.

04/30/18 24
Pins of 8051
• ALE ( pin 30 ): Address Latch Enable
– It is an output pin and is active high.
– The ALE pin is used for de-multiplexing the address
and data by connecting to the G pin of the 74LS373
latch.

• I/O port pins


– The four ports P0, P1, P2, and P3.
– Each port uses 8 pins.
– All I/O pins are bi-directional.

Monday, April 30, 2018


04/30/18 25
Pins of I/O Port

• The 8051 has 4 I/O ports


– Port 0 ( pins 32-39 ): P0 ( P0.0 ~ P0.7 )
– Port 1 ( pins 1-8 ) : P1 ( P1.0 ~ P1.7 )
– Port 2 ( pins 21-28 ): P2 ( P2.0 ~ P2.7 )
– Port 3 ( pins 10-17 ): P3 ( P3.0 ~ P3.7 )
• Each port has 8 pins.
• Named P0.X ( X=0,1,...,7 ) , P1.X, P2.X, P3.X
• Ex : P0.0 is the bit 0 ( LSB ) of P0
• Ex : P0.7 is the bit 7 ( MSB ) of P0
• Each port can be used as input or output (bi-direction).


04/30/18 26
Pins of 8051
Port1 (Pin1 to Pin8): these pins can be configured as  input
or  output pins.

Port2 (Pin 21 to Pin28): can be configured as Input Output


Pins. But, this is only possible  when external memory is not
used. If external memory is used, then these pins will work
as high order address bus.

Port3 (Pin 10 to 17): The Port 3 pins are similar to port 1


pins and can be used as universal I/O.

Port 0 (Pin 32 to 39): Similar to the port 2 and 3 pins,


these pins can be used as I/O pins external memory is not
used.
04/30/18 27
General signal flow diagram

04/30/18 28
Specific Features
• 8 bit cpu with registers A and B

• 16 bit PC and DPTR (data pointer).

• 8 bit program status word (PSW)

• 8 bit Stack Pointer (SP)

• 4K Internal ROM

• 128 bytes Internal RAM


– 4 register banks each having 8 registers
– 16 bytes,which may be addressed at the bit level.
– 80 bytes of general purpose data memory
04/30/18 29
8051
programming
model

04/30/18 30
8051 programming model
• 8051 is a collection of 8 & 16 bit registers and 8 bit memory
location.

• The registers and memory locations can be made to operate using


software instructions that are incorporated as part of design

• Most of the registers have specific functions and occupy individual


blocks for ex A , TH0 , PC etc.

• Other general registers are placed in ROM or RAM

• Each register has internal 1 byte address except PC

• Some registers are byte as well as bit addressable (* marked)

04/30/18 31
Internal memory

• 8051 implements a separate memory space for


programs (code) and data.

• Both code and data may be internal, however, both


expand using external components to a maximum of
64K code memory and 64K data memory.

• Internal memory consists of on-chip ROM and on-chip


data RAM.

04/30/18 32
Internal memory

• On-chip RAM contains a rich arrangement of general


purpose storage, bit addressable storage, register
banks, and special function registers.

• In the 8051, the registers and input/output ports are


memory mapped and accessible like any other memory
location.

• In the 8051, the stack resides within the internal


RAM, rather than in external RAM.

04/30/18 33
Memory And Register Organisation

• The 8051 has a separate memory space for code (programs) and
data.

04/30/18 34
Code / Data memory
• Code memory
– The executable program code is stored in this code memory.

– The code memory size is limited to 64KBytes (in a standard


8051).

– The code memory is read-only in normal operation and is


programmed under special conditions e.g. it is a PROM or a
Flash RAM type of memory.

• Data Memory
– This is read-write memory and is available for storage of data.

– Up to 64KBytes of external RAM data memory is supported (in


a standard 8051).
04/30/18 35
Internal memory
The 8051’s on-chip memory consists of 256 memory bytes
organised as follows:

First 128 bytes: ( Referred as internal RAM)


• 00h to 1Fh Register Banks
• 20h to 2Fh Bit Addressable RAM
• 30 to 7Fh General Purpose RAM

Next 128 bytes:


• 80h to FFh Special Function Registers

04/30/18 36
Internal RAM

04/30/18 37
Internal
Memory

04/30/18 38
Internal RAM – Divided into 3 parts
Ist
– 32 working registers organised as 32 Bytes from 00h to 1Fh
• Registers organized as 4 banks of 8 registers each
• 4 banks numbered 0 to 3 and 8 registers named R0 to R7
• Each register can be addressed by name or its RAM address
2nd
– A bit addressable area of 16 bytes occupies RAM address
from 20h to 2Fh
• Total addressable bits is 128
• Bit address from 00h to 7F h
• Byte address from 20h to 2fh
• Ex : Bit address 4Fh is also bit 7 of byte address 29h
3rd
– General purpose ; addressable as byte from 30h to 7Fh

04/30/18 39
Internal
RAM

04/30/18 40
Special function Register
• 8051 has 21 special function registers (SFRs) at the top of
internal RAM from address 80H to FFH.

• Each SFR has a very specific function. Each SFR has an address
(within the range 80h to FFh) and a name which reflects the
purpose of the SFR.

• Some SFR’s are both bit-addressable and byte addressable,


depending on the instruction accessing the register.

• This area consists of a series of memory-mapped ports and


registers.

• All 8051 CPU registers, I/O ports, timers and other architecture
components are accessible in 8051 C through SFRs

04/30/18 41
SFR

04/30/18 42
SFR and their Addresses

04/30/18 43
Accumulator

• The Accumulator is used as a general register to


accumulate the results of a large number of
instructions.

• It can hold an 8-bit (1-byte) value.

• It is the most versatile register of the 8051 due to


the large number of instructions that make use of the
accumulator.

• More than half of the 8051’s 255 instructions


manipulate or use the accumulator in some way.
04/30/18 44
B register
• The "B" register is very similar to the Accumulator in the sense
that it may hold an 8-bit (1-byte) value.

• The "B" register is only used by two 8051 operations: Multiply


and divide

• MUL AB: multiplies 8 bit unsigned values in A and B and leaves


the 16 bit result in A (low byte) and B (high byte).

• DIV AB: divided A by B, leaving the integer result in A and


remainder in B.

• Aside from the MUL and DIV instructions, the "B" register is
often used as yet another temporary storage register
• much like a ninth "R" register.

04/30/18 45
The data pointer (DPTR)

• The Data Pointer (DPTR) is the 8051’s only user-accessable 16-bit


(2-byte) register.

• DPTR, as the name suggests, is used to point to data. It is used


by a number of commands which allow the 8051 to access external
memory. When the 8051 accesses external memory it will access
external memory at the address indicated by DPTR.

• Many programmers often take advantage of the fact that it’s the
only true 16-bit register available. It is often used to store 2-
byte values which have nothing to do with memory locations.

04/30/18 46
Program counter (PC)
• The PC is a 2-byte address which tells the 8051 where
the next instruction to execute is found in memory.

• When the 8051 is initialized ,PC always starts at 0000h


and is incremented each time an instruction is executed.

• It is incremented by 1, 2 or 3 depending upon


instruction.

• The PC is special in that there is no way to directly


modify it’s value.

04/30/18 47
The Stack Pointer (SP)

• The Stack Pointer – 8 bit

• The SP is used to store and retrieve data quickly.

• SP is used to indicate where the next value to be removed from


the stack should be taken from.

• On pushing a value onto the stack, the 8051 first increments the
value of SP and then stores the value at the resulting memory
location.

• On popping a value off the stack, the 8051 returns the value from
the memory location indicated by SP, and then decrements the
value of SP.

04/30/18 48
I/O Ports
One of the major features of a microcontroller is the versatility
built into the I/O circuits that connect the microcontroller to the
outside world .

8051 has four bidirectional 8-bit I/O ports P0, P1, P2 and P3 .

Each port has an 8-bit latch in the SFR space .

To reduce the overall package pin count, the 8051 employs multiple
functions for each port.

Each port also has an output drive and an input buffer.

These ports can be used to general purpose I/O, as an address and


data lines.

04/30/18 49
Timers and counters

• Many microcontroller applications require the counting of external


events, such as frequency of a pulse train, or the generation of
precise internal time delays between actions.

• Both of these tasks can be accomplished using software


techniques.

• The 8051 has two 16-bit registers that can be used as either
timers or counters named T0 and T1 and are provided for general
use of the programmer.

• The counters are divided into two 8-bit registers called the timer
low (TL0, TL1) and timer high (TH0, TH1) bytes.

04/30/18 50
TMOD (timer mode) register
• TMOD is used to set various timer operations for T0 &T1

• TMOD is 8 bit register in which the lower 4 bits are set aside
for Timer 0 and upper 4 bits for timer 1

• Out of the 4 bits in each case, lower 2 bits are used to set
timer mode and upper 2 to specify the operation

04/30/18 51
TCON (timer control) register

• TCON is an 8 bit register.


• TR0 & TR1 flags of TCON are used to turn ON or OFF the
timers
• Upper 4 bits are used to store TF and TR bits of both timer 0
and timer 1
• Lower 4 bits are used for controlling the interrupt bits

04/30/18 52
Unit 2

Introduction to programming of microcontroller

04/30/18 53
Instruction
• An instruction is a command given to the computer to perform
a specified operation / task on given data.

• An instruction is a binary pattern designed inside a


microprocessor to perform a specific function

• An instruction consists of two parts:

• opcode (operation code) : specifies what operation / task to


be performed

• operand : data to be operated on is called the operand .

04/30/18 54
The 8051 Instructions
• 8085 is an 8-bit device so it can have up to 28 ( =
256) instructions

• However it has only 255 instructions. ( A5 missing)

• Most of the instructions have more than one format.


– 1 byte instruction
– 2 byte instruction
– 3 byte instruction

• The entire group of instructions is called


instruction set.

04/30/18 55
Instruction format

1 byte inst. 2 byte inst. 3 byte inst.

MOV A,Rr ADD A,#n MOV add,#n

04/30/18 56
The 8051 Instruction set
The instructions can be grouped into 05 different groups:

– Arithmetic operations

– Logical operations

– Data transfer operations

– Boolean variable operations

– Program branching operations

04/30/18 57
Arithmetic operations
These instructions perform arithmatic operations:

Addition : any 8-bit number , register content or memory content can


be added to contents of accumulator and result is stored in
accumulator. Ex ADD A,Rn ; ADD A , # data

Subtraction : any 8-bit number , register content or memory content


can be subtracted from the contents of accumulator and result is
stored in accumulator. Ex SUBB A,Rn ; , SUBB A,#data

Increment / decrement: The contents of register or memory location


can be incremented or decremented by 1. Ex INR A , DEC Rn

Multiply / Divide : Ex MUL AB ; DIV AB

04/30/18 58
Logical operations

These instructions perform various logical

AND , OR , Ex-OR : any 8-bit number , register content


or memory content can be logically ANDed , ORed , Ex-
ORed with contents of accumulator and result is stored in
accumulator. Ex ANL A,Rn ; ORL A, #30h

Rotate : Each bit in accumulator can be shifted either


left or right to next position. Ex RR A

Compliment : The contents of accumulator can be


complimented .Ex CPL A

04/30/18 59
Data Transfer Operations
This group of instructions copies data from a location called a source
to another location called a destination.

The data in the source is not changed. It is retained without any


modification

Data transfer instructions can be used to transfer data between an


internal RAM location and an SFR location without going through the
accumulator

It is also possible to transfer data between the internal and


external RAM

Ex MOV A,#25 ; MOV A,R0 ; XCH A, Rn

04/30/18 60
Boolean Variable Instructions

The C8051 processor can perform single bit operations

The operations include set, clear,AND, OR and


complement instructions

Also included are bit–level moves or conditional jump


instructions

Ex CLR C ; MOV C,b ; SETB b

04/30/18 61
Branching operations

This group of instructions alters the sequence of program


execution either conditionally or un conditionally

Ex
Jump : These instructions test for a certain conditions
( ex Zero or carry flag) and alter the sequence when the
condition is met. Ex JZ Over , JNZ Next

NOP : No operation

RET : Return from subroutine

04/30/18 62
Addressing modes
Instructions need to specify where to get operands from

Some possibilities
– Values are in the instruction
– Values are in the register
• Register number is in the instruction
– Values are in memory
• address is in instruction
• address is in a register
– register number is in the instruction
• address is register value plus some offset
– register number is in the instruction
– offset is in the instruction (or in a register)

These ways of specifying the operand locations are called addressing


modes
04/30/18 63
Types of addressing modes

The 8085 instruction set has the following addressing


modes :

– Immediate addressing

– Register addressing

– Direct addressing

– Indirect addressing

04/30/18 64
Immediate addressing
In this mode, the source operand is specified in the instruction
itself.
An immediate mode instruction has an operand field rather than the
address field.

Data must be preceded by pound sign , “#”

Example:
MOV A,#25h ; Load value 25 H into accumulator.
; 25 is the operand here.

MOV DPTR,#4521H ; Move 16-bit data constant 4521 into the 16-
; bit Data Pointer Register.

04/30/18 65
Register addressing

In this mode the operand is stored in the


register and this register is present in CPU.

The instruction has the address of the


Register where the operand is stored.

Ex
MOV A , R0 ; Copy the contents of
register R0 into accumulator
The register bank (Bank 0, 1, 2 or 3) must
be specified prior to this instruction.

ADD A,R7 ; add contents of R7 to A

04/30/18 66
Direct addressing
In this mode, effective address of
operand is present in instruction itself.

Single memory reference to access


data.

No additional calculations to find the


effective address of the operand

Ex
MOV R0,40h – save content of RAM
location 40h in R0

MOV 0E0h, #55H – Save 55H into A

MOV R4 , R7 – invalid ; as data


between Rn registers is not allowed

04/30/18 67
Indirect addressing
In this, the address field of
instruction gives the address where
the effective address is stored in
memory.

Ex
MOV @R1,B – Move contents of B into
RAM location ,whose address is held
by R1

When registers Rn are used as


pointers ( means they hold address of
RAM) they must be preceded by “@”
sign

04/30/18 68
Indexed Addressing Mode And On-Chip ROM Access

In this the contents of the indexed register is added to the Address


part of the instruction, to obtain the effective address of operand.

EA = A + (R), the address field holds two values, A (which is the base
value) and R (that holds the displacement), or vice versa.

Ex
•MOVC A,@A+DPTR :The address is formed by adding the content of
the DPTR register to the accumulator value. Here the DPTR = “base
address” ; Accumulator = “index address”.

04/30/18 69
8051 flag bits and the PSW register
Program Status word (PSW) Register

• It is an 8 bit register

• Only 6 bits are used

• Out of these 04 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 designated as RS0 and RS1. They are
used to change the bank registers.

• The two unused bits are user-definable

04/30/18 70
PSW

04/30/18 71
8051 flags
Carry flag ( CY)
This flag is set whenever there is carry out from D7 bit.
It can be set to 1 or 0 directly by instructions such as SETB C & CLR C

Auxiliary carry (AC)


It is set to 1 if there is a carry from D3 to D4 of the accumulator,
otherwise it is 0. It is used by instructions performing BCD arithmetic.

Parity (P) flag


It tells the number of 1s in Accumulator. P= 1 for odd number of 1s

Overflow flag (OV)


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

04/30/18 72
How to change register banks ?

Register bank 0 is default


Other banks can be switched with the help of RS0 and RS1 :

04/30/18 73
Assembling And Running An 8051 Program

Step 1
Use an editor to type a program. The source file has the extension
“asm“ or “src”.

Step 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”

04/30/18 74
Assembling And Running An 8051 Program
Step 3
Assembler requires 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

Step 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

04/30/18 75
Assembling And Running An 8051 Program

04/30/18 76
List file

04/30/18 77
Loop and Jump instructions
Loop

Repeating a sequence of instructions a certain number of times is


called a loop

Loop action is performed by

DJNZ reg, Label ; Decrement and jump if register ≠ 0


• The register is decremented
• If it is not 0, it jumps to the address specified by 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

04/30/18 78
Example for loop using DJNZ
Ex : WAP to add value 3 to the Accumulator 10 times and
save result in R5

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

Note : A loop can be repeated a maximum of 255 times, if R2 is


FFH

04/30/18 79
Example 2 for loop using DJNZ
Ex : WAP to add the first ten natural numbers and save result
in at RAM location 46H

MOV A , #0 ; A=0, clear ACC


MOV R2 , #10 ; load counter R2=10
MOV R0 , #0 ; Initialize R0 to 0
AGAIN: INC R0 ; increment R0 to hold the number
ADD A , R0 ; add 1st no to A i.e A= 1
DJNZ R2 , AGAIN ; Decrement & repeat until R2 = 0
MOV 46H , A ; save A in R5

04/30/18 80
Loop inside a loop
To repeat an action more than 256 times, a loop inside a loop
called nested loop is used
– � Here multiple registers are used to hold the count

Example : Write a program to (a) load the accumulator with the


value 55H, and (b) complement the ACC 700 times

MOV A , #55H ; A=55H


MOV R3 , #10 ; R3=10, outer loop count
NEXT: MOV R2 , #70 ; R2=70, inner loop count
AGAIN: CPL A ; complement A register
DJNZ R2 , AGAIN ; repeat it 70 times
DJNZ R3 , NEXT
MOV R5 , A

04/30/18 81
Conditional jumps
Jump only if a certain condition is met

All conditional jumps are short jumps . The address of the target must
be within -128 to +127 bytes of the contents of PC

04/30/18 82
Example conditional jump
JZ ( jump if A=0)

The contents of register a is checked . If it is 0 , control jumps


to address given by label

Ex :
MOV A , R0 ; A = R0
JZ OVER ; jump if A = 0
MOV A , R1 ; A = R1
JZ OVER ; jump if A = 0
...
OVER:

Here if R0 or R1 = 0 , control jumps to the label OVER

04/30/18 83
Unconditional jump
In this jump control is transferred unconditionally to the target
location

These are of 02 types :

LJMP (long jump)


3-byte instruction . 1st byte is the opcode . 2nd & 3rd bytes
represent the 16-bit target address i.e any memory location from
0000 to FFFFH

SJMP (short jump)


2-byte instruction . 1st byte is the opcode . 2nd byte is the relative
target address – 00 to FFH (forward +127 and backward -128 bytes
from the current PC)

04/30/18 84
Calculating the short address

All conditional jumps are short jumps as they are all 2 byte
instructions.

How to calculate the target address of a short jump (SJMP, JNC,


JZ, DJNZ, etc.) ?
The second byte of short jump instruction is added to the PC of
the instruction immediately below the jump

If the target address is more than -128 to +127 bytes from the
address below the short jump instruction

The assembler will generate an error stating the jump is out of


range

04/30/18 85
Calculating the short address
Line PC Opcode Label Mnemonic Operand
01 0000 ORG 0000
02 0000 78 00 MOV R0,#0
03 0002 74 55 MOV A,#55H
04 0004 60 03 JZ NEXT
05 0006 08 INC R0
06 0007 04 + AGAIN: INC A
07 0008 04 INC A
08 0009 24 77 NEXT: ADD A,#77H
09 000B 50 05 JNC OVER
10 000D E4 CLR A
11 000E F8 + MOV R0,A
12 000F F9 MOVR1,A
13 0010 FA MOV R2,A
14 0011 FB MOV R3,A
15 0012 2B OVER: ADD A,R3
16 0013 50 F2 JNC AGAIN
17 0015 80 FE HERE: SJMP HERE
18 0017 END

04/30/18 86
Time delay for various 8051 chips
CPU executing an instruction takes a certain number of clock cycles
� These are referred as to as machine cycles

The length of machine cycle depends on the frequency of the crystal


oscillator connected to 8051

In original 8051, one machine cycle lasts 12 oscillator periods

Ex : Find the period of the machine cycle for 11.0592 MHz crystal
frequency
Solution: 11.0592/12 = 921.6 kHz;
1 machine cycle is 1/921.6 kHz = 1.085μs

04/30/18 87
Time delay for various instructions
For 8051 system of 11.0592 MHz, find how long it takes to execute
each instruction.
(a) MOV R3,#55 (b) DEC R3 (c) DJNZ R2 target (d) LJMP (e) SJMP
(f) NOP (g) MUL AB

Solution:
Machine cycles Time to execute
(a) 1 1x1.085μs = 1.085μs
(b) 1 1x1.085μs = 1.085μs
(c) 2 2x1.085μs = 2.17μs
(d) 2 2x1.085μs = 2.17μs
(e) 2 2x1.085μs = 2.17μs
(f) 1 1x1.085μs = 1.085μs
(g) 4 4x1.085μs = 4.34μs

04/30/18 88
Example of delay in program
Find the size of the delay, if the crystal frequency is 11.0592MHz.

MOV A , #55H ; load a with 55h


AGAIN: MOV P1 , A ; send value to port 1
ACALL DELAY ; time delay
CPL A ; Complement register A
SJMP AGAIN ; do this indefinitely
;---time delay-------
DELAY: MOV R3 , #200 ; load R3 with 200
HERE: DJNZ R3 , HERE ; Dcr and jump if R3≠0
RET
Solution:
Machine cycle
DELAY: MOV R3,#200 1
HERE: DJNZ R3,HERE 2
RET 2

Therefore time delay = [(200x2)+1+2]x1.085μs = 436.255μs.

04/30/18 89
Example 2 : delay in program
Ex : Find the size of the delay in the program, if the crystal
frequency is 11.0592MHz.
Machine Cycle
DELAY: MOV R3, #250 1
HERE: NOP 1
NOP 1
NOP 1
NOP 1
DJNZ R3,HERE 2
RET 2
Solution:

The time delay inside HERE loop is [250(1+1+1+1+2)] x 1.085μs =


1627.5μs.

Adding the two instructions outside loop we have 1627.5μs + 3 x


1.085μs = 1630.755μs
04/30/18 90
Example 3 : delay in program
Ex : Find the delay, if the crystal frequency is 11.0592MHz.
Machine Cycle
DELAY: MOV R2,#200 1
AGAIN: MOV R3,#250 1
HERE: NOP 1
NOP 1
DJNZ R3, HERE 2
DJNZ R2, AGAIN 2
RET 2
Solution:
For HERE loop, time delay = (4x250)x1.085μs = 1085μs.

AGAIN loop repeats HERE loop 200 times, so delay = 200x1085μs =


217000μs.

Delay for “MOV R3,#250” & “DJNZ R2,AGAIN” (3x200x1.805)=1083μs.

Total delay 217000+1083=218083μs.

04/30/18 91
Arithmetic and logic instructions
ADD A , source ; A = A + source

The instruction ADD is used to add two operands

– Destination operand is always in register A

– Source operand can be a register, immediate data, or in


memory

– Memory-to-memory arithmetic operations are not allowed in


8051 Assembly language

– The instruction can change any of the AF,CF or P bits


of the flag register depending on the operands involved

04/30/18 92
Example ADD
Ex : Assume that RAM locations 40 – 44H have the following
values. WAP to find the sum of the values. At the end , register
A should contain the low byte and R7 the high byte.
40 = (7D) ; 41 = (EB) ; 42 = (C5) ; 43 = (5B) ; 44 = (30)

Solution:
MOV R0, #40H ; load pointer
MOV R2, #5 ; load counter
CLR A ; A= 0
MOV R7, A ; clear R7
AGAIN: ADD A, @R0 ; add the byte ptr to A by R0
JNC NEXT ; if CY=0 don’t add carry
INC R7 ; keep track of carry
NEXT: INC R0 ; increment pointer
DJNZ R2, AGAIN ; repeat until R2 is zero

04/30/18 93
ADDC instruction
ADDC A , source byte ; Add with carry

When adding two 16-bit data operands, the propagation of a carry


from lower byte to higher byte is to be taken care of

1
3C E7
+ 3B 8D
78 74

04/30/18 94
Example ADDC

Ex : WAP to add two 16-bit numbers (3CE7h & 3B8Dh). Place


the sum in R7 and R6; R6 should have the lower byte.
Solution:

CLR C ; make CY=0


MOV A, #0E7H ; load the low byte now A=E7H
ADD A, #8DH ; add the low byte
MOV R6, A ; save the low byte sum in R6
MOV A, #3CH ; load the high byte
ADDC A, #3BH ; add with the carry
MOV R7, A ; save the high byte sum

04/30/18 95
BCD number system

Unpacked BCD

– In unpacked BCD, the lower 4 bits of the number represent


the BCD number, and the rest of the bits are 0

– Ex. 00001001 and 00000101 are unpacked BCD for 9 and 5

Packed BCD

– In packed BCD, a single byte has two BCD number in it, one
in the lower 4 bits, and one in the upper 4 bits

– Ex. 0101 1001 is packed BCD for 59H

04/30/18 96
Adding two BCD numbers
The addition of two BCD numbers must give a BCD result.

Ex :
MOV A, #17H
ADD A, # 28H

If both numbers are in BCD then the result should be 17 + 28 =


45 (0100 0101).
But it gives 3Fh ( 0011 1111) . F is not BCD

To correct this problem, the programmer must add 6 (0110) to


the lower digit of 3F.
i.e 3F + 06 = 45H.

04/30/18 97
DA instruction
DA A ; decimal adjust for addition

The DA instruction is provided to correct the problem associated


with BCD addition

The DA instruction will add 6 to the lower nibble or higher nibble if


required

Example
MOV A, #47H ; A=47H first BCD operand
MOV B, #25H ; B=25H second BCD operand
ADD A, B ; hex (binary) addition (A=6CH)
DA A ; adjust for BCD addition (A=72H)

Note : The “DA” instruction works only on A.


DA works only after ADD instruction ; it will not work
after INC instruction

04/30/18 98
Summary of DA instruction

After an ADD or ADDC instruction


1. If the lower nibble (4 bits) is greater than 9, or if AC=1,
add 0110 to the lower 4 bits
2. If the upper nibble is greater than 9, or if CY=1, add
0110 to the upper 4 bits
Ex : Add BCD nos 29 and 18

04/30/18 99
Multiplication
The 8051 supports byte by byte multiplication only
– The byte are assumed to be unsigned data

MUL AB ; AxB, 16-bit result in B, A

Ex:
MOV A,#25H ; load 25H to reg. A
MOV B,#65H ; load 65H to reg. B
MUL AB ; 25H * 65H = E99 where
; B = 0EH and A = 99H

Note : Lower byte of result in A , while higher byte is in B

04/30/18 100
Division
The 8051 supports byte by byte division only
– The byte are assumed to be unsigned data

DIV AB ; A/B, result in B, A

Ex:
MOV A, #95H ; load 95H to reg. A
MOV B, #10H ; load 10H to reg. B
MUL AB ; A= 09 (quotient)
; B = 05 (remainder)

Note : CY = 0 and OV = 0 if denominator (B) is not 0


If B = 0 then OV = 1 ( indicating error) & CY = 0

04/30/18 101
Programming in C

Compilers produce hex files that is downloaded to ROM of the


microcontroller
– The size of hex file is the main concern
• Microcontrollers have limited on-chip ROM
• Code space for 8051 is limited to 64K bytes

C programming is less time consuming, but has larger hex file size

The reasons for writing programs in C


– It is easier and less time consuming to write in C than Assembly
– C is easier to modify and update
– You can use code available in function libraries
– C code is portable to other microcontroller with little or no
modification

04/30/18 102
Data types

A good understanding of C data types for 8051 can help


programmers to create smaller hex files
– Unsigned char
– Signed char
– Unsigned int
– Signed int
– Sbit (single bit)
– Bit and sfr

04/30/18 103
Data type – unsigned char

• 8051 is an 8-bit microcontroller so the character data


type is the most natural choice

• Unsigned char is an 8-bit data type in the range of 0 –


255 (00 – FFH) and is the most widely used data
types for the 8051
• Counter value

• ASCII characters

• C compilers use the signed char as the default if we do


not put the keyword unsigned

04/30/18 104
Template of 8051 C program

# include <reg51.h>
define variable ; /* Global variables – accessible by all functions */

Function_type function_name (variable_type variable_name);


{
- - - - - - - - - - - - - - - - - -;
- - - - - - - - - - - - - - - - - -;
}
Void main ()
{
- - - - - - - - - - - - - - - - - -;
- - - - - - - - - - - - - - - - - -;
}

04/30/18 105
Template
#
– This symbol calls header file.
– Header file is program which include many function.

#include reg51.h
– Preprocessor directive
– Used to include a header-file for the registers (SFRs) in the
source file
– Provides the related SFR declarations of the data type,
addresses, pointers and operations during the compilation of
the source file

04/30/18 106
WAP to send values 00 – FF to port P1

#include <reg51.h>
void main (void)
{
unsigned char z;
for (z=0;z<=255;z++)
P1=z;
}

04/30/18 107
WAP to toggle the bits of P1 continuously.

//Toggle P1 forever//
#include <reg51.h>
void main (void)
{
for (;;)
{
p1=0x55; //0x indicates data is in hex
p1=0xAA;
}
}

04/30/18 108
WAP to write 0x75 at port P0

#include <reg51.h> /* Include header file/


void main (void) /* main function */
{
unsigned char portByte; /* Declare variable portByte */
portByte = 0x75; /* portByte variable is assigned the
value= 01110101 */
P0 = portByte; /* P0 is assigned (written) the value
of portByte */
}

04/30/18 109
WAP to send values of -4 to +4 to port P1.
Solution: use signed characters

#include <reg51.h>
void main (void)
{
Char mynum []={+1,-1,+2,-2,+3,-3,+4,-4};
unsigned char z;
for (z=0; z<8; z++)
P1= mynum [z];
}

04/30/18 110
WAP to toggle bit D0 of the port P1 (P1.0)
50,000 times.

Solution: Single bit data type

#include <reg51.h> sbit keyword allows access to the


single bits of the SFR registers
sbit MYBIT= P1^0;

void main(void)
{
unsigned int z;
for (z=0;z<=50000;z++)
{
MYBIT=0;
MYBIT=1;
}
}

04/30/18 111
Time delay
There are two ways to create a time delay in 8051 C
– � Using the 8051 timer
– � Using a simple ‘for’ loop

Three factors that can affect the accuracy of the delay :

The 8051 design


– The number of machine cycle
– The number of clock periods per machine cycle

The crystal, frequency, connected to the X1 – X2 input pins

Compiler choice
– Different compilers produce different code

04/30/18 112
WAP to toggle bits of P1 continuously
forever with some delay.
Solution :Toggle P1 forever with some delay in between “on” and “off”

#include <reg51.h>
void main (void)
{
unsigned int x;
for (;;) //repeat forever
{
p1=0x55;
for (x=0;x<40000;x++); //delay size unknown
p1=0xAA;
for (x=0;x<40000;x++);
}
}

04/30/18 113
Unit 3
Timer Programming

04/30/18 114
Timer
The 8051 has 02 timers / counters, that 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.
The timers are divided into two 8-bit registers called the
timer low (TL0, TL1) and timer high (TH0, TH1) bytes.

04/30/18 115
Timer

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

Each bit of the SFR gives the microcontroller specific information


concerning how to run a timer.

TMOD is a 8-bit register


– � The lower 4 bits are for Timer 0
– � The upper 4 bits are for Timer 1

� In each case,
– � The lower 2 bits are used to set the timer mode
– � The upper 2 bits to specify the operation

04/30/18 116
TMOD

04/30/18 117
TMOD - GATE

GATE :

Timers of 8051 start and stop by either software or hardware control.

The software way to start and stop the timer is when GATE=0
– The start and stop of the timer are controlled by the TR (timer
start) bits TR0 and TR1
– The SETB instruction starts it, and the CLR instruction stops it.
– Ex SETB TR1 and CLR TR1

The hardware way of starting and stopping the timer by an external


source is achieved by making GATE=1 in the TMOD register

04/30/18 118
TMOD – clock / timer
C/T ( clock / timer)

– This bit in TMOD is used to decide whether the timer


is used as delay generator or an event counter.

– If C/T = 0, it is used as a timer for time delay


generation and crystal frequency attached to the 8051
is the source of clock for timer.

– The frequency of timer is always 1/12th the frequency


of crystal

04/30/18 119
Example 1
Which mode and which timer are selected for each of the
following.
(a) MOV TMOD, #01H (b) MOV TMOD, #20H (c) MOV
TMOD, #12H

Sol :
Convert the value from hex to binary.
– 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.

04/30/18 120
Example 2

Find the timer’s clock frequency and its period for various
8051-based system, with the crystal frequency 11.0592
MHz when C/T bit of TMOD is 0.

Solution:
1/12 × 11.0529 MHz = 921.6 MHz;
T = 1/921.6 kHz = 1.085 us

04/30/18 121
Timer Mode 0
Timer Mode 0 is a 13 bit timer.

Generally it is not used in new developments but is kept


to maintain compatibility with its predecessor 8048.

Only 13 bits are used. Bits 0-4 of TLX and bits 0-7 of
THX.

TLX will count from 0 to 31. When TLX is incremented


from 31, it will “reset” to 0 and increment THX. In
essence the counter can contain values from 0 to 8192

04/30/18 122
Timer mode 1
It is a 16 bit timer hence 65536 distinct values.

TLX will count from 0 to 255. When TLX is incremented


from 255, it will “reset” to 0 and increment THX and
continue counting upto 65535 ( FFFFH).

Operation of timer :
TH and TL are loaded with initial 16 bit value & timer is
started.
– done by SETB TR0 for timer 0 and SETB TR1 For
timer 1
It counts up until it reaches its limit FFFH
04/30/18 123
Timer Mode 1 contd
When it rolls over from FFFFH to 0000, Timer flag TF is set high.
– TF0 for timer 0, and TF1 for timer 1
– This timer flag can be monitored

When TF is raised, one option would be to stop the timer with the
instructions CLR TR0 or CLR TR1, for timer 0 and timer 1,
respectively

In order to repeat the process TH and TL must be reloaded with


the original value, and TF must be reloaded to 0

04/30/18 124
To generate time delay using Mode 1
1. Load the TMOD value register indicating which timer (timer 0
or timer 1) is to be used and which timer mode (0 or 1) is
selected

2. Load registers TL and TH with 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. 04/30/18
Go back to Step 2 to load TH and TL again 125
WAP to create a square wave on P1.5
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 ; Compliment i.e toggle P1.5
ACALL DELAY ; Delay subroutine using timer is called
SJMP HERE ; Load TH and TL again

; ------------------Delay using timer 0


SETB TR0 ; start the timer 0
AGAIN: JNB TF0 , AGAIN ; Jump if bit is 0 ;; monitor timer flag 0
; until it rolls over
CLR TR0 ; stop timer 0
CLR TF0 ; clear timer 0 flag
RET

04/30/18 126
Amount of delay in previous slide
Calculate the amount of time delay in the DELAY subroutine .
Assume XTAL = 11.0592 MHz.

Solution:
Each clock pulse has a period of T = 1/921.6kHz = 1.085us.

The number of counts for FFFFH – FFF2H = 0DH = 13 (decimal)

However, add one to 13 because of the extra clock needed when it


rolls over from FFFF to 0 and raise the TF flag. i.e 14

Delay for half pulse = 14 × 1.085us = 15.19us

Delay for the entire period T = 2 × 15.19us = 30.38us

04/30/18 127
Timer mode 2

It is an 8 bit auto reload timer

In mode 2 THx holds the ‘reload value’ where TLx is the


actual timer.

When the TLx reaches 255 (FFh) and is subsequently


incremented instead of resetting to 0 it will reset to
value stored in THx

04/30/18 128
Timer mode 2
For example let initially TH0 = FDh and TL0 = FEh. After
running the following will be the scenario :

Machine cycle TH0 value TL0 value


1 FDh FEh
2 FDh FFh
3 FDh FDh
4 FDh FEh
5 FDh FFh
6 FDh FD
7 FDh FEh
8 FDh FFh

04/30/18 129
To generate time delay using Mode 2
Load the TMOD value register indicating which timer (timer 0
or 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
– � Get out of the loop when TF goes high

Clear the TF flag

Go back to Step4, since mode 2 is autoreload

04/30/18 130
Timer mode 2

04/30/18 131
Benefit of auto-reload

Suppose it is required that the timer has to have values from


200 to 255

If mode 0 and 1 are used , a programmer has to check in the


code to see if the timer had overflowed and if yes , reset the
timer to 200.

This takes precious instructions of execution time to check the


value and /or reload it

In mode 2 the microcontroller takes care of this for you.

Programmer does not have to worry for checking timer overflow


as well as resetting.

04/30/18 132
Mode 3
Mode 3 is split timer mode

When timer 0 is placed in mode 3 , it essentially becomes 02


separate 8 bit timers ie Timer 0 TL0 and Timer 0 TH0

Both timers count from 0 to 255 and overflow back to 0

All the control bits related to timer 1 are tied to TH0 i.e
TR1 and TF1

Timer 1 (i.e TH1 & TL1) can be put to mode 0 , 1 or 2


normally.

Application : Timer 1 can be used as baud rate generator and


TH0/TH1 can be used as 02 separate timers

04/30/18 133
Basics of Serial communication
Computers transfer data in two ways:

Parallel
Often 8 or more lines (wire conductors) are
used to transfer data to a device that is
only a few feet away

Serial
To transfer to a device located many
meters
away, the serial method is used
The data is sent one bit at a time

04/30/18 134
Serial communication
Serial data communication uses two methods

Synchronous method transfers a block of data at a time

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 , so
special ICs - UART (universal asynchronous Receiver
transmitter) USART (universal synchronous-asynchronous
Receiver-transmitter) are used.

04/30/18 135
8051 connection to RS232
As the RS232 is not compatible with today’s microprocessor and
microcontroller so a line driver (voltage converter) is required to
convert RS232 to TTL voltage levels that will be acceptable to
8051’s TxD and RxD pins

04/30/18 136
Data transfer rate in 8051

The rate of data transfer in serial data communication is


stated in bps (bits per second)

Another widely used terminology for bps is baud rate

It is defined as the number of signal changes per second.

In modems, there are occasions when a single change of signal


transfers several bits of data

The simplest connection between a PC and microcontroller


requires a minimum of three pins, TxD, RxD, and ground

04/30/18 137
Baud rate in 8051

The 8051 transfers and receives data serially at many


different baud rates.

The baud rate in 8051 is programmable.

This is done with the help of Timer 1.

The 8051 divides the crystal frequency by 12 to get machine


cycle frequency.

The 8051’s UART circuitry further divides this by 32 before


it is used by Timer 1

04/30/18 138
Serial communication using SBUF register

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 and 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
deframes it by eliminating the stop and start bits,
making a byte out of the data received, and then
placing it in SBUF

04/30/18 139
SCON ( serial control) register
SCON is an 8-bit register used to program the start bit, stop
bit, and data bits of data framing

SM0 Serial port mode specifier


SM1 Serial port mode specifier
SM2 Used for multiprocessor communication
REN Set/cleared by software to enable/disable reception
TB8 Not widely used
RB8 Not widely used
TI Transmit interrupt flag. Set by HW at the begin of the
stop bit mode 1. And cleared by SW
RI Receive interrupt flag. Set by HW at the begin of the stop
bit mode 1. And cleared by SW

04/30/18 140
SCON Register

SM0, SM1 : They determine the framing of data by specifying


the number of bits per character, and the start and stop bits

SM0 SM1
0 0 Serial Mode 0
0 1 Serial Mode 1, 8-bit
data, 1 stop bit, 1 start bit
1 0 Serial Mode 2
1 1 Serial Mode 2

SM2 : This enables the multiprocessing capability of the 8051

04/30/18 141
SCON Register
REN (receive enable) : It is a bit-adressable register
– When it is high, it allows 8051 to receive data on RxD pin
– If low, the receiver is disable

TI (transmit interrupt) : When 8051 finishes the transfer of 8-bit


character
– It raises TI flag to indicate that it is ready to transfer another
byte
– TI bit is raised at the beginning of the stop bit

RI (receive interrupt) : When 8051 receives data serially via RxD, it


gets rid of the start and stop bits and places the byte in SBUF
register
– It raises the RI flag bit to indicate that a byte has been
received and should be picked up before it is lost
– RI is raised halfway through the stop bit

04/30/18 142
Programming 8051 to transfer data serially
Following steps must be taken to transfer 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 baud rate

2. The TH1 is loaded with one of the values to set 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
stop bits

4. TR1 is set to 1 to start timer 1

04/30/18 143
Programming 8051 to transfer data serially

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

04/30/18 144
Interrupt structure of 8051
Interrupt is a signal send by an external device to the processor to
perform a particular task or work.

When µC receives interrupt signal, it discontinues whatever it was


executing.

It starts executing new program ( known as Interrupt Service Routine )


as indicated by the interrupt signal.

After execution of the new program, µC goes back to the previous


program.

Main Program Main Program Main Program

Printer Interrupt Modem Interrupt

04/30/18 145
How to serve several devices?
A single microcontroller can serve several devices .
There are two ways to do it : a) Interrupt b) Polling

Interrupt :
Whenever any device needs its service, the device notifies the
microcontroller by sending it an interrupt signal

When µC receives interrupt signal, it discontinues whatever it was


executing.

It starts executing new program ISR as indicated by the interrupt


signal.

After execution of the new program, µC goes back to the previous


program.
04/30/18 146
Polling mode
Polling can monitor the status of several devices and serve
each of them as certain conditions are met

Polling process
• 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 and so


on until every one is serviced

04/30/18 147
Interrupt vs Polling

The polling method is not efficient, since it wastes much of the


microcontroller’s time by polling devices that do not need
service.

In case of interrupt mode , Each devices can get the attention


of the microcontroller based on the assigned priority attached
to it.

For the polling method, it is not possible to assign priority


since it checks all devices in a round-robin fashion

In interrupt mode , the µC can also ignore (mask) a device


request for service. This is not possible for the polling method

04/30/18 148
Interrupt Vectors and the Vector Table

For every interrupt, there is a fixed location in memory that


holds the address of its ISR

An interrupt vector is a pointer to where the ISR is stored in


memory.

The group of memory locations set aside to hold the addresses


of ISRs is called interrupt vector table

– The IVT is usually located in memory page 00 (0000H


-0023H).

– The purpose of the IVT is to hold the vectors that


redirect the µC to the right place when an interrupt
arrives.
04/30/18 149
Interrupts of 8051

The 06 interrupts are:

• Reset – power-up reset

• Timer 0 interrupt (TF0)

• Timer 1 interrupt (TF1)

• External hardware interrupt 0 - INT0 (or EX1)

• External hardware interrupt 1 - INT1 (or EX2)

• Serial COM Interrupt


04/30/18 150
Vector addresses
The vector address for these interrupts are :

04/30/18 151
Steps in Executing an Interrupt
Upon activation of an interrupt, the microcontroller goes
through the following steps

1. It finishes the instruction it is executing and saves


the address of the next instruction (PC) on the
stack

2. It also saves the current status of all the interrupts


internally (i.e: not on the stack)

3. It jumps to a fixed location in memory, called the


interrupt vector table, that holds the address of
the ISR

04/30/18 152
Steps in Executing an Interrupt
4. The µC gets the address of the ISR from the interrupt vector
table and jumps to it

– It starts to execute the ISR until it reaches the last


instruction of the subroutine which is RETI (return from
interrupt)

5. Upon executing the RETI instruction, the µC returns to the


place where it was interrupted

– First, it gets the program counter (PC) address from the


stack by popping

– Then it starts to execute from that address

04/30/18 153
Enabling and Disabling an Interrupt
Upon reset, all interrupts are disabled (masked), meaning
that none will be responded to by the µC 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

04/30/18 154
Interrupt Enable Register

EA -- ET2 ES ET1 EX1 ET0 EX0

EA Disables all interrupts . If EA= 0 no interrupt is


acknowledged . If EA=1 each interrupt is individually enabled
/ disabled.
-- Not implemented, reserved for future use
ET2 Enables or disables timer 2 overflow or capture interrupt
(8052 only)
ES Enables or disables the serial port interrupt
ET1 Enables or disables timer 1 overflow interrupt
EX1 Enables or disables external interrupt 1
ET0 Enables or disables timer 0 overflow interrupt
EX0 Enables or disables external interrupt

04/30/18 155
Enable an interrupt
To enable an interrupt, we take the following steps:

1. Bit D7 of the IE register (EA) must be set to high to allow


the rest of register to take effect

2. The value of EA

– If EA = 1, interrupts are enabled and will be responded
to, if their corresponding bits in IE are high i.e 1

– If EA = 0, no interrupt will be responded to, even if the
associated bit in the IE register is high i.e 1

04/30/18 156
THANK YOU

04/30/18 157

You might also like