Sunteți pe pagina 1din 135

UnitI

THE 8085 AND 8086 MICROPROCESSORS

1.Explainindetailaboutthegeneralblockdiagramofamicrocomputerandmicroprocessor?

A computer is a multipurpose programmable machine that reads binary


instructions from its memory , accepts binary data as input ,processes the data according to
thoseinstructionsandprovidesresultsasoutput.Itisaprogrammabledevicemadeupofboth
hardwareandsoftware.Thevariouscomponentsofthecomputerarecalledhardware.Asetof
instructionswrittenforthecomputertosolveaspecifictaskiscalledprogramandcollectionof
programsiscalledsoftware.
Thecomputerhardwareconsistsoffourmaincomponents.Thecentralprocessingunit
whichactsascomputersbrain.Inputunitthroughwhichprogramanddatacanbeenteredto
computer, output unit on which the results of the computations can be displayed. Memory in
whichdataandprogramarestored.

CPU

Data

RAM
Bus

RO
M

I/P

Gene
eralralAddres
General-Purpose
Purp
s Bus
Microprocessor System
ose
ose
P

O/
P

Blockdiagramofamicrocomputer

A computer that is designed using a microprocessor as its CPU , is known as a


microcomputer.
Microprocessors

A microprocessor is a general purpose digital computer central processing unit (CPU).


Although known as a Computer on Chip the Microprocessor in no sense a complete digital
computer.BlockdiagramofaMicroprocessorCPUwhichcontainsALU;Programcounter(PC),a
stackpointer(SP),someworkingregisters,aclocktimingcircuitandinterruptcircuitsisshownin
thefollowingfigure.
To make a computer microcomputer one must add memory usually RAM and ROM,
memorydecoders,anoscillatorandanumberofInput,Outputdevicessuchasserialandparallel
ports.Inadditionspecialpurposedevicessuchasinterrupthandlerandcountersmaybeadded
torelievetheCPUfromtimeconsumingcountingortimingcores.WhentheMicrocomputeris
equipped with mass storage devices , I/O peripherals such as a key board and a display CRT it
yieldsasmallcomputerthatcanbeappliedtoarangeofgeneralpurposeapplications

ArithmeticandLogic
Unit

Accumulator

WorkingRegister

ProgramCounter

StackPointer

ClockCircuit

InterruptCircuits

BlockDiagramofaMicroprocessor


.
Thehardwaredesignofamicroprocessorisarrangedsuchthataverysmallorverylargesystem
can be configured around the CPU as the application demands.The prime use of the
Microprocessor is to read data , perform extensive calculations on that data, and store those
calculationsinamassstoragedeviceordisplaytheresultsforhumanuse.Theprogramsusedby
microprocessorarestoredinthemassstoragedeviceandloadedintoRAMasuserdirects.Afew
microprocessorprogramarestoredinROM.TheROMbasedprogramsareprimarilysmallfixed
programsthatoperateperipheralsandotherfixeddevicesthatareconnectedtothesystem.

2..Explainthearchitectureof8085microprocessor?

ControlUnit

Generates signals within uP to carry out the instruction, which has been decoded. In
realitycausescertainconnectionsbetweenblocksoftheuPtobeopenedorclosed,sothatdata
goeswhereitisrequired,andsothatALUoperationsoccur.
ArithmeticLogicUnit.TheALUperformstheactualnumericalandlogicoperationsuchasadd,
subtract,AND,OR,etc.UsesdatafrommemoryandfromAccumulatortoperformarithmetic.
AlwaysstoresresultofoperationinAccumulator.

Registers

The 8085/8080Aprogramming model includes six registers, one accumulator, and one
flagregister,asshowninFigure.Inaddition,ithastwo16bitregisters:thestackpointerandthe
programcounter.Theyaredescribedbrieflyasfollows.

The 8085/8080A has six generalpurpose registers to store 8bit data; these are identified as
B,C,D,E,H,andLasshowninthefigure.TheycanbecombinedasregisterpairsBC,DE,andHL
toperformsome16bitoperations.Theprogrammercanusetheseregisterstostoreorcopydata
intotheregistersbyusingdatacopyinstructions.

Accumulator
Theaccumulatoris an8bitregisterthatisapartof arithmetic/logicunit(ALU).Thisregister is
used to store 8bit data and to perform arithmetic and logical operations. The result of an
operationisstoredintheaccumulator.TheaccumulatorisalsoidentifiedasregisterA.

Flags

The ALU includes five flipflops, which are set or reset after an operation according to
dataconditionsoftheresultintheaccumulatorandotherregisters.TheyarecalledZero(Z),Carry
(CY),Sign(S),Parity(P),andAuxiliaryCarry(AC)flags
Forexample,afteranadditionoftwonumbers,ifthesumintheaccumulatoridlargerthaneight
bits, the flipflop uses to indicate a carry called the Carry flag (CY) is set to one. When an
arithmetic operation results in zero, the flipflop called the Zero(Z) flag is set to one. The first
Figureshowsan8bitregister,calledtheflagregister,adjacenttotheaccumulator.However,itis
notusedasaregister;fivebitpositionsoutofeightareusedtostoretheoutputsofthefiveflip
flops.Theflagsarestoredinthe8bitregistersothattheprogrammercanexaminetheseflags

(data conditions) by accessing the register through an instruction. These flags have critical
importanceinthedecisionmakingprocessofthemicroprocessor.Theconditions(setorreset)of
theflagsaretestedthroughthesoftwareinstructions.Forexample,theinstructionJC(Jumpon
Carry) isimplementedtochangethesequenceofaprogramwhenCYflag is set.Thethorough
understandingofflagisessentialinwritingassemblylanguageprograms.

ProgramCounter(PC)

This16bitregisterdealswithsequencingtheexecutionofinstructions.Thisregisterisamemory
pointer.Memorylocationshave16bitaddresses,andthatiswhythisisa16bitregister.
Themicroprocessorusesthisregistertosequencetheexecutionoftheinstructions.
Thefunctionoftheprogramcounteristopointtothememoryaddressfromwhichthenextbyte
is to be fetched. When a byte (machine code) is being fetched, the program counter is
incrementedbyonetopointtothenextmemorylocation
StackPointer(SP)
Thestackpointerisalsoa16bitregisterusedasamemorypointer.Itpointstoamemory
locationinR/Wmemory,calledthestack.Thebeginningofthestackisdefinedbyloading16bit
addressinthestackpointer.

InstructionRegister/Decoder

Temporary store for the current instruction of a program. Latest instruction sent here from
memory prior to execution. Decoder then takes instruction and decodes or interprets the
instruction.Decodedinstructionthenpassedtonextstage.

MemoryAddressRegister

Holds address, received from PC, of next program instruction. Feeds the address bus with
addressesoflocationoftheprogramunderexecution.

ControlGenerator

GeneratessignalswithinuPtocarryouttheinstructionwhichhasbeendecoded.Inrealitycauses
certainconnectionsbetweenblocksoftheuPtobeopenedorclosed,sothatdatagoeswhereit
isrequired,andsothatALUoperationsoccur.

RegisterSelector

Thisblockcontrolstheuseoftheregisterstackintheexample.Justalogiccircuitwhichswitches
betweendifferentregistersinthesetwillreceiveinstructionsfromControlUnit.

GeneralPurposeRegisters

uPrequiresextraregistersforversatility.Canbeusedtostoreadditionaldataduringaprogram.
Morecomplexprocessorsmayhaveavarietyofdifferentlynamedregisters.

3.Explainthepindiagramof8085microprocessor?

Properties

Single+5VSupply
4VectoredInterrupts(OneisNonMaskable)
SerialIn/SerialOutPort
Decimal,Binary,andDoublePrecisionArithmetic
DirectAddressingCapabilityto64Kbytesofmemory
The Intel 8085A is a new generation, complete 8 bit parallel central processing unit(CPU). The
8085Ausesamultiplexeddatabus.Theaddressissplitbetweenthe8bitaddressbusandthe8bit
databus.Figuresareattheendofthedocument.

PinDescription

Thefollowingdescribesthefunctionofeachpin:

AD0AD7(Input/Output3state)

Multiplexed Address/Data Bus;Lower 8 bits ofthe memory address (orI/0 address) appear on
thebusduringthefirstclockcycleofamachinestate.Itthenbecomesthedatabusduringthe
secondandthirdclockcycles.3statedduringHoldandHaltmodes.

ALE(Output)

Address Latch Enable: It occurs during the first clock cycle of a machine state and enables the
address to get latched into the on chip latch of peripherals. The falling edge of ALE is set to
guaranteesetupandholdtimesfortheaddressinformation.ALEcanalsobeusedtostrobethe
statusinformation.ALEisnever3stated.

SO,S1(Output)

DataBusStatus.Encodedstatusofthebuscycle:
S1 S0

00

HALT

WRITE

READ

FETCH

S1canbeusedasanadvancedR/Wstatus.

RD(Output3state)

READ; indicates the selected memory or 1/0 device is to be read and that the Data Bus is
availableforthedatatransfer.

WR(Output3state)

WRITE; indicates the data on the Data Bus is to be written into the selected memory or 1/0
location.DataissetupatthetrailingedgeofWR.3statedduringHoldandHaltmodes.

READY(Input)

IfReadyishighduringareadorwritecycle,itindicatesthatthememoryorperipheralisreadyto
sendorreceivedata.IfReadyislow,theCPUwillwaitforReadytogohighbeforecompletingthe
readorwritecycle.

HOLD(Input)

HOLD; indicatesthat another Master isrequesting theuse of the Address and DataBuses. The
CPU,uponreceivingtheHoldrequest.willrelinquishtheuseofbusesassoonasthecompletion
of the current machine cycle. Internal processing can continue. The processor can regain the
buses only after the Hold is removed. When the Hold is acknowledged, the Address, Data, RD,
WR,andIO/Mlinesare3stated.

HLDA(Output)


HOLD ACKNOWLEDGE; indicates that the CPU has received the Hold request and that it will
relinquish thebuses in thenextclock cycle. HLDA goes low after theHoldrequest isremoved.
TheCPUtakesthebusesonehalfclockcycleafterHLDAgoeslow.

INTR(Input)

INTERRUPTREQUEST;isusedasageneralpurposeinterrupt.Itissampledonlyduringthenextto
the last clock cycle of the instruction. If it is active, the Program Counter (PC) will be inhibited
fromincrementingandanINTAwillbeissued.DuringthiscycleaRESTARTorCALLinstructioncan
be inserted to jump to the interrupt service routine. The INTR is enabled and disabled by
software.ItisdisabledbyResetandimmediatelyafteraninterruptisaccepted.

INTA(Output)

INTERRUPTACKNOWLEDGE;isusedinsteadof(andhasthesametimingas)RD
during the Instruction cycle after an INTR is accepted. It can be used to activate the 8259
Interruptchiporsomeotherinterruptport.
RST5.5
RST6.5(Inputs)
RST7.5
RESTARTINTERRUPTS; Thesethree inputs havethe same timing asI NTRexcept they causean
internalRESTARTtobeautomaticallyinserted.
RST7.5HighestPriority
RST6.5
RST5.5LowestPriority
Thepriorityoftheseinterruptsisorderedasshownabove.Theseinterruptshaveahigherpriority
thantheINTR.

TRAP(Input)

Trapinterruptisanonmaskablerestartinterrupt.ItisrecognizedatthesametimeasINTR.Itis
unaffectedbyanymaskorInterruptEnable.Ithasthehighestpriorityofanyinterrupt.

RESETIN(Input)

ResetsetstheProgramCountertozeroandresetstheInterruptEnableandHLDAflipflops.None
oftheotherflagsorregisters(excepttheinstructionregister)areaffectedTheCPUisheldinthe
resetconditionaslongasResetisapplied.

RESETOUT(Output)

Indicates CPlJ is being reset. Can be used as a system RESET. The signal is synchronized to the
processorclock.

X1,X2(Input)

CrystalorR/CnetworkconnectionstosettheinternalclockgeneratorX1canalsobeanexternal
clockinputinsteadofacrystal.Theinputfrequencyisdividedby2togivetheinternaloperating
frequency.

CLK(Output)

ClockOutputforuseasasystemclockwhenacrystalorR/Cnetworkisusedasaninputtothe
CPU.TheperiodofCLKistwicetheX1,X2inputperiod.

IO/M(Output)

IO/M indicates whether the Read/Write is to memory or l/O Tristated during Hold and Halt
modes.

SID(Input)


Serial input data line The data on this line is loaded into accumulator bit 7 whenever a RIM
instructionisexecuted.

SOD(output)

Serialoutputdataline.TheoutputSODissetorresetasspecifiedbytheSIMinstruction.

Vcc

+5voltsupply.

Vss

GroundReference.

4.Explainabouttheaddressingmodesof8085microprocessor?

Theinstructions MOVB,AorMVIA,82Haretocopydata fromasourceintoadestination.In


theseinstructionsthesourcecanbearegister,aninputport,oran8bitnumber(00HtoFFH).
Similarly, a destination can be a register or an output port. The sources and destination are
operands.Thevarious formats for specifying operands are calledtheADDRESSINGMODES. For
8085,theyare:

1.Immediateaddressing.
2.Registeraddressing.
3.Directaddressing.
4.Indirectaddressing.

Immediateaddressing

Dataispresentintheinstruction.Loadtheimmediatedatatothedestinationprovided.
Example:MVIR,data

Registeraddressing

Dataisprovidedthroughtheregisters.
Example:MOVRd,Rs

Directaddressing

Usedtoacceptdatafromoutsidedevicestostoreintheaccumulatororsendthedatastoredin
theaccumulatortotheoutsidedevice.Acceptthedatafromtheport00Handstoretheminto
theaccumulatororSendthedatafromtheaccumulatortotheport01H.
Example:IN00HorOUT01H

IndirectAddressing

This means that the Effective Address is calculated by the processor. And the contents of the
address(andtheonefollowing)isusedtoformasecondaddress.Thesecondaddressiswhere
thedataisstored.Notethatthisrequiresseveralmemoryaccesses;twoaccessestoretrievethe
16bitaddressandafurtheraccess(oraccesses)toretrievethedatawhichistobeloadedinto
theregister.

5.Explaintheinstructionsetof8085microprocessor?

Aninstructionisabinarypatterndesignedinsideamicroprocessortoperformaspecificfunction.
The entire group of instructions, called the instruction set, determines what functions the
microprocessorcanperform.Theseinstructionscanbeclassifiedintothefollowingfivefunctional
categories:datatransfer(copy)operations,arithmeticoperations,logicaloperations,branching
operations,andmachinecontroloperations.


DataTransfer(Copy)Operations

Thisgroupofinstructionscopydatafromalocationcalledasourcetoanotherlocationcalleda
destination, withoutmodifyingthecontentsofthesource.Intechnicalmanuals,thetermdata
transferisusedforthiscopyingfunction.However,thetermtransferismisleading;itcreatesthe
impressionthatthecontentsofthesourcearedestroyedwhen,infact,thecontentsareretained
withoutanymodification.

ArithmeticOperations

These instructions perform arithmetic operations such as addition, subtraction, increment, and
decrement.
AdditionAny8bitnumber,orthecontentsofaregisterorthecontentsofamemorylocation
canbeaddedtothecontentsoftheaccumulatorandthesumisstoredintheaccumulator.No
twoother8bitregisterscanbeaddeddirectly(e.g.,thecontentsofregisterBcannotbeadded
directlytothecontentsoftheregisterC).TheinstructionDADisanexception;itadds16bitdata
directlyinregisterpairs.
Subtraction Any 8bit number, or the contents of a register, or the contents of a memory
location can be subtracted from the contents of the accumulator and the results stored in the
accumulator. The subtraction is performed in 2's compliment, and the results if negative, are
expressedin2'scomplement.Notwootherregisterscanbesubtracteddirectly.
Increment/Decrement The 8bit contents of a register or a memory location can be
incrementedordecrementby1.Similarly,the16bitcontentsofaregisterpair(suchasBC)can
be incremented or decrement by 1. These increment and decrement operations differ from
addition and subtraction in an important way; i.e., they can be performed in any one of the
registersorinamemorylocation.

LogicalOperations

Theseinstructionsperformvariouslogicaloperationswiththecontentsoftheaccumulator.

AND,ORExclusiveORAny8bitnumber,orthecontentsofaregister,orofamemorylocation
can be logically ANDed, Ored, or ExclusiveORed with the contents of the accumulator. The
resultsarestoredintheaccumulator.
RotateEachbitintheaccumulatorcanbeshiftedeitherleftorrighttothenextposition.
Compare Any 8bit number, or the contents of a register, or a memory location can be
comparedforequality,greaterthan,orlessthan,withthecontentsoftheaccumulator.
ComplementThecontentsoftheaccumulatorcanbecomplemented.All0sarereplacedby1s
andall1sarereplacedby0s.

BranchingOperations

This group of instructions alters the sequence of program execution either conditionally or
unconditionally.
Jump Conditional jumps are an important aspect of the decisionmaking process in the
programming.Theseinstructionstestforacertainconditions(e.g.,ZeroorCarryflag)andalter
the program sequence when the condition is met. In addition, the instruction set includes an
instructioncalledunconditionaljump.
Call,Return,andRestartTheseinstructionschangethesequenceofaprogrameitherbycalling
asubroutineorreturningfromasubroutine.TheconditionalCallandReturninstructionsalsocan
testconditionflags.

MachineControlOperations

TheseinstructionscontrolmachinefunctionssuchasHalt,Interrupt,ordonothing.
The microprocessor operations related to data manipulation can be summarized in four
functions:
1.copyingdata
2.performingarithmeticoperations
3.performinglogicaloperations
4.testingforagivenconditionandalertingtheprogramsequence

Someimportantaspectsoftheinstructionsetarenotedbelow:


1. In data transfer, the contents of the source are not destroyed; only the contents of the
destinationarechanged.Thedatacopyinstructionsdonotaffecttheflags.
2. Arithmetic and Logical operations are performed with the contents of the accumulator, and
the results are stored in the accumulator (with some expectations). The flags are affected
accordingtotheresults.
3.Anyregisterincludingthememorycanbeusedforincrementanddecrement.
4. A program sequence can be changed either conditionally or by testing for a given data
condition.

6.Explainindetailabouttheinstructionformat?

Aninstructionisacommandtothemicroprocessortoperformagiventaskonaspecifieddata.
Eachinstructionhastwoparts:oneistasktobeperformed,calledtheoperationcode(opcode),
andthesecondisthedatatobeoperatedon,calledtheoperand.Theoperand(ordata)canbe
specified in various ways. It may include 8bit (or 16bit ) data, an internal register, a memory
location,or8bit(or16bit)address.Insomeinstructions,theoperandisimplicit.

Instructionwordsize

The8085instructionsetisclassifiedintothefollowingthreegroupsaccordingtowordsize:

1.Onewordor1byteinstructions
2.Twowordor2byteinstructions
3.Threewordor3byteinstructions

Inthe8085,"byte"and"word"aresynonymousbecauseitisan8bitmicroprocessor.However,
instructionsarecommonlyreferredtointermsofbytesratherthanwords.

OneByteInstructions

A1byteinstructionincludestheopcodeandoperandinthesamebyte.Operand(s)areinternal
registerandarecodedintotheinstruction.

Forexample:

CopythecontentsoftheaccumulatorintheregisterC.
MOVC,A

AddthecontentsofregisterBtothecontentsoftheaccumulator.
ADDB

Invert(compliment)eachbitintheaccumulator.
CMA

Theseinstructionsare1byteinstructionsperformingthreedifferenttasks.Inthefirstinstruction,
bothoperandregistersarespecified.Inthesecondinstruction,theoperandBisspecifiedandthe
accumulatorisassumed.Similarly,inthethirdinstruction,theaccumulatorisassumedtobethe
implicitoperand.Theseinstructionsarestoredin8bitbinaryformatinmemory;eachrequires
onememorylocation.

MOVrd,rs
copiescontentsofrsintord.

Example:MOVA,B

ADDr

TwoByteInstructions

Inatwobyteinstruction,thefirstbytespecifiestheoperationcodeandthesecondbytespecifies
theoperand.Sourceoperandisadatabyteimmediatelyfollowingtheopcode.Forexample:

Loadan8bitdatabyteintheaccumulator.
MVIA,Data3E

Theinstructionwouldrequiretwomemorylocationstostoreinmemory.
MVIr,data

Example:MVIA,30Hcodedas3EH30Hastwocontiguousbytes.Thisisanexampleofimmediate
addressing.
ADIdata
OUTport
whereportisan8bitdeviceaddress.Sincethebyteisnotthedatabutpointsdirectlytowhereit
islocatedthisiscalleddirectaddressing.

ThreeByteInstructions
In a threebyte instruction, the first byte specifies the opcode, and the following two bytes
specifythe16bitaddress.Notethatthesecondbyteistheloworderaddressandthethirdbyte
isthehighorderaddress.

opcode+databyte+databyte
Forexample:
JMP2085H
Thisinstructionwouldrequirethreememorylocationstostoreinmemory.
Threebyteinstructionsopcode+databyte+databyte

LXIrp,data16
rpisoneofthepairsofregistersBC,DE,HLusedas16bitregisters.Thetwodatabytesare16bit
datainLHorderofsignificance.


Example:
LXIH,0520H
LDAaddr

7.writetheassemblylanguageprogramforthefollowingoperations?

a.Toaddtwonumbers

b.Tomultiplyanumberby8

c.Tofindgreatestbetweentwonumbers

a.Toaddtwonumbers
MVID,8BH
MVIC,6FH
MOVA,C
ADDD
OUTPORT1
HLT
b.Tomultiplyanumberby8
MVIA,30H
RRC
RRC
RRC
OUTPORT1
HLT

c.Tofindgreatestbetweentwonumbers
MVIB,30H

MVIC,40H
MOVA,B
CMPC
JZEQU
JCGRT
OUTPORT1
HLT
EQU:MVIA,01H
OUTPORT1
HLT
GRT:MOVA,C
OUTPORT1
HLT

8.writeaassemblylanguageprogramforthefollowing?
1.multiplytwo8bitnumber
2.dividetwo8bitnumber
3.subtracttwo8bitnumbers
4.searchalargestnumber

Multiplicationoftwo8bitnumber

LDA4200H

MOVB,A

LDA4501H

MVID,00H

MOVE,B

LXIH,0000H

LOOPDADD

DCRA

JNZLOOP

SHLD4202H

HLT

Divisionoftwo8bitnumber

LDA4200H

MOVB,A

LDA4501H

MVIC,00H

AGAINCMPB

JCLOOP

SUBB

INRC

JMPAGAIN

LOOPSTA4202H

MOVA,C

STA4203H

HLT

Addtwo8bitnumbers

LXIH,2000H

MOVA,M

INXH

ADDM

INXH

MOVM,A

HLT

Searchingalargestnumber

LXIH,4200H

MOVB,M

INXH

LOOP2MOVA,M
LOOP3DCRB

JZLOOP1

INXH

CMPM

JCLOOP2

JMPLOOP3

LOOP1STA4500H

HLT

UNIT2
8086 SOFTWARE ASPECTS

UNIT2
1.Explainthearchitectureof8086microprocessor.

Execution Unit (E
EU) : Executtion unit recceives program instructiion codes an
nd data from
m
the BIU
U, executes th
hem and stores
the resuults in the geeneral registeers. It can alsso store the data
d in a meemory locatioon or send
them too an I/O deviice by passin
ng the data bback to the BIU.
B
This uniit, EU, has no
n
connecttion with thee system Busses. It receivves and outpuuts all its datta through BIU.
B
ALU (A
Arithmetic and Logic Unit) : Thhe EU unit contains a ccircuit boardd called thee
Arithmeetic and Log
gic Unit. Th
he ALU cann perform arrithmetic, suuch as, +,-,
,/ and logicc
such as OR, AND, NOT operattions.

Registers : A register is like a memory location where the exception is that these are
denoted by name rather than numbers. It has 4 data registers, AX, BX, CX, DX and 2
pointer registers SP, BP and 2 index registers SI, DI and 1 temporary register and 1 status
register FLAGS . AX, BX, CX and DX registers has 2 8-bit registers to access the high
and low byte data registers. The high byte of AX is called AH and the low byte is AL.
Similarly, the high and low bytes of BX, CX, DX are BH and BL, CH and Cl, DH and DL
respectively. All the data, pointer, index and status registers are of 16 bits. Else these, the
temporary register holds the operands for the ALU and the individual bits of the FLAGS
register reflect the result of a computation.
Bus Interface Unit : As the EU has no connection with the system Busses, this job is
done by BIU. BIU and EU are connected with an internal bus. BIU connects EU with the
memory or I/O circuits. It is responsible for transmitting data, addresses and control signal
on the busses.
Registers : BIU has 4 segment busses, CS, DS, SS, ES. These all 4 segment registers
holds the addresses of instructions and data in memory. These values are used by the
processor to access memory locations. It also contain 1 pointer register IP. IP contains the
address of the next instruction to executed by the EU.

Instruction Queue : BIU also contain an instruction queue. When the EU executes
instructions, the BIU gets up to 6 bytes of the next instruction and stores them in the
instruction queue and this process is called instruction prefetch. This is a process to speed
up the processor. Also when the EU needs to be connected with memory or peripherals,
BIU suspends instruction prefetch and performs the needed operations
General Registers : All general registers of the 8086 microprocessor can be used for
arithmetic and logic operations. The general registers are:
AX (Accumulator): This is accumulator register. It gets used in arithmetic, logic and
data

transfer

instructions.

In

manipulation

and

division

, one of the numbers involved must be in AX or AL.


BX (Base Register): This is base register. BX register is an address register. It usually
contain a data pointer used for based, based indexed or register indirect addressing.

CX (Count register): This is Count register. This serves as a loop counter. Program loop
constructions are facilitated by it. Count register can also be used as a counter in string
manipulation and shift/rotate instruction.
DX (Data Register): This is data register. Data register can be used as a port number in
I/O operations. It is also used in multiplication and division.
SP (Stack Pointer): This is stack pointer register pointing to program stack. It is used in
conjunction with SS for accessing the stack segment.
BP (Base Pointer): This is base pointer register pointing to data in stack segment. Unlike
SP, we can use BP to access data in the other segments.
SI (Source Index): This is source index register which is used to point to memory
locations in the data segment addressed by DS. By incrementing the contents of SI one can
easily access consecutive memory locations.
DI (Destination Index): This is destination index register performs the same function as
SI. There is a class of instructions called string operations, that use DI to access the
memory locations addressed by ES.

Segment Register:
CS (Code Segment) : Code segment (CS) is a 16-bit register containing address of 64
KB segment with processor instructions. The processor uses CS segment for all accesses
to instructions referenced by instruction pointer (IP) register. CS register cannot be
changed

directly.The

CS

register

is automatically updated during far jump, far call and far return instructions.
Stack segment (SS) is a 16-bit register containing address of 64KB segment with
program stack. By default, the processor assumes that all data referenced by the stack
pointer (SP) and base pointer (BP) registers is located in the stack segment. SS register can
be changed directly using POP instruction.

Data segment (DS) is a 16-bit register containing address of 64KB segment with program
data. By default, the processor assumes that all data referenced by general registers (AX,
BX, CX, DX) and index register (SI, DI) is located in the data segment. DS register can be
changed directly using POP and LDS instructions.
Extra segment (ES) is a 16-bit register containing address of 64KB segment, usually with
program data. By default, the processor assumes that the DI register references the ES
segment in string manipulation instructions. ES register can be changed directly using
POP and LES instructions.
2.Explain about the signals of 8085.

The Microprocessor 8086 is a 16-bit CPU available in different clock rates and packaged
in a 40 pin CERDIP or plastic package.

The 8086 operates in single processor or multiprocessor configuration to achieve high


performance. The pins serve a particular function in minimum mode (single processor
mode ) and other function in maximum mode configuration (multiprocessor mode ).

The 8086 signals can be categorised in three groups.

The first are the signal having common functions in minimum as well as maximum mode.

The second are the signals which have special functions for minimum mode

The third are the signals having special functions for maximum mode.

The following signal descriptions are common for both modes.

AD15-AD0 : These are the time multiplexed memory I/O address and data lines.

Address remains on the lines during T1 state, while the data is available on the data bus
during T2, T3, Tw and T4. These lines are active high and float to a tristate during
interrupt acknowledge and local bus hold acknowledge cycles.

A19/S6,A18/S5,A17/S4,A16/S3 : These are the time multiplexed address and status lines.

During T1 these are the most significant address lines for memory operations.

During I/O operations, these lines are low.

During memory or I/O operations, status information is available on those lines for
T2,T3,Tw and T4.

The status of the interrupt enable flag bit is updated at the beginning of each clock cycle.

The S4 and S3 combinely indicate which segment register is presently being used for
memory accesses as in below fig.

These lines float to tri-state off during the local bus hold acknowledge. The status line S6
is always low.

The address bit are separated from the status bit using latches controlled by the ALE
signal.

S4

S3

Indication

Alternate Data

Stack

Code or None

Data

Whole word

Upper byte from or to even address

Lower byte from or to even address

BHE/S7 : The bus high enable is used to indicate the transfer of data over the higher order
( D15-D8 ) data bus as shown in table. It goes low for the data transfer over D15-D8 and is

used to derive chip selects of odd address memory bank or peripherals. BHE is low during
T1 for read, write and interrupt acknowledge cycles, whenever a byte is to be transferred
on higher byte of data bus. The status information is available during T2, T3 and T4. The
signal is active low and tristated during hold. It is low during T1 for the first pulse of the
interrupt acknowledge cycle.

RD Read : This signal on low indicates the peripheral that the processor is performing
memory or I/O read operation. RD is active low and shows the state for T2, T3, Tw of any
read cycle. The signal remains tristated during the hold acknowledge.

READY : This is the acknowledgement from the slow device or memory that they have
completed the data transfer. The signal made available by the devices is synchronized by
the 8284A clock generator to provide ready input to the 8086. the signal is active high.

INTR-Interrupt Request : This is a triggered input. This is sampled during the last clock
cycles of each instruction to determine the availability of the request. If any interrupt
request is pending, the processor enters the interrupt acknowledge cycle. This can be
internally masked by resulting the interrupt enable flag. This signal is active high and
internally synchronized.

TEST : This input is examined by a WAIT instruction. If the TEST pin goes low,
execution will continue, else the processor remains in an idle state. The input is
synchronized internally during each clock cycle on leading edge of clock.

CLK- Clock Input : The clock input provides the basic timing for processor operation
and bus control activity. Its an asymmetric square wave with 33% duty cycle.
3.Explain about the interrupts of 8086.
INTERRUPTS
There are two main types of interrupt in the 8086 microprocessor, internal and external
hardware interrupts. Hardware interrupts occur when a peripheral device asserts an
interrupt input pin of the microprocessor. Whereas internal interrupts are initiated by the
state of the CPU (e.g. divide by zero error) or by an instruction.

Provided the interrupt is permitted, it will be acknowledged by the processor at the end of
the current memory cycle. The processor then services the interrupt by branching to a
special service routine written to handle that particular interrupt. Upon servicing the
device, the processor is then instructed to continue with what is was doing previously by
use of the "return from interrupt" instruction.
The status of the programme being executed must first be saved. The processors registers
will be saved on the stack, or, at very least, the programme counter will be saved.
Preserving those registers which are not saved will be the responsibility of the interrupt
service routine. Once the programme counter has been saved, the processor will branch to
the address of the service routine.
Edge or Level sensitive Interrupts
Edge level interrupts are recognised on the falling or rising edge of the input signal. They
are generally used for high priority interrupts and are latched internally inside the
processor. If this latching was not done, the processor could easily miss the falling edge
(due to its short duration) and thus not respond to the interrupt request.
Level sensitive interrupts overcome the problem of latching, in that the requesting device
holds the interrupt line at a specified logic state (normally logic zero) till the processor
acknowledges the interrupt. This type of interrupt can be shared by other devices in a
wired 'OR' configuration, which is commonly used to support daisy chaining and other
techniques.
Maskable Interrupts
The processor can inhibit certain types of interrupts by use of a special interrupt mask bit.
This mask bit is part of the flags/condition code register, or a special interrupt register. In
the 8086 microprocessor if this bit is clear, and an interrupt request occurs on the Interrupt
Request input, it is ignored.
Non-Maskable Interrupts
There are some interrupts which cannot be masked out or ignored by the processor. These
are associated with high priority tasks which cannot be ignored (like memory parity or bus

faults). In general, most processors support the Non-Maskable Interrupt (NMI). This
interrupt has absolute priority, and when it occurs, the processor will finish the current
memory cycle, then branch to a special routine written to handle the interrupt request.
Advantages of Interrupts
Interrupts are used to ensure adequate service response times by the processing.
Sometimes, with software polling routines, service times by the processor cannot be
guaranteed, and data may be lost. The use of interrupts guarantees that the processor will
service the request within a specified time period, reducing the likelihood of lost data.
Interrupt Latency
The time interval from when the interrupt is first asserted to the time the CPU recognises
it. This will depend much upon whether interrupts are disabled, prioritized and what the
processor is currently executing. At times, a processor might ignore requests whilst
executing some indivisible instruction stream (read-write-modify cycle). The figure that
matters most is the longest possible interrupt latency time.
Interrupt Response Time
The time interval between the CPU recognising the interrupt to the time when the first
instruction of the interrupt service routine is executed. This is determined by the processor
architecture and clock speed.
The Operation of an Interrupt sequence on the 8086 Microprocessor:
1. External interface sends an interrupt signal, to the Interrupt Request (INTR) pin, or an
internal interrupt occurs.
2. The CPU finishes the present instruction (for a hardware interrupt) and sends Interrupt
Acknowledge (INTA) to hardware interface.
3. The interrupt type N is sent to the Central Processor Unit (CPU) via the Data bus from
the hardware interface.
4. The contents of the flag registers are pushed onto the stack.

5. Both the interrupt (IF) and (TF) flags are cleared. This disables the INTR pin and the
trap or single-step feature.
6. The contents of the code segment register (CS) are pushed onto the Stack.
7. The contents of the instruction pointer (IP) are pushed onto the Stack.
8. The interrupt vector contents are fetched, from (4 x N) and then placed into the IP and
from (4 x N +2) into the CS so that the next instruction executes at the interrupt service
procedure addressed by the interrupt vector.
9. While returning from the interrupt-service routine by the Interrupt Return (IRET)
instruction, the IP, CS and Flag registers are popped from the Stack and return to their
state prior to the interrupt.
Multiple Interrupts
If more than one device is connected to the interrupt line, the processor needs to know to
which device service routine it should branch to. The identification of the device
requesting service can be done in either hardware or software, or a combination of both.
The three main methods are:
1. Software Polling,
2. Hardware Polling, (Daisy Chain),
3. Hardware Identification (Vectored Interrupts).
Software Polling Determination of the Requesting Device
A software routine is used to identify the device requesting service. A simple polling
technique is used, each device is checked to see if it was the one needing service.

Having identified the device, the processor then branches to the appropriate interrupthandling-routine address for the given device. The order in which the devices appear in the
polling sequence determines their priority.

4.Explain about the assembler directives of 8086.

ASSUME
This directive tells the assembler the name of the logical segment it should use for a
specified segment. For example ASSUME CS:CODE, tells the assembler that the
instructions for a program are in a logical segment named CODE. The 8086 works
directly with only 4 physical segments: a Code segment, a data segment, a stack segment,
and an extra segment.
DB Define Byte
This directive is used to declare a byte type variable or to store a byte in memory location.
For example
NAME DB PROCESSOR;

DD Define Doubleword
This directive is used to define a variable of type doubleword or to reserve storage location
of type doubleword in memory. For example
POINTER DD 123H
DQ Define Quadword
This directive is used to define a variable of type quadword or to reserve storage location
of type quadword in memory.

DT Define Ten Bytes


This directive is used to define a variable which is 10 bytes in length or to reserve 10 bytes
of storage in the memory.

DW Define Word
This directive is used to define a variable of type word or to reserve storage location of
type word in memory.
ARRAY DW 100DUP(0) ; defines an array of size 100 all initialized to 0.
MULTIPLIER DW 1234h; defines a variable multiplier of value 1234h

ENDS

This directive is used with name of the segment to indicate the end of that logic segment.
For example
CODE SEGMENT ; this statement starts the segment
CODE ENDS ; this statement ends the segment
EQU
This directive is used to give a name to some value or to a symbol. Each time the
assembler finds the name in the program, it will replace the name with the value or symbol
you given to that name. for example
FACTOR EQU 03H ; this equates factor to 03h can be used as
ADD AL, FACTOR ; When it codes this instruction the assembler will code it as
ADDAL, 03H The advantage of using EQU in this manner is, if FACTOR is used many
no of times in a program and you want to change the value, all you had to do is change the
EQU statement at beginning, it will changes the rest of all
EVEN
This directive instructs the assembler to increment the location of the counter to the next
even address if it is not already in the even address. If the word is at even address 8086
can read a memory in 1 bus cycle.
If the word starts at an odd address, the 8086 will take 2 bus cycles to get the data. A
series of words can be read much more quickly if they are at even address. When EVEN is
used the location counter will simply incremented to next address and NOP instruction is
inserted in that incremented location. For example

DATA SEGMENT
Location counter will point to 0009 after assembler reads next statement
SALES DB 9 DUP(?) ;declare an array of 9 bytes
EVEN ; increment location counter to 000AH
RECORD DW 100 DUP(0) ;Array of 100 words will start from an even address for
quicker read
GROUP

This directive is used to group the logical segments named after the directive into one
logical group segment
INCLUDE
This directive is used to insert a block of source code from the named file into the current
source module.
5.Explain about the addressing modes of 8086.
There are seven types of addressing modes
1)

Register Addressing mode

2)

Immediate Addressing mode

3)

Register Indirect Addressing mode

4)

Direct Addressing mode

5)

Indexed Addressing mode

6)

Base Relative Addressing mode

7)

Base Indexed Addressing mode

Register Addressing Mode


Data transfer using registers is called register addressing mode. Here operand value is
present in register. For example
MOV AL,BL;
MOV AX,BX;
Immediate Addressing mode
When data is stored in code segment instead of data segment immediate addressing mode
is used. Here operand value is present in the instruction. For example
MOV AX, 12345;
Direct Addressing mode
When direct memory address is supplied as part of the instruction is called direct
addressing mode. Operand offset value with respect to data segment is given in
instruction. For example

MOV AX, [1234];


ADD AX, [1234];
Register Indirect Addressing mode
Here operand offset is given in a cpu register. Register used are BX, SI(source index),
DI(destination index), or BP(base pointer). BP holds offset w.r.t Stack segment, but SI,DI
and BX refer to data segment. For example
MOV [BX],AX;
ADD AX, [SI];
Indexed Addressing mode
Here operand offset is given by a sum of a value held in either SI, or DI register and a
constant displacement specified as an operand. For example
Lets take arrays as an example. This is very efficient way of accessing arrays.
My_array DB 1, 2, 3,4,5;
MOV SI, 3;
MOV AL, My_array[3];
So AL holds value 4.
Base Relative Addressing mode
Operand offset given by a sum of a value held either in BP, or BX and a constant offset
sepecified as an operand. For example
MOV AX,[BP+1];
JMP [BX+1];
Base Indexed
Here operand offset is given by sum of either BX or BP with either SI or DI. For example
MOV AX, [BX+SI]
JMP [BP+DI
6.Explain the data transfer group instruction of 8086.

These instructions are used to transfer data from source to destination.The operand
can be a constant, memory location, register or I/O port address.
MOV Des, Src:
Src operand can be register, memory location or immediate operand.
Des can be register or memory operand. Both Src and Des cannot be memory location at
the same time.
E.g.:
MOV CX, 037A H
MOV AL, BL
MOV BX, [0301 H]
PUSH Operand:
It pushes the operand into top of stack.
E.g.: PUSH BX
POP Des:
It pops the operand from top of stack to Des. Des can be a general purpose register,
segment register (except CS) or memory location.
E.g.: POP AX
XCHG Des, Src:
This instruction exchanges Src with Des. It cannot exchange two memory locations
directly.
E.g.: XCHG DX, AX
IN Accumulator, Port Address:
It transfers the operand from specified port to accumulator register.
E.g.: IN AX, 0028 H
OUT Port Address, Accumulator:
It transfers the operand from accumulator to specified port.
E.g.: OUT 0028 H, AX
LEA Register, Src:
It loads a 16-bit register with the offset address of the data specified by the Src.
E.g.: LEA BX, [DI]
This instruction loads the contents of DI (offset) into the BX register

LDS Des, Src:


It loads 32-bit pointer from memory source to destination register and DS.
The offset is placed in the destination register and the segment is placed in DS.
To use this instruction the word at the lower memory address must contain the offset and
the word at the higher address must contain the segment.
E.g.: LDS BX, [0301 H]
LES Des, Src:
It loads 32-bit pointer from memory source to destination register and ES. The offset is
placed in the destination register and the segment is placed in ES. This instruction is very
similar to LDS except that it initializes ES instead of DS.
E.g.: LES BX, [0301 H]
LAHF:
It copies the lower byte of flag register to AH.
SAHF:
It copies the contents of AH to lower byte of flag register.
PUSHF:
Pushes flag register to top of stack.
POPF:
Pops the stack top to flag register.

7.Explain the arithmetic group instruction of 8086.


ADC Des, Src:
It adds the two operands with CF.It effects AF, CF, OF, PF, SF, ZF flags.
E.g.:
ADC AL, 74H
ADC DX, AXADC AX, [BX]

ADD Des, Src:


It adds a byte to byte or a word to word. It effects AF, CF, OF, PF, SF, ZF flags.
E.g.:
ADD AL, 74H

ADD DX, AXADD AX, [BX]

SUB Des, Src:


It subtracts a byte from byte or a word from word. It effects AF, CF, OF, PF, SF, ZF flags.
For subtraction, CF acts as borrow flag.
E.g.:
SUB AL, 74H
SUB DX, AXSUB AX, [BX]

SBB Des, Src:


It subtracts the two operands and also the borrow from the result.It effects AF, CF, OF,
PF, SF, ZF flags.
E.g.:
SBB AL, 74H
SBB DX, AX
SBB AX, [BX]

INC Src:
It increments the byte or word by one. The operand can be a register or memory
location. It effects AF, OF, PF, SF, ZF flags. CF is not effected.
E.g.: INC AX
DEC Src:
It decrements the byte or word by one. The operand can be a register or memory
location. It effects AF, OF, PF, SF, ZF flags. CF is not effected.
E.g.: DEC AX
AAA (ASCII Adjust after Addition):
The data entered from the terminal is in ASCII format. In ASCII, 0 9 are represented by
30H 39H. This instruction allows us to add the ASCII codes. This instruction does not
have any operand. Other ASCII Instructions:
AAS (ASCII Adjust after Subtraction)
AAM (ASCII Adjust after Multiplication)

AAD (ASCII Adjust Before Division)


DAA (Decimal Adjust after Addition)
It is used to make sure that the result of adding two BCD numbers is adjusted to be a
correct BCD number. It only works on AL register.

DAS (Decimal Adjust after Subtraction)


It is used to make sure that the result of subtracting two BCD numbers is adjusted to be a
correct BCD number. It only works on AL register

NEG Src:
It creates 2s complement of a given number. That means, it changes the sign of a
Number
CMP Des, Src:
It compares two specified bytes or words. The Src and Des can be a constant, register or
memory location. Both operands cannot be a memory location at the same time. The
comparison is done simply by internally subtracting the source from destination. The value
of source and destination does not change, but the flags are modified to indicate the result.

MUL Src:
It is an unsigned multiplication instruction. It multiplies two bytes to produce a word or
two words to produce a double word.
AX = AL * Src
DX : AX = AX * Src
This instruction assumes one of the operand in AL or AX. Src can be a register or memory
location.

IMUL Src:
It is a signed multiplication instruction.
DIV Src:
It is an unsigned division instruction. It divides word by byte or double word by word.
The operand is stored in AX, divisor is Src and the result is stored as:AH = remainder AL
= quotient

IDIV Src:
It is a signed division instruction
CBW (Convert Byte to Word):
This instruction converts byte in AL to word in AX. The conversion is done by extending
the sign bit of AL throughout AH.

CWD (Convert Word to Double Word):


This instruction converts word in AX to double word in DX : AX. The conversion is
done by extending the sign bit of AX throughout DX.
8.Write an ALP to add two packed BCD numbers.

Mov dx, buffer address


Mov ah,0a
Mov si,dx
Mov byte ptr [si], 8
Int 21
Mov ah,0eh
Mov al,0ah
Int 10 ;
sub byte ptr[si+2], 30h
sub byte ptr[si+3], 30h

sub byte ptr[si+5], 30h


sub byte ptr[si+6], 30h
Mov cl,4
Rol byte ptr [si+3],cl
Rol byte ptr [si+6],cl
Ror word ptr [si+2], cl
Ror word ptr [si+2], cl
Mov al, [si+3]
Add al, [si+6]
Daa
Mov bh,al
Mov al,1
Call display
Mov al,bh
Call display
Int 20
Display Subroutine:
mov bl,al ;
mov cl,4 ;

ror al,cl ;
add al,30 ;
mov ah,0e ;
int 10 ;
mov al,bl ;
and al,0f ;
add al,30 ;
int 10 ;
ret ;

UNIT 3
MULTIPROCESSOR CONFIGURATIONS

1.Write short notes on coprocessor configuration?

Coprocessor Systems refer to the use of multiple processors that execute


instructions simultaneously and communicate using mailboxes and semaphores.A
coprocessor may not be a general-purpose processor in its own right. Some coprocessors
cannot fetch instructions from memory, execute program flow control instructions, do
input/output operations, manage memory, and so on. These processors require the host
main processor to fetch the coprocessor instructions and handle all other operations aside
from the coprocessor functions. In some architectures the coprocessor is a more generalpurpose computer, but carries out only a limited range of functions under the close control
of a supervisory processor.
The coprocessor sped up floating-point arithmetic on the order of fiftyfold. Users that only
used the PC for word processing, for example, saved the high cost of the coprocessor,
which would not have accelerated performance of text manipulation operations.

The 8087 was tightly integrated with the 8086/8088 and responded to floatingpoint machine code operation codes inserted in the 8088 instruction stream. An 8088
processor without an 8087 could not interpret these instructions, requiring separate
versions of programs for FPU and non-FPU systems, or at least a test at run time to detect
the FPU and select appropriate mathematical library functions.
Another coprocessor for the 8086/8088 central processor was the 8089
input/output coprocessor. It used the same programming technique as 8087 for
input/output operations, such as transfer of data from memory to a peripheral device, and
so reducing the load on the CPU. But IBM didn't use it in IBM PC design and Intel
stopped development of this type of coprocessor
Maximum mode of 8086 is designed to implement 3 basic multiprocessor configurations:
1. coprocessor (8087)
2. closely coupled (8089)
3. loosely coupled (Multibus)
Coprocessors and closely coupled configurations are similar in that both the CPU and the
external
processor share:
- Memory
- I/O system
- Bus & bus control logic
- Clock generator

2.Explain Closely coupled configuration

When developing an application that requires multiple processors, the symmetric


multiprocessor (SMP) architecture is the easiest to use. This architecture allows the
programmer to ignore most issues relating to the location of execution of his application's
tasks. Debugging tools on an SMP system provide a single system view of all tasks,
regardless of the processor where the task is executing. These tools also allow easy
monitoring of interactions between tasks running on separate processors. The convenience
of the SMP programming environment is in stark contrast to the environment that is
generally available when programming for multiple single board computers. Most
operating systems today support only TCP/IP style of networked communication between
tasks on separate SBCs. This type of communication is very inefficient compared to interprocess communication within an SMP. The tools for debugging applications on multiSBC configurations generally require a separate invocation of a tool for each SBC being
debugged - allowing no possibility for synchronized access to the task on separate SBCs.
The support for closely-coupled systems is a layer of software and hardware
support that mimics the environment of an SMP system. It provides a range of
communication facilities for communicating between tasks that are executing on separate
SBCs. These communication facilities offer a range of application convenience and
efficiency.
The architecture required for closely-coupled support is a system composed of
multiple single board computers, which share the same VME rack. The set of SBCs within
a single rack is known as a cluster. Each of the SBCs runs a unique copy of the
PowerMAX OS operating system. While there are many possible ways of connecting

3.Explain Loosely Coupled Configuration:


multiple SBCs, the most common configuration is to have a disk attached to just one of the
SBCs, which is
- has shared system bus, system memory, and system I/O
then known as the
file server for the - each processor has its own clock as well as its own memory (in addition to access to
cluster. The file
environment for
controlling the

the system resources, such as the system clock) server provides an


- clocks are of similar frequency, but asynchro-nous towards each other

cluster and can provide disk


- Used for medium to large multiprocessor systems storage space for the SBCs
- Each module is capable of being the bus master without attached disks. The file
- Any module could be a processor capable of being a bus master, a coprocessor configuration or a
closely coupled configuration. server also acts as the boot server, booting the
other SBCs by directly mapping their control
registers via the VME bus. It is also possible to support a completely diskless
configuration of SBCs.
Closely-coupled support consists of the following capabilities:

configuration tools that allow the system administrator to specify the relationships
between SBCs and how they will be booted
inter-task communication facilities that allow communication between tasks that are
executing on separate SBCs
the ability to have shared memory between tasks executing on separate SBCs
access to DMA capabilities to allow very efficient transfer of large amounts of data
between the memory of separate SBCs
support within application development tools for viewing multiple SBCs as a single
system
optional hardware support for tighter coupling of SBCs
4.Write short notes on BUS Arbitration Technique

- Can use priority resolution here:


- Need a bus controller to monitor bus busy and bus request signals
- Highest priority is granted first, if it does not respond, then a lower priority is granted, and so on
- Sends a bus grant to a Master >> each Master either keeps the service or passes it on
(ie: one request line, 3-bit grant line)

- Controller synchronizes the clocks


- No direct connections between the modules. Each share the system bus and communicate through
shared resources.
- Processor in their saeparate modules can simulateneously access their private subsystems through
their local busses, and perorm their local data references and instruction fetches independandtly.
This results in improved degree of concurrent processing.
...
- Ecellent for real time applications, as separate modules can be assigned specialized tasks.
ADVANTAGES:
- high system throughput can be achieved by having more than one CPU.
- The system can be expanded in modular form. Each bus master module is an independant unit and
normally resides on a separate PC board. One can be added or removed without affecting the
others in the system.
- A failure in one module normally does not affect the breakdown of the entire system and the faulty
module can be easily detected and replaced
- each bus master has its own local bus to access dedicated memory or IO devices so a greater de- gre
processing can be achieved.
PROBLEMS:
- Bus Arbitration (contention): Make sure that only 1 processor can access the bus at any given time
- must synchronize local and system clocks for synchronous transfer
- requires control chips to tie into the system bus
Processor Bus Access:
- Needs some kind of priority allocation
- Output a Bus Request >BRQ= to request the bus >> BRQ line goes to some controller
- Input a Bus Grant >BGR= to gain access to bus >> BGR line from some controller
- Output a Bus Busy >BBSY= signal to hold the bus

Clocking:
- take both clocks and derive a common clock (ie: local clock & system clock)
or
- take leading edge of one of the clocks >> can alternate or change for each individual
operation (clock will jitter)
- Could have fixed priority, rotating priority, etc.
usually fixed because memory is desired to be the highest priority
- Synchronization of the clocks must be performed once a Master is recognized
- Master will receive a common clock from one side and pass it to the controller which will
derive a
.- Can accurately predict calculations (since memory is always the highest priority)

5.Explainthearchitectureof8087?

It is a processor which works in parallel with the main processor.It has its own set of
specialized instructions.The number crunching part of the program is executed by 8087.
Instruction for 8087 are written in the main program interspersed with the 8086 instructions
.All the 8087 instruction codes have 11011 as the most significant bits of their first code byte.
The 80x87 family of math coprocessors (also known as MCPs [MathCoProcessors],
NDPs [Numerical Data Processors], NPXs [Numerical ProcessoreXtensions], or FPUs
[Floating-Point Units], or simply "math chips") are typical examples of such coprocessors.
The 80x86 CPUs, with the exception of the 80486 (which has a built-in FPU) can only handle
8, 16, or 32 bit integers as their basic data types. However, many PC-based applications
require the use of not only integers, but floating-point numbers. Simply put, the use of
floating-point numbers enables a binary representation of not only integers, but also
fractional values over a wide range. A common application of floating-point numbers is in
scientific applications, where very small
(e.g., Planck's constant) and very large numbers (e.g., speed of light) must be accurately
expressed. But floating-point numbers are also useful for business applications such as
computing interest, and in the geometric calculations inherent in CAD/CAM processing.
Because the instruction sets of all 80x86 CPUs directly support only integers and
calculations upon integers, floating-point numbers and operations on them must be
programmed indirectly by using series of CPU integer instructions. This means that
computations when floating-point numbers are used are far slower than normal, integer
calculations. And this is where the 80x87 coprocessors come in: adding an 80x87 to an
80x86-based system augments the
CPU architecture with eight floating-point registers, five additional data types and over 70
additional instructions, all designed to deal directly with floating-point numbers as a basic
data type. This removes the 'penalty' for floating-point computations, and greatly increases
overall system performance for applications which depend heavily on these calculations. In
addition to being able to quickly execute load/store operations on floating-point numbers, the
80x87 coprocessors can directly perform all the basic arithmetic operation on them. Besides
"knowing" how to add, subtract, multiply and divide floating-point numbers, they can also

operate on them to perform comparisons, square roots, transcendental functions (such as


logarithms and sine/cosine/tangent), and compute their absolute value and remainder. Like
most things in life, floating-point arithmetic has been standardized.

THE 8087 INTERNAL ARCHITECTURE

The internal structure of 8087 coprocessor is


divided into two major sections:
1. Control Unit (CU)
2.Numerical Execution Unit (NEU)
CONTROL UNIT (CU)

It interfaces coprocessor to the microprocessor system bus.

It also synchronize the operation of the coprocessor and the microprocessor.

This unit has a Control Word, Status Word and Data Buffer.

If an instruction is ESC instruction, then coprocessor executes it.

If not, then microprocessor executes.

NUMERIC EXECUTION UNIT (NEU)

This unit is responsible for executing all coprocessor instructions.

It has an 8 register stack that holds the operands for instructions and result of
instructions.

The stack contains 8 registers that are 80-bits wide.

Numeric data is transferred inside the coprocessor in two parts:


64-bit mantissa bus
16-bit exponent bus

8087 Stack Operations

8087atus Word Formats

Status Register tells the overall status of 8087 coprocessor.

It is a 16-bit register.

It is accessed by executing the FSTSW instruction. This instruction stores the


contents of status register into memory.

Once the status is stored in memory, the bit positions of the status register can be
examined.

Busy: It indicates that the coprocessor is busy executing the task.


Condition Codes (C0-C3): They indicate various conditions about the coprocessor.
Top of Stack: It indicates a register as top of stack register, out of the eight stack registers.
Exception Flag: It is set if any of the exception flag bits (SF, PR, UF, OF, ZD, DN, IO) are
set.
Stack Fault: It is not available in 8087. It is active only in 80387 and above.
Precision: It indicates that the result has exceeded the selected precision.

Underflow: It tells if the result is too small to fit in a register.


Overflow: It tells if the result is too large to fit in a register.
Zero Divide: It indicates that you try to divide a non-zero value by zero.
Demoralized: It indicates that at least one of the operand is de-normalized.
Invalid Operation: It indicates an invalid operation.
For e.g.: pushing more than eight items onto the stack, attempting to pop an item off an
empty stack or taking the square root of a negative number.

8087 Control Word Formats


Control Register controls the operating modes of 8087.

It is also a 16-bit register.

It performs rounding control and precision control.

It is also used to do masking and unmasking of the exception bits that correspond to
the rightmost six bits of the status register.

FLDCW instruction is used to load the value into control register.

Rounding Control: It determines the type of rounding or truncating to be done.


Precision Control: It sets the precision of the result.
Exception Masks: It determines that whether an error effects the exception bits in the status
register. If it is one, then the corresponding error is ignored. If it is zero and the
corresponding error occurs, then it generates an interrupt, and the corresponding bit in status
register is set.

6.Explain 8089 I/O Processor

7. ExplainCommunication between CPU and IOP

Peripheral Devices:

The input-output subsystem of a computer provides an efficient mode of communication


between the central system and the outside environment.

Programs and data must be entered into computer memory for processing and results
obtained from computations must be recorded or displayed for the user.

The common input devices are keyboard, mouse and joystick.

To use a computer efficiently, a large amount of programs and data must be prepared in
advance and transmitted into a storage medium such as magnetic tapes or disks.

The information in the disk is then transferred into computer memory at a rapid rate.

Devices that are under the direct control of the computer are said to be connected on-line.

Input or output devices attached to the computer are also called peripherals.

Among the most common peripherals are keyboards, display units, and printers.

Peripherals that provide auxiliary storage for the system are magnetic disks and tapes.
Input Output Interface:

Input - output interface provides a method for transferring information between internal
storage and external I/O devices.

Peripherals connected to a computer need special communication links for interfacing


them with the central processing unit.

The purpose of the communication link is to resolve the differences that exist between the
central computer and each peripheral. The major differences are:
1.
Peripherals manner of operation is different from
CPU and memory,

the

2.
The data transfer rate of peripherals is usually
rate of the CPU,

slower than the transfer

3.
Data codes and formats in peripherals differ from
CPU and memory.

the word format in the

4.The operating modes of peripherals are different from each other.

operation of the

To resolve these differences, computer systems include special hardware components


between the CPU and peripherals to supervise and synchronize all input and output
transfers. These components are called interface units.

Because they interface between the processor bus and the peripheral device.
In addition, each device may have its own controller that supervises the operations of the
particular mechanism in the peripheral.
I/O Bus and Interface modules:
A typical communication link between the processor and several peripherals as shown in
below figure.

The I/O bus consists of data lines, address lines, and control lines.

The magnetic disk, printer, and terminal are employed in practically any general-purpose
computer.

Each peripheral device has associated with it an interface unit.

Each interface decodes the address and control received from the I/O bus interprets them
for the peripheral and provides signals for the peripheral controller.

It also synchronizes the data flow and supervises the transfer between peripheral and
processor.

Each peripheral has its own controller that operates the particular electromechanical
device.

To communicate with a particular device, the processor places a device address on the
address lines.

When the interface detects its own address, it activates the path between the bus lines and
the device that it controls.

All peripherals whose address does not correspond to the address in the bus are disabled
by their interface.

At the same time that the address is made available in the address lines, the processor
provides a function code in the control lines.

The interface selected responds to the function code and proceeds to execute it. The
function code is referred to as an I/O command.

There are four types of commands that an interface may receive. They are classified as
control, status, data output, and data input.

A control command is issued to activate the peripheral and to inform it what to do.

A status command is used to test various status conditions in the interface and the
peripheral.

A data output command causes the interface to respond by transferring data from the bus
into one of its registers.

The data input command is the case interface receives an item of data from the peripheral
and places it in its buffer registers.

I/O versus Memory Bus:

There are four types of commands that an interface may receive. They are classified as
control, status, data output, and data input.

A control command is issued to activate the peripheral and to inform it what to do.

A status command is used to test various status conditions in the interface and the
peripheral.

A data output command causes the interface to respond by transferring data from the bus
into one of its registers.

The data input command is the case interface receives an item of data from the peripheral
and places it in its buffer registers.

I/O versus Memory Bus:

In addition to communicating with I/O, the processor must communicate with the memory
unit.

Like the I/O bus, the memory bus contains data, address, and read/write control lines.

There are three ways that computer buses can be used to communicate with memory and
I/O:
1.

Use two separate buses, one for memory and

2.
Use one common bus for both memory and I/O
control lines for each.
3.

Use one common bus for memory and I/O with

the other for I/O.


but have separate
common control lines.

Isolated versus Memory-mapped I/O:

Many computers use one common bus to transfer information between memory or I/O and
the CPU.

The distinction between a memory transfer and I/O transfer is made through separate read
and write lines.

The CPU specifies whether the address on the address lines is for a memory word or for an
interface register by enabling one of two possible read or write lines.

The I/O read and I/O write control lines are enabled during an I/O transfer.

The memory read and memory write control lines are enabled during a memory transfer.

This configuration isolates all I/O interface addresses from the addresses assign to
memory and is referred to as the isolated I/O method for assigning addresses in a common
bus.

In the isolated I/O configuration, the CPU has distinct input and output instructions, and
each of these instructions is associated with the address of an interface register.

When the CPU fetches and decodes the operation code of an input or output instruction, it
places the address associated with the instruction into the common address lines.
At the same time, it enables the I/O read (for input) or I/O write (for output) control line.
This informs the external components that are attached to the common bus that the address
in the address lines is for an interface register and not for a memory word

The isolated I/O method isolates memory and I/O addresses so memory address values are
not affected by interface address assignment since each has its own address space.

The other alternative is to use the same address space for both memory and I/O.

This is the case in computers that employ only one set of read and write signals and do not
distinguish between memory and I/O addresses. This configuration is referred to as
memory-mapped I/O.

The CPU can manipulate I/O data residing in interface registers with the same instructions
that are used to manipulate memory words.

Strobe Control:

The strobe control method of asynchronous data transfer employs a single control line to
time each transfer. The strobe may be activated by either the source or the destination unit.

The data bus carries the binary information from source unit to the destination unit.
Typically, the bus has multiple lines to transfer an entire byte or word.

The strobe is a single line that informs the destination unit when a valid data word is
available in the bus.

8. Explain the data types of 8087


The NDP data types are divided into three main types , namely , Integer data type , BCD and
Real data type.
The integer data type is further divided into three
1. Word.
2. Double word.
3. Long.
Real data type is also divided into three main types
1. Short real format.
2. Long real format.
3. Temporary real format.

UnitIV

I/O INTERFACING

1.Explainthebasicinterfacingconceptofa8085microprocessor?

Multiplexing
Multiplexing is transferring different information at different well defined times
through same lines. A group of such lines is called multiplexed bus. The advantage of
multiplexing is that fewer pins are required for microprocessors to communicate with
outside world.
Theloworderaddressanddatalinesof8085aredemultiplexedusinganexternal8bitD
Latch(74LS373)andtheALEsignalof8085,asshowninfig.

8085

AoA7

7
ADoAD

74LS373

LATCH

D0D7

Demultiplexingofaddressanddatalinesin8085processor

At thebeginningof every machinecycle,ALE is asserted high andthen low. Alsothe low


byte of address is given out through ADo AD7 lines. Since the ALE is connected to Enable of
Latch,whenALEisassertedhighandthenlowtheaddressesarelatchedintotheoutputlinesof
thelatch.NowthelinesADoAD7arefreefordatatransfer.

TheIO/MisusedtodifferentiatememoryaccessandI/Oaccess.ForINandOUTinstructionitis
high.Formemoryreferenceinstructionsitislow.READYisaninputsignaltotheprocessor,used
bythememoryorI/Odevicestogetextratimefordatatransferortointroducewaitstatesin
thebuscycles.HOLDandHLDAsignalsareusedfortheDirectMemoryAccess(DMA)typeofdata
transfer.TheDMAcontrollerplaceahighonHOLDpininordertotakecontrolofthesystembus.
TheHOLDrequestisacknowledgedbythe8085bydrivingallitstristatedpinstohighimpedance
stateandassertingHLDAsignalhigh.
The processor cycle or machine cycle is the basic operation performed by the processor. To
executeaninstruction,theprocessorwillrunoneormoremachinecyclesinaparticularorder.

The sequence of operations that a processor has to carry out while executing the
instruction is called Instruction cycle. Each instruction cycle of a processor in tum consists of a
numberofmachinecycles.
Ingeneral,theinstructioncycleofaninstructioncanbedividedintofetchandexecute
cycles. The fetch cycle is executed to fetch the opcode from memory. The execute cycle is
executedtodecodetheinstructionandtoperformtheworkinstructedbytheinstruction.
Thevariousmachinecyclesof8085are

(i)Opcodefetchcycle
(ii)Memoryreadcycle
(iii)Memorywritecycle

(iv)1/0readcycle

(v)1/0writecycle

(vi)Interruptacknowledgecycle

(vii)Busidlecycle.

MemoryMapped1/0Standard1/0mapped1/0
1.16bitaddressisallotedto1.8bitaddressisallotedtoanI/O
anI/Odevicedevice.

2.Thedevicesareaccessedby

2.Thedevicesareaccessedby

I/OreadorI/Owritecycle.memoryreadormemorywrite
cycle.
3.Allinstructionsrelatedto

3.OnlyINandOUTinstructions

memorycanbeusedforcanbeusedfordatatransfer.
datatransfer.
4.AlargenumberofI/Oports4.Only256portscanbeinterfaced.
canbeinterfaced.
The memory mapping is the process of interfacing memories to microprocessor and
allocatingaddressestoeachmemorylocations.Thememoryaccesstimeisthetimetakenbythe
processor to read or write a memory location. During read operation it is the time between a
valid address on the bus and end of read control signal. During write operation it is the time
betweenavalidaddressonthebusandtheendofwritecontrolsignal.
Interrupt is a signal send by an external device to the processor so as to request the
processortoperformaparticulartaskorwork.
Theyarethreemethodsofclassifyinginterrupts
MethodI:TheinterruptsareclassifiedintoHardwareandSoftwareinterrupts
MethodII:TheinterruptsareclassifiedintovectoredandNonVectoredinterrupt

When an interrupt is accepted, if the processor control branches to a specific address


definedbythemanufacturerthentheinterruptiscalledvectoredinterrupt.

In Nonvectored interrupt there is no specific address for storing the interrupt service
routine.Hencetheinterrupteddeviceshouldgivetheaddressoftheinterruptserviceroutine.
Softwareinterrupts:
RST0,RSTl,RST2,
RST3,RST4,RST5,
RST6andRST7.
Hardwareinterrupts:
TRAP,RST7.5,RST6.5,
RST5.5andINTR.

Polling is a scheme or an algorithm to identify the devices interrupting the processor.


Pollingisemployedwhenmultipledevicesinterrupttheprocessorthroughoneinterruptpinof
theprocessor.

Thepollingcanbeclassifiedintosoftwareandhardwarepolling.Insoftwarepollingthe
entire polling process is govern by a prograrn.1n hardware polling, the hardware takes care of
checkingthestatusofinterruptingdevicesandallowingonebyonetotheprocessor.

2.Explainthememoryinterfacingof8085microprocessor?

AddressableMemory
Theamountofmemoryaddressingcapabilityneededdependsontheapplicationyouhave.
Usually, the larger the microprocessors data word, the larger the main memory space it can
address.Inasimplemicroprocessorbasesystem,theprogramstepsarestoredinROMandthe
variabledataisstoredinRAM.

CPU reads/fetches each instruction (one at a time), from memory and performs data
manipulation specified by the instruction. It also reads data from input devices, and writes (or
sends)datatooutputdevices.

TherearetwocategoriesofMPUcommunicationprocessandrelatedoperations.
-

MPU(orprogram)initiatedoperations
Peripheral(orexternally)initiatedoperations

Agroupoflogiccircuits
Asetofsignalstotransferinformation
controlsignalsfortiming
Clockcircuitry

1.
2.
3.
4.

Memoryread:Readsdata(binaryinformation)frommemory
Memorywrite:Writesdataintomemory
I/ORead:Acceptsdatafrominputdevices
I/OWrite:Senddatatooutputdevices

1. Identifythememorylocationortheperipheralwithitsaddress.

2. Providetimingorsynchronizationsignal.
3. Transferbinarydata.
To perform theoperationsdescribed above, theMPU requires three set ofcommunication
buseslines:
1. Addressbus:identifythememorylocation
2. Databus:transferdata
3. Controllines:timingsignals

Addressbus

Itdependsupontheinternaldesignofmicroprocessorandavailablepinsonachip(8,16,20,or
morebits).

Databus
These lines are used to transfer data are bidirectional. The size of the data bus
determineshowlargeabinarynumbercanbetransferredandprocessedatatime.The8085and
theZ80haveeightdatalinesandcalled8bitmicroprocessors.Ontheotherhand,the8086,the
80286,andtheZ8000have16datalinesandarecalled16bitmicroprocessors.

Controlsignals
TheseareindividualsignallinesgeneratedbytheMPUtoindicateitsoperations.

TheMPUgeneratesaspecificsignalforeachofitsfouroperations
-

MemoryRead
MemoryWrite
I/ORead
I/OWrite

Thesearetimingsignalsthatareusedtoenable,oractivate,peripherals.

ExternalRequestSignals

Reset:Startagainfromthebeginning.
Interrupt: Stop the ongoing process temporarily; do something now and then go back to the
originalprocess.
Wait:WhenmemoryresponsetimeistooslowtorespondtothespeedoftheMPU,thissignal
canbeusedtodelaytheMPUoperations.
Busrequest:WhentheMPUoperationsaretooslowcomparedtothespeedofaperipheral,the
peripheralcanrequesttheuseofthebuses.

RequestAcknowledgeSignals

The MPU to inform the external peripheral that it is ready to accept the request. To
indicateitsresponsetosomeoftheseexternalrequests,theMPUneedsadditionalsignals.

ClockSignalsandPower
Clock
Power
Ground
The timing is very critical in all its operations. Therefore, the MPU needs circuits that
generateclocksignals.

3.Whatisamemory?Explainhowdataisreadfrommemoryanddataiswrittenonmemory?
Alsoexplaintheneedofmemory?

Memory is and essential component of microcomputer system; it stores binary


instructions and data for the microprocessor. They can be classified in two groups: prime (or
main)memoryandstoragememory.

This latch,whichcanstoreone binarybit,iscalled a memorycell. The R/W memory is


madeupofregisters,andeachregistercanusethismemorytoholdprogramsandstoredata.On
theotherhand,theROMstoresinformationpermanentlyintheformofdiodes.

Itisacircuitthatcanstorebits.Aflipfloporlatchisabasicelementofmemory.Towriteor
storeabitinthelatch,weneedaninputdatabitandanenablesignal

TocommunicatewithmemoryandI/Odevices,theMPUshouldhavethefollowingsixgroups
ofsignals:
1.
2.
1.
2.
3.
4.

AddressbustosendtheaddressofamemoryregisteroranI/O.
DatabustotransferdatabetweentheMPU
Controlsignalstoidentifyitsoperationsandprovidetiming.
ExternalRequestsignallinestointerrupttheMPUoperations.
RequestAcknowledgesignalstorespondtotherequestsbyperipherals.
Clocksignalstoprovidetimingandpowertooperatecircuits.
Toprocessinternally,theMPUshouldincludethefollowing:

1.
2.
3.
4.
5.

InstructionDecodertodecodethefetchedbinaryinformation.
Registerstostorebinarydata.
Registersasmemorypointersforaddressingmemoryregisters.
ALUtoperformarithmeticandlogicoperations.
Flags(flipflops)toindicatedataconditionsfordecisionmaking.

MPUwritesintoandReadsfromMemory
.
1. Placesthe16bitaddressontheaddressofthememorylocationwhereabyteistobestored.The
interfacinglogicofthememorychipdecodestheaddressandselectsthememoryregistertobe
writteninto.
2. Placesthebyteonthedatabus.
3. SendthecontrolsignalMemory.Writetoenabletheinputbufferofthememoryandthenstores
thebyte.
Toreadfrommemorythesteparesimilartothatofwritingintomemory,excepttheorderof
step2and3.
2. TheMPUsendthecontrolsignalMemoryReadtoenabletheoutputbufferofthememorychip.
3. Thememorychipplacesthedatabyteonthedatabus,andtheMPUreadsthedatabyte.
Therequirementsofamemory.

1. Amemorychiprequiresaddresslinestoidentifyamemoryregister,achipselectCSsignal.
2. Thenumberofaddresslinesrequiredisdeterminedbythenumberofregistersinachip(2n)
3. Ifadditionaladdresslinesareavailableinasystem,chipselectsignalisused.
4. ThecontrolsignalRead( RD )enablestheoutputbuffer.ThecontrolsignalWrite( WR )enables
theinputbuffer.

MemoryMapandAddress

Typically,inan8bitmicroprocessorsystem,16addresslinesareavailableformemory.It
iscapableofidentifying216(65,536)memoryregisters,eachregisterwitha16bitaddress.The
entirememoryaddressescanrangefrom0000toFFFFinHex.

4.ExplainmemorymappedI/OandI/OmappedI/O?Alsoexplaintheoperationsperformedin
aninstruction?

Input/outputdevicesarethemeansthroughwhichtheMPUcommunicationswiththe
outsideworld.TheMPUacceptsbinarydataasinputfromdevicessuchaskeyboardsandA/D
convertersandsendsdatatooutputdevicessuchasLEDsorprinters.
TherearetwodifferentmethodsbywhichanMPUcanidentifyI/Odevices:
o
o

8bitaddress
16bitaddress

I/Oswith8bitAddresses(PeripheralMappedI/O)

TheMPUuseseightaddresslinestoidentifyaninputoranoutputdevice.TheMPUcan
identify256inputand256outputdeviceswithaddressesrangingfrom00HtoFFH.
ThestepsincommunicatingwithI/Odevicecanbesummarizedasfollows:

1. TheMPU places an 8 bit address on the address bus, which is decodes by the external decode
logic.

2. TheMPUsendsacontrolsignal(I/OReadorI/OWrite)toenabletheI/Odevice.
3. Dataaretransferredonthedatabus.

I/Oswith16bitAddresses(MemoryMappedI/O)

The MPU uses 16 address lines to identify an I/O device; an I/O is connected as if
it is a memory register. In memory-mapped I/O, the MPU uses the same control signals
(Memory Read or Memory Write) and instructions as there of memory and follows the
same steps as when it is accessing a memory register.

Toexecutethisoneinstruction,theMPUperformsthefollowingoperations.

1. MPUmustreadthebinarycodeoftheoutinstructionstoredinlocation8000H.Toreadthecode
D3,theMPUplacestheaddress8000Hontheaddressbus,enablesthememorychipbyasserting
theMemoryRead( MEMRD )signal,andfetchesthecodeD3Husingthedatabus.Thisiscalled
thefetchoperation.

2. ThecodeD3Hintheinstructiondecoderanditisinterpretedasatwobyteinstruction.TheMPU
placesthenextaddress8001Hontheaddressbus,assertsthe MEMRD signal,andfetchesthe
address43H.Nowithasreadthecompleteinstruction,andisreadytoexecutetheinstruction.

3. TheMPUplacestheaddressofthefanoutputport(43H)ontheaddressbus,sendsabytetoturn
onthefanusingthedatabus,andassertstheIOWRsignaltoenabletheoutputport.
Operationsperformedinaninstructions

Fetchinganinstruction

The microprocessor places a memory address on the address bus and reads binary
information using the data bus. Therefore, it needs a register that can hold memory addresses
andincrementtheseaddressesafterthefetchingiscomplete,asortofmemorypointer.

Decodinganinstruction

Onceaninstructionbyteisfetched,itneedstobedecodedtoanswerthefollowing:
Isitacompleteinstruction?Ifnot,howmanymorebytesneedtobefetched?
Whattypeofoperationisrequiredandonwhatdata?

Executinganinstruction

The type of data manipulation the MPU can perform depends on its internal micro
programs,thatis,onitsinstructionset.Theseoperationscanbeclassifiedasdatacopy(transfer),
arithmetic/logic operations, and decision making. For example, to subtract two numbers, both
numbersmustbeloadedintoregisters.Afterthesubtraction,itisnecessarytoindicatewhether
the result is positive, negative, or zero. This can be indicated by setting or resetting flipflops
calledflags.

5.Explainthearchitectureof8255Programmableperipheralinterface?

1.Data bus buffer


2. Read Write control logic
3. Group A and Group B controls
4. Port A, B and C

Databusbuffer:

This is a tristate bidirectional buffer used to interface the 8255 to system databus. Data is
transmitted or received by the buffer on execution of input or output instruction by the CPU.
Control word and status information are also transferred through this unit.

Read/Writecontrollogic:

This unit accepts control signals ( RD , WR ) and also inputs from address bus and issues
commands to individual group of control blocks ( Group A, Group B).

a) CS Chip select : A low on this PIN enables the communication between CPU and 8255.
b) RD (Read) A low on this pin enables the CPU to read the data in the ports or the status word
through data bus buffer.
c) WR ( Write ) : A low on this pin, the CPU can write data on to the ports or on to the control
register through the data bus buffer.
d) RESET: A high on this pin clears the control register and all ports are set to the input mode
e) A0 and A1 ( Address pins ): These pins in conjunction with RD and WR pins control the selection
of one of the 3 ports.

GroupAandGroupBcontrols

These block receive control from the CPU and issues commands to their respective ports.

Group A - PA and PCU ( PC7 PC4)


Group B - PCL ( PC3 PC0)
Control word register can only be written into no read operation of the CW register is allowed.

a) Port A: This has an 8 bit latched/buffered O/P and 8 bit input latch. It can be programmed in 3
modes mode 0, mode 1, mode 2.
b) Port B: This has an 8 bit latched / buffered O/P and 8 bit input latch. It can be programmed in
mode 0, mode1.
c) Port C: This has an 8 bit latched input buffer and 8 bit out put latched/buffer. This port can be
divided into two 4 bit ports and can be used as control signals for port A and port B. it can be
programmed in mode 0.

ModesofOperationof8255

These are two basic modes of operation of 8255. I/O mode and Bit Set-Reset mode (BSR).

In I/O mode, the 8255 ports work as programmable I/O ports, while in BSR mode only port C
(PC0-PC7) can be used to set or reset its individual port bits.

Under the I/O mode of operation, further there are three modes of operation of 8255, so as to
support different types of applications, mode 0, mode 1 and mode 2.

BSRMode: In this mode any of the 8-bits of port C can be set or reset depending
on D0 of the control word.

BasicI/Omode

This mode is also called as basic input/output mode. This mode provides simple input and
output capabilities using each of the three ports. Data can be simply read from and written to the
input and output ports respectively, after appropriate initialisation.

The salient features of this mode are as listed below:


1.
2.
3.
4.
5.
6.

Two 8-bit ports ( port A and port B )and two 4-bit ports (port C upper and lower ) are available.
The two 4-bit ports can be combinedly used as a third 8-bit port.
Any port can be used as an input or output port.
Outputportsarelatched.Inputportsarenotlatched.
Amaximumoffourportsareavailablesothatoverall16I/Oconfigurationarepossible.
Allthesemodescanbeselectedbyprogrammingaregisterinternalto8255knownasCWR
Thecontrolwordregisterhastwoformats.ThefirstformatisvalidforI/Omodesofoperation,
i.e.modes0,mode1andmode2whilethesecondformatisvalidforbitset/reset(BSR)modeof
operation.

6.Explainthepindiagramof8255Programmableperipheralinterface?

The parallel input-output port chip 8255 is also called as programmableperipheral inputoutput
port. The Intels 8255 is designed for use with Intels 8-bit, 16-bit and higher capability

microprocessors. It has 24 input/output lineswhich may be individually programmed in two groups


of twelve lines each, orthree groups of eight lines
.
The two groups of I/O pins are named as Group A and Group B. Each of these two groups
contains a subgroup of eight I/O lines called as 8-bit port and another subgroup of four lines or a 4bit port. Thus Group A contains an 8-bit port A along with a 4-bit port C upper.

The port A lines are identified by symbols PA0-PA7 while the port C lines are identified as PC4PC7. Similarly, Group B contains an 8-bit port B, containing lines PB0-PB7 and a 4-bit port C with
lower bits PC0- PC3. The port C upper and port C lower can be used in combination as an 8-bit
port C.

Both the port C are assigned the same address. Thus one may have either three 8-bit I/O ports or
two 8-bit and two 4-bit ports from 8255. All of these ports can function independently either as
input or as output ports. This can be achieved by programming the bits of an internal register of
8255 called as control word register ( CWR ).

The 8-bit data bus buffer is controlled by the read/write control logic. The read/write control
logic manages all of the internal and external transfers of both data and control words.

RD , WR , A1, A0 and RESET are the inputs provided by the microprocessor to the READ/
WRITE control logic of 8255. The 8-bit, 3-state bidirectional buffer is used to interface the 8255
internal data bus with the external system data bus.

This buffer receives or transmits data upon the execution of input or output instructions by the
microprocessor. The control words or status information is also transferred through the buffer.

PA7PA0: These are eight port A lines that acts as either latched output or buffered input lines
depending upon the control word loaded into the control word register.

PC7PC4 : Upper nibble of port C lines. They may act as either output latches or input buffers
lines.

This port also can be used for generation of handshake lines in mode 1 or mode 2.

PC3PC0: These are the lower port C lines, other details are the same as PC7-PC4 lines.

PB0PB7 : These are the eight port B lines which are used as latched output lines or buffered input
lines in the same way as port A.

RD : This is the input line driven by the microprocessor and should be low to indicate read
operation to 8255.

WR : This is an input line driven by the microprocessor. A low on this line indicates write
operation.

CS : This is a chip select line. If this line goes low, it enables the 8255 to respond to RD and WR
signals, otherwise RD and WR signal are neglected.

A1A0 : These are the address input lines and are driven by the microprocessor. These lines A1-A0
with RD , WR and CS from the following operations for 8255.

D0D7: These are the data bus lines those carry data or control word to/from the microprocessor.

RESET : A logic high on this line clears the control word register of 8255. All ports are set as
input ports by default after reset.

7.Explain the architecture of 8279.

The 8279 It is a 40 pin device with two major segments: keyboard and display
1. The keyboard segment cab be connected to a 64 key matrix keyboard
2. Keys are automatically debounced and stored in 8X8 FIFO RAM
3. Display section contain 16X8 display RAM. and display can be set up in either right
entry or left entry format

8279 Architecture

8279 Block Diagram

The four major sections of 8279 are


1 keyboard,
2 scan,
2 display and
4 CPU interface.
Keyboard section:
1. The section has eight lines(RL0 - RL7) that can be connected to eight coluns of a
keyboard matrix.
2. It has two additional input : shift and control/strobe. The keys are automatically
debounced.
3.
The two operating modes of keyboard section are 1) 2-key lockout 2) N-key
rollover
4. In the 2-key lockout mode, if two keys are pressed simultaneously, only the first key
is recognized.
5. In the N-key rollover mode simultaneous keys are recognized and their codes are
stored in FIFO.
6. The keyboard section also have an 8 x 8 FIFO (First In First Out) RAM.The FIFO can
store eight key codes in the scan keyboard mode. The status of the shift key and
control key are also stored along with key code.
7. The 8279 generate an interrupt signal(IRQ) to MPU when the FIFO is not empty.
Scan section:

1. The scan section has a scan counter and four scan lines, SL0 to SL3.
2. These four scan lines cab be decoded as 16 scan lines by using 4-to-16 decoder.
3. These scan lines are connected to the rows of a matrix keyboard and digit drivers of a
multiplexed display keyb
Display section:
1. The display section has eight output lines divided into two groups A0-A3 and B0-B3.
2. The output lines can be used either as a single group of eight lines or as two groups of
four lines, in conjunction with the scan lines for a multiplexed display.
3. The display can be blanked by BD (low) line.
4. The display section consists of 16 x 8 display RAM. The CPU can read from or write
into any location of the display RAM.
CPU interface section:
1. This section has eight bidirectional data lines DB0 to DB7 for data transfer between
8279 and CPU.
2. it has one IRQ line+six lines for interfacing

3. It requires two internal address if A0 =0 for selecting data buffer and A0 = 1 for
selecting control register address of 8279.
4. The control signals WR (low), RD (low), CS (low) and A0 are used for read/write to
8279.
5. The 8279 require an internal clock frequency of 100 kHz. This can be obtained by
dividing the input clock by an internal prescaler.
6. The RESET signal sets the 8279 in 16-character display with two -key lockout
keyboard modes.
8279 Data word Format:
Data word format used to read the pressed key

8279 Status word:


Status word used to read the status of the keys where key is pressed or not and check the
others conditions.

8.Explain the and stepper motor controller system using 8085 microprocessor?
A stepper motor is a device used to obtain an accurate position control of rotating
shafts. A stepper motor employs rotation of its shaft in terms of steps, rather than
continuous rotation as in case of AC or DC motor. A stepper motor rotates in steps in
responsetodigitalpulseinput.Theshaftsofthemotorrotateswithrespecttothepulseapplied.
Thedirectionofrotationdependsuponthepulseapplied.therearetwotypesofsteppermotor.

The interfacing of stepper motor to 8085 microprocessor and to run it in continuous


or stepped motion in forward or reverse direction under program control, using 8085
microprocessor.
The hardware setup consists of a microprocessor motherboard and stepper motor
interface board. The motherboard consists of 8085 MPU, 8KB EPROM, 8KB RAM,
Keyboard and display controller 8279, 21-key Hex-keypad and six numbers of seven
segment LEDs and Bus Expansion connector. The stepper motor interface consists of
driver transistors for stepper motor windings and address decoding circuit. The
microprocessor output the binary sequence through data bus, which are converted to
current pulses by the driver transistors and used to drive stepper motor. The software for
the system is developed in 8085 assembly language.

1. Permanentmagnettype.
2. Variablereluctancetype.

Thestatorwindingsareenergizedbypulses.

microprocessor

Bufferand
amplifier

8255

Pole
windingof
stepper
motor

Blockdiagramofasteppermotorcontrolsystem

Algorithm

Step1:initializealltheportsof8255asoutputports.
Step2:storethesteppermotorcontrolsequencedatainmemory.
Step3:setthecountertostorethenumberofconditions.
Step4;sendthefirstdatatoportA,SeconddatatoportBandthirddatatoportC.
Step5:callthedelayprogram.
Step6:repeatsteps2to6forcontinuousrotationofsteppermotor.

flowchart
start

Initializeportsof8255

Storetheswitchingsequenceinmemory

Setthecounter
OUTthedatatosteppermotor

Callthedelayprogram

Decrementthecounter

yes

No
Iscounter=0

stepper

Applicationsof
motor

The
immense
printing,
Precision
drilling,
machines,

stepper motors have


applications
in
Industrial Robotics,
tool motions in
cutting and shaping
latheetc.

Having identified the device, the processor then branches to the appropriate interrupthandling-routine address for the given device. The order in which the devices appear in the
polling sequence determines their priority.

U
UNIT 5
MICROCO
ONTROLLE
ERS

1.Explaain the arch


hitecture of 8051

12 MHzz clock. Proccessor instruuction cycle time 1


s. [in Classic
C
versiion]
_ An 8--bit ALU.

_ Harvard memory architecture the external


program memory and data memory have separate
address spaces from 0x0000 and separate control
signal(s).
_ 8-bit internal data bus width and 16-bit internal
address bus Harvard memory architecture
_ CISC (Complex Instruction Set Computer)
Special function registers (SFRs) PSW
(processor status word), A (accumulator),
B register, SP (stack pointer) and registers
for serial IOs, timers, ports and interrupt
handler.
Special bit manipulation instructions.
_ 16-bit Program counter with initial default
reset value defined by processor is
0x0000.
_ 8-bit stack pointer with initial default
value defined by processor is 0x07
Classic 8051 simple architecture
_ no floating-point processor,
_ no cache,
_ no memory management-unit,
_ no atomic operations unit,
_ no pipeline and
_ no instruction level parallelism.
RAM 256 bytes.]
_ 32 bytes of RAM also used as four banks
(sets) of registers. Each register-set (bank)
thus eight registers.
_ External data/stack memory can be added
upto 64 kB in most version. In certain
8051 enhancements, this limit enhanced to
16 MB
8051 microcontroller features
_ Two external interrupt pins, INT0 and INT1.
_ Four ports of 8-bits each in single chip mode.
_ Two timers
_ Serial interface (SI)programmable for three
full duplex UART modes for serial IO. [IO
with each bit of a word successive
transmission on the data line for a time
interval.] The same be programmable for half
duplex synchronous IO
In certain versions DMA controller
_ In certain versions pulse width modulator

and thus support to DAC, d.c. and servo


motor controls.
_ In Certain versions modem, watchdog
timer, ADC. Siemens SAB 80535-N
supports ADC with programmable
reference voltage. Advanced versions
support these features and a version is
selected as per the system requirement
2.Explain the pin diagram of 8051

18: Port 1- Each of these pins can be used as either input or output according to your
needs. Also, pins 1 and 2 (P1.0 and P1.1) have special functions associated with timer 2. 9:
Reset Signal; high logical state on this input halts the MCU and clears all the registers.
Bringing this pin back to logical state zero starts the program anew as if the power had just
been turned on.
10-17: Port 3 - As with Port 1, each of these pins can be used as universal input or output.
However, each pin of Port 3 has an alternative function.
Pin 10: RXD - serial input for asynchronous communication or serial output for
synchronous communication.

Pin 11: TXD - serial output for asynchronous communication or clock output for
synchronous communication.
Pin 12: INT0 - input for interrupt 0.
Pin 13: INT1 - input for interrupt 1.
Pin 14: T0 - clock input of counter 0.
Pin 15: T1 - clock input of counter 1.
Pin 16: WR - signal for writing to external (add-on) RAM memory.
Pin 17: RD - signal for reading from external RAM memory.
18-19: X2 and X1; Input and output of internal oscillator. Quartz crystal controlling the
frequency commonly connects to these pins. Capacitances within the oscillator mechanism
(see the image) are not critical and are normally about 30pF. Instead of a quartz crystal,
miniature ceramic resonators can be used for dictating the pace. In that case,
manufacturers recommend using somewhat higher capacitances (about 47 pF).
20: GND.
Ground 21- 28: Port 2 - If external memory is not present, pins of Port 2 act as universal
input/output. If external memory is present, this is the location of the higher address byte,
i.e. addresses A8 A15.
29: PSEN - MCU activates this bit (brings to low state) upon each reading of byte
(instruction) from program memory. If external ROM is used for storing the program,
PSEN is directly connected to its control pins.
30: ALE -Before each reading of the external memory, MCU sends the lower byte of the
address register (addresses A0 A7) to port P0 and activates the output ALE. External
register (74HCT373 or 74HCT375 circuits are common), memorizes the state of port P0
upon receiving a signal from ALE pin, and uses it as part of the address for memory chip.
During the second part of the mechanical MCU cycle, signal on ALE is off, and port P0 is
used as Data Bus.
31: EA - Bringing this pin to the logical state zero (mass) designates the ports P2 and P3
for transferring addresses regardless of the presence of the internal memory. This means
that even if there is a program loaded in the MCU it will not be executed, but the one from
the external ROM will be used instead. Conversely, bringing the pin to the high logical
state causes the controller to use both memories, first the internal, and then the external (if
present).
32-39: Port 0 - Similar to Port 2, pins of Port 0 can be used as universal input/output, if
external memory is not used. If external memory is used, P0 behaves as address output
(A0 A7) when ALE pin is at high logical level, or as data output (Data Bus) when ALE
pin is at low logical level.
40: VCC - Power +5V.
3.Explain the ports of 8051?

Input Output (I/O) Ports


Every MCU from 8051 family has 4 I/O ports of 8 bits each. This provides the user with
32 I/O lines for connecting MCU to the environs. Unlike the case with other controllers,
there is no specific SFR register for designating pins as input or output. Instead, the port
itself is in charge: 0=output, 1=input. If particular pin on the case is needed as output, the
appropriate bit of I/O port should be cleared. This will generate 0V on the specified
controller pin. Similarly, if particular pin on the case is needed as input, the appropriate bit
of I/O port should be set. This will designate the pin as input, generating +5V as a side
effect.
PORT 0
Port 0 has two fold role: if external memory is used, it contains the lower address byte
(addresses A0-A7), otherwise all bits of the port are either input or output. Another feature
of this port comes to play when it has been designated as output. Unlike other ports, Port 0
lacks the "pull up" resistor (resistor with +5V on one end). This seemingly insignificant
change has the following consequences:

When designated as input, pin of Port 0 acts as high impedance offering the infinite input
resistance with no "inner" voltage.

When designated as output, pin acts as "open drain". Clearing a port bit grounds the
appropriate pin on the case (0V). Setting a port bit makes the pin act as high impedance.
Therefore, to get positive logic (5V) at output, external "pull up" resistor needs to be
added for connecting the pin to the positive pole.
Port 1
This is "true" I/O port, devoid of dual function characteristic for Port 0. Having the "pull
up" resistor, Port 1 is fully compatible with TTL circuits.
Port 2
When using external memory, this port contains the higher address byte (addresses A8
A15), similar to Port 0. Otherwise, it can be used as universal I/O port.
Port 3
Beside its role as universal I/O port, each pin of Port 3 has an alternate function. In order
to use one of these functions, the pin in question has to be designated as input, i.e. the
appropriate bit of register P3 needs to be set. From a hardware standpoint, Port 3 is similar
to Port 0.

Types of Memory

The 8051 has three very general types of memory. To effectively program the 8051 it is
necessary to have a basic understanding of these memory types. The memory types are
illustrated in the following graphic. They are: On-Chip Memory, External Code Memory,
and External RAM.
On - Chip
On-Chip Memory refers to any memory (Code, RAM, or other) that physically exists on
the microcontroller itself. On-chip memory can be of several types, but we'll get into that
shortly.
External Code Memory
External Code Memory is code (or program) memory that resides off-chip. This is often in
the form of an external EPROM.
External RAM
External RAM is RAM memory that resides off-chip. This is often in the form of standard
static RAM or flash refers to any memory (Code, RAM, or other) that physically exists on
the microcontroller itself. On-chip memory can be of several types, but we'll get into that
shortly.
Code Memory
Code memory is the memory that holds the actual 8051 program that is to be run. This
memory is limited to 64K and comes in many shapes and sizes: Code memory may be
found on-chip, either burned into the microcontroller as ROM or EPROM. Code may also
be stored completely off-chip in an external ROM or, more commonly, an external
EPROM. Flash RAM is also another popular method of storing a program. Various
combinations of these memory types may also be used--that is to say, it is possible to have
4K of code memory on-chip and 64k of code memory off-chip in an EPROM.
External RAM
External RAM As an obvious opposite of Internal RAM, the 8051 also supports what is
called External RAM. As the name suggests, External RAM is any random access memory
which is found off-chip. Since the memory is off-chip it is not as flexible in terms of
accessing, and is also slower. For example, to increment an Internal RAM location by 1
requires only 1 instruction and 1 instruction cycle. To increment a 1-byte value stored in
External RAM requires 4 instructions and 7 instruction cycles. In this case, external
memory is 7 times slower!
On-Chip Memory

As menntioned earliier, the 8051 includes a certain am


mount of on--chip memoory. On-chipp
memoryy is really one
o of two types:
t
Internnal RAM annd Special F
Function Reggister (SFR))
memoryy.
The 805
51 has a bannk of 128 byytes of Interrnal RAM. This
T Internall RAM is found on-chipp
on the 8051
8
so it iss the fastest RAM availaable, and it is
i also the m
most flexiblee in terms off
readingg, writing, annd modifyingg its contents. Internal RAM
R
is volattile, so when
n the 8051 iss
reset th
his memory is
i cleared. The
T 128 bytees of internall ram is subddivided as shhown on thee
memoryy map. The first 8 bytess (00h - 07h)) are "registeer bank 0". B
By manipulaating certainn
SFRs, a program may
m choose to use regisster banks 1, 2, or 3. Thhese alternaative registerr
banks are
a located in
n internal RA
AM in addreesses 08h thrrough 1Fh.
Bit Mem
mory also livves and is paart of internaal RAM. Bitt memory actually residees in internall
RAM, from
f
addressses 20h thro
ough 2Fh. T
The 80 bytess remaining of Internal RAM, from
m
addressses 30h throough 7Fh, may
m be usedd by user variables
v
thaat need to be
b accessedd
frequenntly or at hig
gh-speed. Thhis area is aalso utilized by the micrrocontroller as a storagee
area forr the operatiing stack. Thhis fact seveerely limits the
t 8051s sttack since, as
a illustratedd
in the memory
m
mapp, the area reeserved for tthe stack is only 80 bytees--and usuaally it is lesss
since thhese 80 bytess has to be sh
hared betweeen the stackk and user vaariables.

Register
Banks
The 80051 uses 8 "R"
"
registerrs which aree used in many
m
of its instructions.. These "R""
registerrs are numbeered from 0 through 7 (R0, R1, R22, R3, R4, R
R5, R6, andd R7). Thesee

registers are generally used to assist in manipulating values and moving data from one
memory location to another. For example, to add the value of R4 to the Accumulator, we
would execute the following instruction:
ADD A, R4
Thus if the Accumulator (A) contained the value 6 and R4 contained the value 3, the
Accumulator would contain the value 9 after this instruction was executed.
However, as the memory map shows, the "R" Register R4 is really part of Internal RAM.
Specifically, R4 is address 04h. Thus the above instruction accomplishes the same thing as
the following operation:
ADD A, 04h
This instruction adds the value found in Internal RAM address 04h to the value of the
Accumulator, leaving the result in the Accumulator. Since R4 is really Internal RAM 04h,
the above instruction effectively accomplished the same thing.
As the memory map shows, the 8051 has four distinct register banks. When the 8051 is
first booted up, register bank 0 (addresses 00h through 07h) is used by default. However,
your program may instruct the 8051 to use one of the alternate register banks; i.e., register
banks 1, 2, or 3. In this case, R4 will no longer be the same as Internal RAM address 04h.
For example, if your program instructs the 8051 to use register bank 3, "R" register R4
will now be synonymous with Internal RAM address 1Ch.
Bit Memory
The 8051, being a communications-oriented microcontroller, gives the user the ability to
access a number of bit variables. These variables may be either 1 or 0. There are 128 bit
variables available to the user, numbered 00h through 7Fh. The user may make use of
these variables with commands such as SETB and CLR. For example, to set bit number 24
(hex) to 1 you would execute the instruction:
SETB 24h
It is important to note that Bit Memory is really a part of Internal RAM. In fact, the 128 bit
variables occupy the 16 bytes of Internal RAM from 20h through 2Fh. Thus, if you write
the value FFh to Internal RAM address 20h youve effectively set bits 00h through 07h.
That is to say that:
MOV 20h,#0FFh

is equivalent to:
SETB 00h
SETB 01h
SETB 02h
SETB 03h
SETB 04h
SETB 05h
SETB 06h
SETB 07h
4.Explain Special Function Registers (SFR) of 8051
The 8051 is a flexible microcontroller with a relatively large number of modes of
operations. Your program may inspect and/or change the operating mode of the 8051 by
manipulating the values of the 8051's Special Function Registers (SFRs).
SFRs are accessed as if they were normal Internal RAM. The only difference is that
Internal RAM is from address 00h through 7Fh whereas SFR registers exist in the address
range of 80h through FFh.
Each SFR has an address (80h through FFh) and a name. The chart on next page provides
a graphical presentation of the 8051's SFRs, their names, and their address.
Although the address range of 80h through FFh offer 128 possible addresses, there are
only 21 SFRs in a standard 8051. All other addresses in the SFR range (80h through FFh)
are considered invalid. Writing to or reading from these registers may produce undefined
values or behavior.
SFR Types
As mentioned in the chart itself, the SFRs that have a blue background are SFRs related to
the I/O ports. The 8051 has four I/O ports of 8 bits, for a total of 32 I/O lines. Whether a
given I/O line is high or low and the value read from the line are controlled by the SFRs in
green. TCON controls the timers, SCON controls the serial port.

The remaining SFRs, with green backgrounds, are "other SFRs." These SFRs can be
thought of as auxiliary SFRs in the sense that they don't directly configure the 8051 but
obviously the 8051 cannot operate without them. For example, once the serial port has
been configured using SCON, the program may read or write to the serial port using the
SBUF register.
SFR Desdriptions
P0 (Port 0, Address 80h, Bit-Addressable)
This is input/output port 0. Each bit of this SFR corresponds to one of the pins on the
microcontroller. For example, bit 0 of port 0 is pin P0.0, bit 7 is pin P0.7. Writing a value
of 1 to a bit of this SFR will send a high level on the corresponding I/O pin whereas a
value of 0 will bring it to a low level.
SP (Stack Pointer, Address 81h)
This is the stack pointer of the microcontroller. This SFR indicates where the next value to
be taken from the stack will be read from in Internal RAM. If you push a value onto the
stack, the value will be written to the address value onto the stack at address 08h. This
SFR is modified by all instructions which modify the stack, such as PUSH, POP, LCALL,
RET, RETI, and whenever interrupts are provoked by the microcontroller.
DPL/DPH (Data Pointer Low/High, Addresses 82h/83h)
The SFRs DPL and DPH work together to represent a 16-bit value called the Data Pointer.
The data pointer is used in operations regarding external RAM and some instructions
involving code memory. Since it is an unsigned two-byte integer value, it can represent
values from 0000h to FFFFh (0 through 65,535 decimal).
PCON (Power Control, Addresses 87h)
The Power Control SFR is used to control the 8051's power control modes. Certain
operation modes of the 8051 allow the 8051 to go into a type of "sleep" mode which
requires much less power. These modes of operation are controlled through PCON.
Additionally, one of the bits in PCON is used to double the effective baud rate of the
8051's serial port.
TCON (Timer Control, Addresses 88h, Bit-Addressable)
The Timer Control SFR is used to configure and modify the way in which the 8051's two
timers operate. This SFR controls whether each of the two timers is running or stopped
and contains a flag to indicate that each timer has overflowed. Additionally, some nontimer related bits are located in the TCON SFR. These bits are used to configure the way

in which the external interrupts are activated and also contain the external interrupt flags
which are set when an external interrupt has occurred.
TMOD (Timer Mode, Addresses 89h)
The Timer Mode SFR is used to configure the mode of operation of each of the two
timers. Using this SFR your program may configure each timer to be a 16-bit timer, an 8bit auto reload timer, a 13-bit timer, or two separate timers. Additionally, you may
configure the timers to only count when an external pin is activated or to count "events"
that are indicated on an external pin.
TL0/TH0 (Timer 0 Low/High, Addresses 8Ah/8Ch)
These two SFRs, taken together, represent timer 0. Their exact behavior depends on how
the timer is configured in the TMOD SFR; however, these timers always count up. What is
configurable is how and when they increment in value.
TL1/TH1 (Timer 1 Low/High, Addresses 8Bh/8Dh)
These two SFRs, taken together, represent timer 1. Their exact behavior depends on how
the timer is configured in the TMOD SFR; however, these timers always count up. What is
configurable is how and when they increment in value.
P1 (Port 1, Address 90h, Bit-Addressable)
This is input/output port 1. Each bit of this SFR corresponds to one of the pins on the
microcontroller. For example, bit 0 of port 1 is pin P1.0, bit 7 is pin P1.7. Writing a value
of 1 to a bit of this SFR will send a high level on the corresponding I/O pin whereas a
value of 0 will bring it to a low level.
SCON (Serial Control, Addresses 98h, Bit-Addressable)
The Serial Control SFR is used to configure the behavior of the 8051's on-board serial
port. This SFR controls the baud rate of the serial port, whether the serial port is activated
to receive data, and also contains flags that are set when a byte is successfully sent or
received.
SBUF (Serial Control, Addresses 99h)
The Serial Buffer SFR is used to send and receive data via the on-board serial port. Any
value written to SBUF will be sent out the serial port's TXD pin. Likewise, any value
which the 8051 receives via the serial port's RXD pin will be delivered to the user program
via SBUF. In other words, SBUF serves as the output port when written to and as an input
port when read from.

I/O ports
z List the 4 ports of the 8051
z Describe the dual role of port 0 in providing both data and addresses
z Code Assembly language to use the ports for input or output
z Explain the dual role of port 0 and port 2
z Code 8051 instructions for I/O handling
z Code I/O bit-manipulation programs for the 8051
z I/O port pins and their functions

All the ports upon RESET are configured


as inputs, ready to be used as input ports.

When the first 0 is written to a port, it becomes an output.

z To reconfigure it as an input, a 1 must be sent to the port.


To use any of these ports as an input port, it must be programmed
z Port 0

Port 0
z It can be used for input or output.
z To use the pins of port 0 as both input and output each pin must be connected externally to
a 10 Kohm pull-up resistor.
This is due to the fact that P0 is an open drain, unlike P 1, P2, and P3
Port 0 as input
z With resistors connected to port 0, in order to make it an input, the port must be
programmed by writing 1 to all the bits.

Dual role of port 0

z Port 0 is also designated as AD0 - AD7, allowing it to be used for both address and data.
z When connecting an 8051/31 to an external memory, port 0 provides both address and
data.
The 8051 multiplexes address and data through port 0 to save pins
8051 I/O PROGRAMMING

z Port 1
z It can be used as input or output.
z This port does not need any pull-up resistors since it already has pull-up resistors
internally.
z Upon reset, port I is configured as an input port.

Port 1 as input
z If port 1 has been configured as an output port, to make it an input port again, it must
programmed as such by writing 1 to all its bits.
z In the following code, port 1 is configured first as an input port by writing 1 s to it, then
data is received from that port and saved in R7, R6, and R5.

5.Explain the Memory organization of 8051

The 805
51 has three very generaal types of m
memory. To effectively
e
program the 8051
8
it is
necessaary to have a basic underrstanding of these memoory types.
The meemory types are illustrateed in the folllowing graph
hic. They aree: On-Chip Memory,
M
Externaal Code Mem
mory, and Ex
xternal RAM
M.

On-Chip Memory refers to anyy memory (C


Code, RAM, or other) thhat physicallly exists on
the miccrocontroller itself. On-chhip memoryy can be of seeveral types,, but we'll geet into that
shortly..
External Code Meemory is codde (or prograam) memory
y that residess off-chip. Th
his is often
in the foorm of an exxternal EPRO
OM.
External RAM is RAM
R
memoory that residdes off-chip. This is oftenn in the form
m of
standard
d static RAM
M or flash RAM.
R
Code Memory
M
Code memory
m
is thee memory thhat holds thee actual 8051
1 program thhat is to be ruun. This
memoryy is limited to
t 64K and comes
c
in maany shapes an
nd sizes: Coode memory may be
found on-chip,
o
eitheer burned innto the microocontroller ass ROM or EPROM. Cod
de may also
be storeed completelly off-chip inn an externall ROM or, more
m
commonly, an exterrnal
EPROM
M. Flash RA
AM is also annother popular method of storing a program. Varrious
combinnations of theese memory types may aalso be used---that is to saay, it is possible to have
4K of code
c
memoryy on-chip annd 64k of codde memory off-chip
o
in ann EPROM.
When thhe program is stored on--chip the 64K
K maximum
m is often redduced to 4k, 8k, or 16k.
This vaaries dependiing on the veersion of thee chip that is being used. Each versioon offers
specificc capabilitiess and one off the distinguuishing factors from chipp to chip is how
h much
ROM/E
EPROM spacce the chip has.
h
Howeveer, code mem
mory is most commonlyy implementeed as off-chiip EPROM. This is
especiaally true in loow-cost deveelopment sysstems and inn systems devveloped by students.
s
Prograamming Tip
p: Since codee memory is restricted too 64K, 8051 programs arre limited to
64K. So
ome assemblers and com
mpilers offerr ways to gett around this limit when used with
speciallly wired harddware. How
wever, withouut such speciial compilerss and hardware,
program
ms are limiteed to 64K.

External RAM
As an obvious
o
oppo
osite of Interrnal RAM, thhe 8051 alsoo supports whhat is called External
RAM.
As the name
n
suggessts, Externall RAM is anyy random acccess memorry which is found
f
offchip. Siince the mem
mory is off-cchip it is not as flexible in
i terms of aaccessing, annd is also
slower. For examplle, to increm
ment an Internnal RAM loccation by 1 rrequires onlyy 1
instructtion and 1 innstruction cycle. To increement a 1-byyte value stoored in External RAM
requiress 4 instructioons and 7 insstruction cyccles. In this case,
c
externaal memory iss 7 times
slower!
What External
E
RAM
M loses in sp
peed and flexxibility it gaains in quantiity. While Innternal
RAM iss limited to 128
1 bytes (2256 bytes witth an 8052), the 8051 suupports Exterrnal RAM
up to 644K.
Prograamming Tip
p: The 8051 may
m only adddress 64k off RAM. To eexpand RAM
M beyond
this lim
mit requires programming
p
g and hardware tricks. You
Y may havve to do this "by
" hand"
since many
m
compileers and assem
mblers, whille providing support for programs inn excess of
64k, doo not supportt more than 64k
6 of RAM
M. This is rathher strange ssince it has been
b
my
experience that proggrams can usually
u
fit in 64k but ofteen RAM is w
what is lackinng. Thus if
you neeed more thann 64k of RAM
M, check to see if your compiler
c
suppports it-- buut if it
doesn't,, be prepared
d to do it by hand.
On-Chip Memory
As menntioned at thee beginning of this chaptter, the 80511 includes a certain amouunt of onchip meemory. On-cchip memory
y is really onne of two typpes: Internal RAM and Special
S
Functioon Register (SFR) memo
ory. The layoout of the 8051's internall memory is presented
in the foollowing meemory map:

As is illlustrated in this
t map, thee 8051 has a bank of 1288 bytes of Internal RAM
M. This
Internall RAM is fou
und on-chip on the 80511 so it is the fastest RAM
M available, and
a it is

also the most flexible in terms of reading, writing, and modifying its contents. Internal
RAM is volatile, so when the 8051 is reset this memory is cleared.
The 128 bytes of internal ram is subdivided as shown on the memory map. The first 8
bytes (00h - 07h) are "register bank 0". By manipulating certain SFRs, a program may
choose to use register banks 1, 2, or 3. These alternative register banks are located in
internal RAM in addresses 08h through 1Fh. We'll discuss "register banks" more in a later
chapter. For now it is sufficient to know that they "live" and are part of internal RAM.
Bit Memory also lives and is part of internal RAM. We'll talk more about bit memory very
shortly, but for now just keep in mind that bit memory actually resides in internal RAM,
from addresses 20h through 2Fh.
The 80 bytes remaining of Internal RAM, from addresses 30h through 7Fh, may be used
by user variables that need to be accessed frequently or at high-speed. This area is also
utilized by the microcontroller as a storage area for the operating stack. This fact severely
limits the 8051s stack since, as illustrated in the memory map, the area reserved for the
stack is only 80 bytes--and usually it is less since this 80 bytes has to be shared between
the stack and user variables.
Register Banks
The 8051 uses 8 "R" registers which are used in many of its instructions. These "R"
registers are numbered from 0 through 7 (R0, R1, R2, R3, R4, R5, R6, and R7). These
registers are generally used to assist in manipulating values and moving data from one
memory location to another. For example, to add the value of R4 to the Accumulator, we
would execute the following instruction:
ADD A,R4
Thus if the Accumulator (A) contained the value 6 and R4 contained the value 3, the
Accumulator would contain the value 9 after this instruction was executed.
However, as the memory map shows, the "R" Register R4 is really part of Internal RAM.
Specifically, R4 is address 04h. This can be see in the bright green section of the memory
map. Thus the above instruction accomplishes the same thing as the following operation:
ADD A,04h
This instruction adds the value found in Internal RAM address 04h to the value of the
Accumulator, leaving the result in the Accumulator. Since R4 is really Internal RAM 04h,
the above instruction effectively accomplished the same thing.
But watch out! As the memory map shows, the 8051 has four distinct register banks.
When the 8051 is first booted up, register bank 0 (addresses 00h through 07h) is used by
default. However, your program may instruct the 8051 to use one of the alternate register
banks; i.e., register banks 1, 2, or 3. In this case, R4 will no longer be the same as Internal
RAM address 04h. For example, if your program instructs the 8051 to use register bank 3,
"R" register R4 will now be synonomous with Internal RAM address 1Ch.

The concept of register banks adds a great level of flexibility to the 8051, especially when
dealing with interrupts (we'll talk about interrupts later). However, always remember that
the register banks really reside in the first 32 bytes of Internal RAM.
Programming Tip: If you only use the first register bank (i.e. bank 0), you may use
Internal RAM locations 08h through 1Fh for your own use. But if you plan to use register
banks 1, 2, or 3, be very careful about using addresses below 20h as you may end up
overwriting the value of your "R" registers!
Bit Memory
The 8051, being a communications-oriented microcontroller, gives the user the ability to
access a number of bit variables. These variables may be either 1 or 0.
There are 128 bit variables available to the user, numberd 00h through 7Fh. The user may
make use of these variables with commands such as SETB and CLR. For example, to set
bit number 24 (hex) to 1 you would execute the instruction:
SETB 24h
It is important to note that Bit Memory is really a part of Internal RAM. In fact, the 128 bit
variables occupy the 16 bytes of Internal RAM from 20h through 2Fh. Thus, if you write
the value FFh to Internal RAM address 20h youve effectively set bits 00h through 07h.
That is to say that:
MOV 20h,#0FFh
is equivalent to:
SETB 00h
SETB 01h
SETB 02h
SETB 03h
SETB 04h
SETB 05h
SETB 06h
SETB 07h
As illustrated above, bit memory isnt really a new type of memory. Its really just a subset
of Internal RAM. But since the 8051 provides special instructions to access these 16 bytes
of memory on a bit by bit basis it is useful to think of it as a separate type of memory.
However, always keep in mind that it is just a subset of Internal RAM--and that operations
performed on Internal RAM can change the values of the bit variables.
Programming Tip: If your program does not use bit variables, you may use Internal
RAM locations 20h through 2Fh for your own use. But if you plan to use bit variables, be
very careful about using addresses from 20h through 2Fh as you may end up overwriting
the value of your bits!
Bit variables 00h through 7Fh are for user-defined functions in their programs. However,
bit variables 80h and above are actually used to access certain SFRs on a bit-by-bit basis.

For example, if output lines P0.0 through P0.7 are all clear (0) and you want to turn on the
P0.0 output line you may either execute:
MOV P0,#01h
or you may execute:
SETB 80h
Both these instructions accomplish the same thing. However, using the SETB command
will turn on the P0.0 line without effecting the status of any of the other P0 output lines.
The MOV command effectively turns off all the other output lines which, in some cases,
may not be acceptable.
Programming Tip: By default, the 8051 initializes the Stack Pointer (SP) to 07h when
the microcontroller is booted. This means that the stack will start at address 08h and
expand upwards. If you will be using the alternate register banks (banks 1, 2 or 3) you
must initialize the stack pointer to an address above the highest register bank you will be
using, otherwise the stack will overwrite your alternate register banks. Similarly, if you
will be using bit variables it is usually a good idea to initialize the stack pointer to some
value greater than 2Fh to guarantee that your bit variables are protected from the stack.
Special Function Register (SFR) Memory
Special Function Registers (SFRs) are areas of memory that control specific functionality
of the 8051 processor. For example, four SFRs permit access to the 8051s 32 input/output
lines. Another SFR allows a program to read or write to the 8051s serial port. Other SFRs
allow the user to set the serial baud rate, control and access timers, and configure the
8051s interrupt system.
When programming, SFRs have the illusion of being Internal Memory. For example, if
you want to write the value "1" to Internal RAM location 50 hex you would execute the
instruction:
MOV 50h,#01h
Similarly, if you want to write the value "1" to the 8051s serial port you would write this
value to the SBUF SFR, which has an SFR address of 99 Hex. Thus, to write the value "1"
to the serial port you would execute the instruction:
MOV 99h,#01h
As you can see, it appears that the SFR is part of Internal Memory. This is not the case.
When using this method of memory access (its called direct address), any instruction that
has an address of 00h through 7Fh refers to an Internal RAM memory address; any
instruction with an address of 80h through FFh refers to an SFR control register.
Programming Tip: SFRs are used to control the way the 8051 functions. Each SFR has a
specific purpose and format which will be discussed later. Not all addresses above 80h are
assigned to SFRs. However, this area may NOT be used as additional RAM memory even
if a given address has not been assigned to an SFR.

6. Explain Timers and counters


The 8051 comes equipped with two timers, both of which may be controlled, set, read, and
configured individually. The 8051 timers have three general functions: 1) Keeping time
and/or calculating the amount of time between events, 2) Counting the events themselves,
or 3) Generating baud rates for the serial port.
The three timer uses are distinct so we will talk about each of them separately. The first
two uses will be discussed in this chapter while the use of timers for baud rate generation
will be discussed in the chapter relating to serial ports.
How does a timer count?
How does a timer count? The answer to this question is very simple: A timer always
counts up. It doesnt matter whether the timer is being used as a timer, a counter, or a baud
rate generator: A timer is always incremented by the microcontroller.
Programming Tip: Some derivative chips actually allow the program to configure
whether the timers count up or down. However, since this option only exists on some
derivatives it is beyond the scope of this tutorial which is aimed at the standard 8051. It is
only mentioned here in the event that you absolutely need a timer to count backwards, you
will know that you may be able to find an 8051-compatible microcontroller that does it.
USING TIMERS TO MEASURE TIME
Obviously, one of the primary uses of timers is to measure time. We will discuss this use
of timers first and will subsequently discuss the use of timers to count events. When a
timer is used to measure time it is also called an "interval timer" since it is measuring the
time of the interval between two events.
How long does a timer take to count?
First, its worth mentioning that when a timer is in interval timer mode (as opposed to event
counter mode) and correctly configured, it will increment by 1 every machine cycle. As
you will recall from the previous chapter, a single machine cycle consists of 12 crystal
pulses. Thus a running timer will be incremented:
11,059,000 / 12 = 921,583
921,583 times per second. Unlike instructions--some of which require 1 machine cycle,
others 2, and others 4--the timers are consistent: They will always be incremented once per
machine cycle. Thus if a timer has counted from 0 to 50,000 you may calculate:
50,000 / 921,583 = .0542
.0542 seconds have passed. In plain English, about half of a tenth of a second, or onetwentieth of a second.

Obviously its not very useful to know .0542 seconds have passed. If you want to execute
an event once per second youd have to wait for the timer to count from 0 to 50,000 18.45
times. How can you wait "half of a time?" You cant. So we come to another important
calculation.
Lets say we want to know how many times the timer will be incremented in .05 seconds.
We can do simple multiplication:
.05 * 921,583 = 46,079.15.
This tells us that it will take .05 seconds (1/20th of a second) to count from 0 to 46,079.
Actually, it will take it .049999837 seconds--so were off by .000000163 seconds-however, thats close enough for government work. Consider that if you were building a
watch based on the 8051 and made the above assumption your watch would only gain
about one second every 2 months. Again, I think thats accurate enough for most
applications--I wish my watch only gained one second every two months!
Obviously, this is a little more useful. If you know it takes 1/20th of a second to count
from 0 to 46,079 and you want to execute some event every second you simply wait for
the timer to count from 0 to 46,079 twenty times; then you execute your event, reset the
timers, and wait for the timer to count up another 20 times. In this manner you will
effectively execute your event once per second, accurate to within thousandths of a
second.
Thus, we now have a system with which to measure time. All we need to review is how to
control the timers and initialize them to provide us with the information we need.
Timer SFRs
As mentioned before, the 8051 has two timers which each function essentially the same
way. One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs
(TMOD and TCON) which control the timers, and each timer also has two SFRs dedicated
solely to itself (TH0/TL0 and TH1/TL1).
Weve given SFRs names to make it easier to refer to them, but in reality an SFR has a
numeric address. It is often useful to know the numeric address that corresponds to an SFR
name. The SFRs relating to timers are:
SFR Name

Description

SFR Address

TH0

Timer 0 High Byte

8Ch

TL0

Timer 0 Low Byte

8Ah

TH1

Timer 1 High Byte

8Dh

TL1

Timer 1 Low Byte

8Bh

TCON

Timer Control

88h

TMOD

Timer Mode

89h

When you enter the name of an SFR into an assembler, it internally converts it to a
number. For example, the command:
MOV TH0,#25h
moves the value 25h into the TH0 SFR. However, since TH0 is the same as SFR address
8Ch this command is equivalent to:
MOV 8Ch,#25h
Now, back to the timers. First, lets talk about Timer 0.
Timer 0 has two SFRs dedicated exclusively to itself: TH0 and TL0. Without making
things too complicated to start off with, you may just think of this as the high and low byte
of the timer. That is to say, when Timer 0 has a value of 0, both TH0 and TL0 will contain
0. When Timer 0 has the value 1000, TH0 will hold the high byte of the value (3 decimal)
and TL0 will contain the low byte of the value (232 decimal). Reviewing low/high byte
notation, recall that you must multiply the high byte by 256 and add the low byte to
calculate the final value. That is to say:
TH0 * 256 + TL0 = 1000
3 * 256 + 232 = 1000
Timer 1 works the exact same way, but its SFRs are TH1 and TL1.
Since there are only two bytes devoted to the value of each timer it is apparent that the
maximum value a timer may have is 65,535. If a timer contains the value 65,535 and is
subsequently incremented, it will reset--or overflow--back to 0.
The TMOD SFR
Lets first talk about our first control SFR: TMOD (Timer Mode). The TMOD SFR is used
to control the mode of operation of both timers. Each bit of the SFR gives the
microcontroller specific information concerning how to run a timer. The high four bits
(bits 4 through 7) relate to Timer 1 whereas the low four bits (bits 0 through 3) perform
the exact same functions, but for timer 0.
The individual bits of TMOD have the following functions:
TMOD (89h) SFR
Bit
Name
7

Explanation of Function

Timer

GATE1

When this bit is set the timer will only run


when INT1 (P3.3) is high. When this bit
is clear the timer will run regardless of the
state of INT1.

C/T1

When this bit is set the timer will count


events on T1 (P3.5). When this bit is clear
the timer will be incremented every
machine cycle.

T1M1

Timer mode bit (see below)

T1M0

Timer mode bit (see below)

GATE0

When this bit is set the timer will only run


when INT0 (P3.2) is high. When this bit
is clear the timer will run regardless of the
state of INT0.

C/T0

When this bit is set the timer will count


events on T0 (P3.4). When this bit is clear
the timer will be incremented every
machine cycle.

T0M1

Timer mode bit (see below)

0
T0M0
Timer mode bit (see below)
0
As you can see in the above chart, four bits (two for each timer) are used to specify a
mode of operation. The modes of operation are:
Timer Mode
Description of Mode
TxM1
TxM0
0

13-bit Timer.

16-bit Timer

8-bit auto-reload

Split timer mode

13-bit Time Mode (mode 0)


Timer mode "0" is a 13-bit timer. This is a relic that was kept around in the 8051 to
maintain compatability with its predecesor, the 8048. Generally the 13-bit timer mode is
not used in new development.
When the timer is in 13-bit mode, TLx will count from 0 to 31. When TLx is incremented
from 31, it will "reset" to 0 and increment THx. Thus, effectively, only 13 bits of the two
timer bytes are being used: bits 0-4 of TLx and bits 0-7 of THx. This also means, in
essence, the timer can only contain 8192 values. If you set a 13-bit timer to 0, it will
overflow back to zero 8192 machine cycles later.
Again, there is very little reason to use this mode and it is only mentioned so you wont be
surprised if you ever end up analyzing archaeic code which has been passed down through
the generations (a generation in a programming shop is often on the order of about 3 or 4
months).
16-bit Time Mode (mode 1)
Timer mode "1" is a 16-bit timer. This is a very commonly used mode. It functions just
like 13-bit mode except that all 16 bits are used.
TLx is incremented from 0 to 255. When TLx is incremented from 255, it resets to 0 and
causes THx to be incremented by 1. Since this is a full 16-bit timer, the timer may contain
up to 65536 distinct values. If you set a 16-bit timer to 0, it will overflow back to 0 after
65,536 machine cycles.

8-bit Time Mode (mode 2)


Timer mode "2" is an 8-bit auto-reload mode. What is that, you may ask? Simple. When a
timer is in mode 2, THx holds the "reload value" and TLx is the timer itself. Thus, TLx
starts counting up. When TLx reaches 255 and is subsequently incremented, instead of
resetting to 0 (as in the case of modes 0 and 1), it will be reset to the value stored in THx.
For example, lets say TH0 holds the value FDh and TL0 holds the value FEh. If we were
to watch the values of TH0 and TL0 for a few machine cycles this is what wed see:
Machine Cycle

TH0 Value

TL0 Value

FDh

FEh

FDh

FFh

FDh

FDh

FDh

FEh

FDh

FFh

FDh

FDh

FDh

FEh

As you can see, the value of TH0 never changed. In fact, when you use mode 2 you almost
always set THx to a known value and TLx is the SFR that is constantly incremented.
Whats the benefit of auto-reload mode? Perhaps you want the timer to always have a value
from 200 to 255. If you use mode 0 or 1, youd have to check in code to see if the timer had
overflowed and, if so, reset the timer to 200. This takes precious instructions of execution
time to check the value and/or to reload it. When you use mode 2 the microcontroller takes
care of this for you. Once youve configured a timer in mode 2 you dont have to worry
about checking to see if the timer has overflowed nor do you have to worry about resetting
the value--the microcontroller hardware will do it all for you.
The auto-reload mode is very commonly used for establishing a baud rate which we will
talk more about in the Serial Communications chapter.
Split Timer Mode (mode 3)
Timer mode "3" is a split-timer mode. When Timer 0 is placed in mode 3, it essentially
becomes two separate 8-bit timers. That is to say, Timer 0 is TL0 and Timer 1 is TH0.
Both timers count from 0 to 255 and overflow back to 0. All the bits that are related to
Timer 1 will now be tied to TH0.
While Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be put into modes
0, 1 or 2 normally--however, you may not start or stop the real timer 1 since the bits that
do that are now linked to TH0. The real timer 1, in this case, will be incremented every
machine cycle no matter what.

The only real use I can see of using split timer mode is if you need to have two separate
timers and, additionally, a baud rate generator. In such case you can use the real Timer 1
as a baud rate generator and use TH0/TL0 as two separate timers.
The TCON SFR
Finally, theres one more SFR that controls the two timers and provides valuable
information about them. The TCON SFR has the following structure:
TCON (88h) SFR
Bit

Name

Bit
Address

Explanation of Function

Timer

TF1

8Fh

Timer 1 Overflow. This bit is set by the


microcontroller when Timer 1 overflows.

TR1

8Eh

Timer 1 Run. When this bit is set Timer


1 is turned on. When this bit is clear
Timer 1 is off.

TF0

8Dh

Timer 0 Overflow. This bit is set by the


microcontroller when Timer 0 overflows.

Timer 0 Run. When this bit is set Timer


0 is turned on. When this bit is clear
0
Timer 0 is off.
As you may notice, weve only defined 4 of the 8 bits. Thats because the other 4 bits of the
SFR dont have anything to do with timers--they have to do with Interrupts and they will be
discussed in the chapter that addresses interrupts.
4

TR0

8Ch

A new piece of information in this chart is the column "bit address." This is because this
SFR is "bit-addressable." What does this mean? It means if you want to set the bit TF1-which is the highest bit of TCON--you could execute the command:
MOV TCON, #80h
... or, since the SFR is bit-addressable, you could just execute the command:
SETB TF1
This has the benefit of setting the high bit of TCON without changing the value of any of
the other bits of the SFR. Usually when you start or stop a timer you dont want to modify
the other values in TCON, so you take advantage of the fact that the SFR is bitaddressable.
Initializing a Timer
Now that weve discussed the timer-related SFRs we are ready to write code that will
initialize the timer and start it running.

As youll recall, we first must decide what mode we want the timer to be in. In this case we
want a 16-bit timer that runs continuously; that is to say, it is not dependent on any
external pins.
We must first initialize the TMOD SFR. Since we are working with timer 0 we will be
using the lowest 4 bits of TMOD. The first two bits, GATE0 and C/T0 are both 0 since we
want the timer to be independent of the external pins. 16-bit mode is timer mode 1 so we
must clear T0M1 and set T0M0. Effectively, the only bit we want to turn on is bit 0 of
TMOD. Thus to initialize the timer we execute the instruction:
MOV TMOD,#01h
Timer 0 is now in 16-bit timer mode. However, the timer is not running. To start the timer
running we must set the TR0 bit We can do that by executing the instruction:
SETB TR0
Upon executing these two instructions timer 0 will immediately begin counting, being
incremented once every machine cycle (every 12 crystal pulses).
Reading the Timer
There are two common ways of reading the value of a 16-bit timer; which you use
depends on your specific application. You may either read the actual value of the timer as
a 16-bit number, or you may simply detect when the timer has overflowed.
Reading the value of a Timer
If your timer is in an 8-bit mode--that is, either 8-bit AutoReload mode or in split timer
mode--then reading the value of the timer is simple. You simply read the 1-byte value of
the timer and youre done.
However, if youre dealing with a 13-bit or 16-bit timer the chore is a little more
complicated. Consider what would happen if you read the low byte of the timer as 255,
then read the high byte of the timer as 15. In this case, what actually happened was that the
timer value was 14/255 (high byte 14, low byte 255) but you read 15/255. Why? Because
you read the low byte as 255. But when you executed the next instruction a small amount
of time passed--but enough for the timer to increment again at which time the value rolled
over from 14/255 to 15/0. But in the process youve read the timer as being 15/255.
Obviously theres a problem there.
The solution? Its not too tricky, really. You read the high byte of the timer, then read the
low byte, then read the high byte again. If the high byte read the second time is not the
same as the high byte read the first time you repeat the cycle. In code, this would appear
as:
REPEAT:

MOV A,TH0
MOV R0,TL0
CJNE A,TH0,REPEAT

...
In this case, we load the accumulator with the high byte of Timer 0. We then load R0 with
the low byte of Timer 0. Finally, we check to see if the high byte we read out of Timer 0-which is now stored in the Accumulator--is the same as the current Timer 0 high byte. If it
isnt it means weve just "rolled over" and must reread the timers value--which we do by
going back to REPEAT. When the loop exits we will have the low byte of the timer in R0
and the high byte in the Accumulator.
Another much simpler alternative is to simply turn off the timer run bit (i.e. CLR TR0),
read the timer value, and then turn on the timer run bit (i.e. SETB TR0). In that case, the
timer isnt running so no special tricks are necessary. Of course, this implies that your timer
will be stopped for a few machine cycles. Whether or not this is tolerable depends on your
specific application.
Detecting Timer Overflow
Often it is necessary to just know that the timer has reset to 0. That is to say, you are not
particularly interest in the value of the timer but rather you are interested in knowing when
the timer has overflowed back to 0.
Whenever a timer overflows from its highest value back to 0, the microcontroller
automatically sets the TFx bit in the TCON register. This is useful since rather than
checking the exact value of the timer you can just check if the TFx bit is set. If TF0 is set
it means that timer 0 has overflowed; if TF1 is set it means that timer 1 has overflowed.
We can use this approach to cause the program to execute a fixed delay. As youll recall,
we calculated earlier that it takes the 8051 1/20th of a second to count from 0 to 46,079.
However, the TFx flag is set when the timer overflows back to 0. Thus, if we want to use
the TFx flag to indicate when 1/20th of a second has passed we must set the timer initially
to 65536 less 46079, or 19,457. If we set the timer to 19,457, 1/20th of a second later the
timer will overflow. Thus we come up with the following code to execute a pause of
1/20th of a second:
MOV TH0,#76;High byte of 19,457 (76 * 256 = 19,456)
MOV TL0,#01;Low byte of 19,457 (19,456 + 1 = 19,457)
MOV TMOD,#01;Put Timer 0 in 16-bit mode
SETB TR0;Make Timer 0 start counting
JNB TF0,$;If TF0 is not set, jump back to this same instruction
In the above code the first two lines initialize the Timer 0 starting value to 19,457. The
next two instructions configure timer 0 and turn it on. Finally, the last instruction JNB
TF0,$, reads "Jump, if TF0 is not set, back to this same instruction." The "$" operand
means, in most assemblers, the address of the current instruction. Thus as long as the timer
has not overflowed and the TF0 bit has not been set the program will keep executing this
same instruction. After 1/20th of a second timer 0 will overflow, set the TF0 bit, and
program execution will then break out of the loop.
Timing the length of events
The 8051 provides another cool toy that can be used to time the length of events.

For example, let's say we're trying to save electricity in the office and we're interested in
how long a light is turned on each day. When the light is turned on, we want to measure
time. When the light is turned off we don't. One option would be to connect the
lightswitch to one of the pins, constantly read the pin, and turn the timer on or off based on
the state of that pin. While this would work fine, the 8051 provides us with an easier
method of accomplishing this.
Looking again at the TMOD SFR, there is a bit called GATE0. So far we've always
cleared this bit because we wanted the timer to run regardless of the state of the external
pins. However, now it would be nice if an external pin could control whether the timer
was running or not. It can. All we need to do is connect the lightswitch to pin INT0 (P3.2)
on the 8051 and set the bit GATE0. When GATE0 is set Timer 0 will only run if P3.2 is
high. When P3.2 is low (i.e., the lightswitch is off) the timer will automatically be stopped.
Thus, with no control code whatsoever, the external pin P3.2 can control whether or not
our timer is running or not.
USING TIMERS AS EVENT COUNTERS
We've discussed how a timer can be used for the obvious purpose of keeping track of time.
However, the 8051 also allows us to use the timers to count events.
How can this be useful? Let's say you had a sensor placed across a road that would send a
pulse every time a car passed over it. This could be used to determine the volume of traffic
on the road. We could attach this sensor to one of the 8051's I/O lines and constantly
monitor it, detecting when it pulsed high and then incrementing our counter when it went
back to a low state. This is not terribly difficult, but requires some code. Let's say we
hooked the sensor to P1.0; the code to count cars passing would look something like this:
JNB P1.0,$
JB P1.0,$

;If a car hasn't raised the signal, keep waiting


;The line is high which means the car is on the sensor right
now

INC
;The car has passed completely, so we count it
COUNTER
As you can see, it's only three lines of code. But what if you need to be doing other
processing at the same time? You can't be stuck in the JNB P1.0,$ loop waiting for a car to
pass if you need to be doing other things. Of course, there are ways to get around even this
limitation but the code quickly becomes big, complex, and ugly.
Luckily, since the 8051 provides us with a way to use the timers to count events we don't
have to bother with it. It is actually painfully easy. We only have to configure one
additional bit.
Let's say we want to use Timer 0 to count the number of cars that pass. If you look back to
the bit table for the TCON SFR you will there is a bit called "C/T0"--it's bit 2 (TCON.2).
Reviewing the explanation of the bit we see that if the bit is clear then timer 0 will be
incremented every machine cycle. This is what we've already used to measure time.
However, if we set C/T0 timer 0 will monitor the P3.4 line. Instead of being incremented
every machine cycle, timer 0 will count events on the P3.4 line. So in our case we simply

connect our sensor to P3.4 and let the 8051 do the work. Then, when we want to know
how many cars have passed, we just read the value of timer 0--the value of timer 0 will be
the number of cars that have passed.
So what exactly is an event? What does timer 0 actually "count?" Speaking at the
electrical level, the 8051 counts 1-0 transitions on the P3.4 line. This means that when a
car first runs over our sensor it will raise the input to a high ("1") condition. At that point
the 8051 will not count anything since this is a 0-1 transition. However, when the car has
passed the sensor will fall back to a low ("0") state. This is a 1-0 transition and at that
instant the counter will be incremented by 1.
It is important to note that the 8051 checks the P3.4 line each instruction cycle (12 clock
cycles). This means that if P3.4 is low, goes high, and goes back low in 6 clock cycles it
will probably not be detected by the 8051. This also means the 8051 event counter is only
capable of counting events that occur at a maximum of 1/24th the rate of the crystal
frequency. That is to say, if the crystal frequency is 12.000 Mhz it can count a maximum
of 500,000 events per second (12.000 Mhz * 1/24 = 500,000). If the event being counted
occurs more than 500,000 times per second it will not be able to be accurately counted by
the 8051.

7.Explain serial communication of 8051


The 8051 comes equipped with two timers, both of which may be controlled, set, read, and
configured individually. The 8051 timers have three general functions: 1) Keeping time
and/or calculating the amount of time between events, 2) Counting the events themselves,
or 3) Generating baud rates for the serial port.
The three timer uses are distinct so we will talk about each of them separately. The first
two uses will be discussed in this chapter while the use of timers for baud rate generation
will be discussed in the chapter relating to serial ports.
How does a timer count?
How does a timer count? The answer to this question is very simple: A timer always
counts up. It doesnt matter whether the timer is being used as a timer, a counter, or a baud
rate generator: A timer is always incremented by the microcontroller.
Programming Tip: Some derivative chips actually allow the program to configure
whether the timers count up or down. However, since this option only exists on some
derivatives it is beyond the scope of this tutorial which is aimed at the standard 8051. It is
only mentioned here in the event that you absolutely need a timer to count backwards, you
will know that you may be able to find an 8051-compatible microcontroller that does it.
USING TIMERS TO MEASURE TIME
Obviously, one of the primary uses of timers is to measure time. We will discuss this use
of timers first and will subsequently discuss the use of timers to count events. When a

timer is used to measure time it is also called an "interval timer" since it is measuring the
time of the interval between two events.
How long does a timer take to count?
First, its worth mentioning that when a timer is in interval timer mode (as opposed to event
counter mode) and correctly configured, it will increment by 1 every machine cycle. As
you will recall from the previous chapter, a single machine cycle consists of 12 crystal
pulses. Thus a running timer will be incremented:
11,059,000 / 12 = 921,583
921,583 times per second. Unlike instructions--some of which require 1 machine cycle,
others 2, and others 4--the timers are consistent: They will always be incremented once per
machine cycle. Thus if a timer has counted from 0 to 50,000 you may calculate:
50,000 / 921,583 = .0542
.0542 seconds have passed. In plain English, about half of a tenth of a second, or onetwentieth of a second.
Obviously its not very useful to know .0542 seconds have passed. If you want to execute
an event once per second youd have to wait for the timer to count from 0 to 50,000 18.45
times. How can you wait "half of a time?" You cant. So we come to another important
calculation.
Lets say we want to know how many times the timer will be incremented in .05 seconds.
We can do simple multiplication:
.05 * 921,583 = 46,079.15.
This tells us that it will take .05 seconds (1/20th of a second) to count from 0 to 46,079.
Actually, it will take it .049999837 seconds--so were off by .000000163 seconds-however, thats close enough for government work. Consider that if you were building a
watch based on the 8051 and made the above assumption your watch would only gain
about one second every 2 months. Again, I think thats accurate enough for most
applications--I wish my watch only gained one second every two months!
Obviously, this is a little more useful. If you know it takes 1/20th of a second to count
from 0 to 46,079 and you want to execute some event every second you simply wait for
the timer to count from 0 to 46,079 twenty times; then you execute your event, reset the
timers, and wait for the timer to count up another 20 times. In this manner you will
effectively execute your event once per second, accurate to within thousandths of a
second.
Thus, we now have a system with which to measure time. All we need to review is how to
control the timers and initialize them to provide us with the information we need.
Timer SFRs

As mentioned before, the 8051 has two timers which each function essentially the same
way. One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs
(TMOD and TCON) which control the timers, and each timer also has two SFRs dedicated
solely to itself (TH0/TL0 and TH1/TL1).
Weve given SFRs names to make it easier to refer to them, but in reality an SFR has a
numeric address. It is often useful to know the numeric address that corresponds to an SFR
name. The SFRs relating to timers are:
SFR Name

Description

SFR Address

TH0

Timer 0 High Byte

8Ch

TL0

Timer 0 Low Byte

8Ah

TH1

Timer 1 High Byte

8Dh

TL1

Timer 1 Low Byte

8Bh

TCON

Timer Control

88h

TMOD

Timer Mode

89h

When you enter the name of an SFR into an assembler, it internally converts it to a
number. For example, the command:
MOV TH0,#25h
moves the value 25h into the TH0 SFR. However, since TH0 is the same as SFR address
8Ch this command is equivalent to:
MOV 8Ch,#25h
Now, back to the timers. First, lets talk about Timer 0.
Timer 0 has two SFRs dedicated exclusively to itself: TH0 and TL0. Without making
things too complicated to start off with, you may just think of this as the high and low byte
of the timer. That is to say, when Timer 0 has a value of 0, both TH0 and TL0 will contain
0. When Timer 0 has the value 1000, TH0 will hold the high byte of the value (3 decimal)
and TL0 will contain the low byte of the value (232 decimal). Reviewing low/high byte
notation, recall that you must multiply the high byte by 256 and add the low byte to
calculate the final value. That is to say:
TH0 * 256 + TL0 = 1000
3 * 256 + 232 = 1000
Timer 1 works the exact same way, but its SFRs are TH1 and TL1.
Since there are only two bytes devoted to the value of each timer it is apparent that the
maximum value a timer may have is 65,535. If a timer contains the value 65,535 and is
subsequently incremented, it will reset--or overflow--back to 0.
The TMOD SFR

Lets first talk about our first control SFR: TMOD (Timer Mode). The TMOD SFR is used
to control the mode of operation of both timers. Each bit of the SFR gives the
microcontroller specific information concerning how to run a timer. The high four bits
(bits 4 through 7) relate to Timer 1 whereas the low four bits (bits 0 through 3) perform
the exact same functions, but for timer 0.
The individual bits of TMOD have the following functions:
TMOD (89h) SFR
Bit
Name

Explanation of Function

Timer

GATE1

When this bit is set the timer will only run


when INT1 (P3.3) is high. When this bit
is clear the timer will run regardless of the
state of INT1.

C/T1

When this bit is set the timer will count


events on T1 (P3.5). When this bit is clear
the timer will be incremented every
machine cycle.

T1M1

Timer mode bit (see below)

T1M0

Timer mode bit (see below)

GATE0

When this bit is set the timer will only run


when INT0 (P3.2) is high. When this bit
is clear the timer will run regardless of the
state of INT0.

C/T0

When this bit is set the timer will count


events on T0 (P3.4). When this bit is clear
the timer will be incremented every
machine cycle.

T0M1

Timer mode bit (see below)

0
T0M0
Timer mode bit (see below)
0
As you can see in the above chart, four bits (two for each timer) are used to specify a
mode of operation. The modes of operation are:
Timer Mode
Description of Mode
TxM1
TxM0
0

13-bit Timer.

16-bit Timer

8-bit auto-reload

Split timer mode

13-bit Time Mode (mode 0)


Timer mode "0" is a 13-bit timer. This is a relic that was kept around in the 8051 to
maintain compatability with its predecesor, the 8048. Generally the 13-bit timer mode is
not used in new development.

When the timer is in 13-bit mode, TLx will count from 0 to 31. When TLx is incremented
from 31, it will "reset" to 0 and increment THx. Thus, effectively, only 13 bits of the two
timer bytes are being used: bits 0-4 of TLx and bits 0-7 of THx. This also means, in
essence, the timer can only contain 8192 values. If you set a 13-bit timer to 0, it will
overflow back to zero 8192 machine cycles later.
Again, there is very little reason to use this mode and it is only mentioned so you wont be
surprised if you ever end up analyzing archaeic code which has been passed down through
the generations (a generation in a programming shop is often on the order of about 3 or 4
months).
16-bit Time Mode (mode 1)
Timer mode "1" is a 16-bit timer. This is a very commonly used mode. It functions just
like 13-bit mode except that all 16 bits are used.
TLx is incremented from 0 to 255. When TLx is incremented from 255, it resets to 0 and
causes THx to be incremented by 1. Since this is a full 16-bit timer, the timer may contain
up to 65536 distinct values. If you set a 16-bit timer to 0, it will overflow back to 0 after
65,536 machine cycles.
8-bit Time Mode (mode 2)
Timer mode "2" is an 8-bit auto-reload mode. What is that, you may ask? Simple. When a
timer is in mode 2, THx holds the "reload value" and TLx is the timer itself. Thus, TLx
starts counting up. When TLx reaches 255 and is subsequently incremented, instead of
resetting to 0 (as in the case of modes 0 and 1), it will be reset to the value stored in THx.
For example, lets say TH0 holds the value FDh and TL0 holds the value FEh. If we were
to watch the values of TH0 and TL0 for a few machine cycles this is what wed see:
Machine Cycle

TH0 Value

TL0 Value

FDh

FEh

FDh

FFh

FDh

FDh

FDh

FEh

FDh

FFh

FDh

FDh

FDh

FEh

As you can see, the value of TH0 never changed. In fact, when you use mode 2 you almost
always set THx to a known value and TLx is the SFR that is constantly incremented.
Whats the benefit of auto-reload mode? Perhaps you want the timer to always have a value
from 200 to 255. If you use mode 0 or 1, youd have to check in code to see if the timer had
overflowed and, if so, reset the timer to 200. This takes precious instructions of execution
time to check the value and/or to reload it. When you use mode 2 the microcontroller takes

care of this for you. Once youve configured a timer in mode 2 you dont have to worry
about checking to see if the timer has overflowed nor do you have to worry about resetting
the value--the microcontroller hardware will do it all for you.
The auto-reload mode is very commonly used for establishing a baud rate which we will
talk more about in the Serial Communications chapter.
Split Timer Mode (mode 3)
Timer mode "3" is a split-timer mode. When Timer 0 is placed in mode 3, it essentially
becomes two separate 8-bit timers. That is to say, Timer 0 is TL0 and Timer 1 is TH0.
Both timers count from 0 to 255 and overflow back to 0. All the bits that are related to
Timer 1 will now be tied to TH0.
While Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be put into modes
0, 1 or 2 normally--however, you may not start or stop the real timer 1 since the bits that
do that are now linked to TH0. The real timer 1, in this case, will be incremented every
machine cycle no matter what.
The only real use I can see of using split timer mode is if you need to have two separate
timers and, additionally, a baud rate generator. In such case you can use the real Timer 1
as a baud rate generator and use TH0/TL0 as two separate timers.
The TCON SFR
Finally, theres one more SFR that controls the two timers and provides valuable
information about them. The TCON SFR has the following structure:
TCON (88h) SFR
Bit

Name

Bit
Address

Explanation of Function

Timer

TF1

8Fh

Timer 1 Overflow. This bit is set by the


microcontroller when Timer 1 overflows.

TR1

8Eh

Timer 1 Run. When this bit is set Timer


1 is turned on. When this bit is clear
Timer 1 is off.

TF0

8Dh

Timer 0 Overflow. This bit is set by the


microcontroller when Timer 0 overflows.

Timer 0 Run. When this bit is set Timer


0 is turned on. When this bit is clear
0
Timer 0 is off.
As you may notice, weve only defined 4 of the 8 bits. Thats because the other 4 bits of the
SFR dont have anything to do with timers--they have to do with Interrupts and they will be
discussed in the chapter that addresses interrupts.
4

TR0

8Ch

A new piece of information in this chart is the column "bit address." This is because this
SFR is "bit-addressable." What does this mean? It means if you want to set the bit TF1-which is the highest bit of TCON--you could execute the command:

MOV TCON, #80h


... or, since the SFR is bit-addressable, you could just execute the command:
SETB TF1
This has the benefit of setting the high bit of TCON without changing the value of any of
the other bits of the SFR. Usually when you start or stop a timer you dont want to modify
the other values in TCON, so you take advantage of the fact that the SFR is bitaddressable.
Initializing a Timer
Now that weve discussed the timer-related SFRs we are ready to write code that will
initialize the timer and start it running.
As youll recall, we first must decide what mode we want the timer to be in. In this case we
want a 16-bit timer that runs continuously; that is to say, it is not dependent on any
external pins.
We must first initialize the TMOD SFR. Since we are working with timer 0 we will be
using the lowest 4 bits of TMOD. The first two bits, GATE0 and C/T0 are both 0 since we
want the timer to be independent of the external pins. 16-bit mode is timer mode 1 so we
must clear T0M1 and set T0M0. Effectively, the only bit we want to turn on is bit 0 of
TMOD. Thus to initialize the timer we execute the instruction:
MOV TMOD,#01h
Timer 0 is now in 16-bit timer mode. However, the timer is not running. To start the timer
running we must set the TR0 bit We can do that by executing the instruction:
SETB TR0
Upon executing these two instructions timer 0 will immediately begin counting, being
incremented once every machine cycle (every 12 crystal pulses).
Reading the Timer
There are two common ways of reading the value of a 16-bit timer; which you use
depends on your specific application. You may either read the actual value of the timer as
a 16-bit number, or you may simply detect when the timer has overflowed.
Reading the value of a Timer
If your timer is in an 8-bit mode--that is, either 8-bit AutoReload mode or in split timer
mode--then reading the value of the timer is simple. You simply read the 1-byte value of
the timer and youre done.
However, if youre dealing with a 13-bit or 16-bit timer the chore is a little more
complicated. Consider what would happen if you read the low byte of the timer as 255,

then read the high byte of the timer as 15. In this case, what actually happened was that the
timer value was 14/255 (high byte 14, low byte 255) but you read 15/255. Why? Because
you read the low byte as 255. But when you executed the next instruction a small amount
of time passed--but enough for the timer to increment again at which time the value rolled
over from 14/255 to 15/0. But in the process youve read the timer as being 15/255.
Obviously theres a problem there.
The solution? Its not too tricky, really. You read the high byte of the timer, then read the
low byte, then read the high byte again. If the high byte read the second time is not the
same as the high byte read the first time you repeat the cycle. In code, this would appear
as:
REPEAT:

MOV A,TH0
MOV R0,TL0
CJNE A,TH0,REPEAT
...
In this case, we load the accumulator with the high byte of Timer 0. We then load R0 with
the low byte of Timer 0. Finally, we check to see if the high byte we read out of Timer 0-which is now stored in the Accumulator--is the same as the current Timer 0 high byte. If it
isnt it means weve just "rolled over" and must reread the timers value--which we do by
going back to REPEAT. When the loop exits we will have the low byte of the timer in R0
and the high byte in the Accumulator.
Another much simpler alternative is to simply turn off the timer run bit (i.e. CLR TR0),
read the timer value, and then turn on the timer run bit (i.e. SETB TR0). In that case, the
timer isnt running so no special tricks are necessary. Of course, this implies that your timer
will be stopped for a few machine cycles. Whether or not this is tolerable depends on your
specific application.
Detecting Timer Overflow
Often it is necessary to just know that the timer has reset to 0. That is to say, you are not
particularly interest in the value of the timer but rather you are interested in knowing when
the timer has overflowed back to 0.
Whenever a timer overflows from its highest value back to 0, the microcontroller
automatically sets the TFx bit in the TCON register. This is useful since rather than
checking the exact value of the timer you can just check if the TFx bit is set. If TF0 is set
it means that timer 0 has overflowed; if TF1 is set it means that timer 1 has overflowed.
We can use this approach to cause the program to execute a fixed delay. As youll recall,
we calculated earlier that it takes the 8051 1/20th of a second to count from 0 to 46,079.
However, the TFx flag is set when the timer overflows back to 0. Thus, if we want to use
the TFx flag to indicate when 1/20th of a second has passed we must set the timer initially
to 65536 less 46079, or 19,457. If we set the timer to 19,457, 1/20th of a second later the
timer will overflow. Thus we come up with the following code to execute a pause of
1/20th of a second:

MOV TH0,#76;High byte of 19,457 (76 * 256 = 19,456)


MOV TL0,#01;Low byte of 19,457 (19,456 + 1 = 19,457)
MOV TMOD,#01;Put Timer 0 in 16-bit mode
SETB TR0;Make Timer 0 start counting
JNB TF0,$;If TF0 is not set, jump back to this same instruction
In the above code the first two lines initialize the Timer 0 starting value to 19,457. The
next two instructions configure timer 0 and turn it on. Finally, the last instruction JNB
TF0,$, reads "Jump, if TF0 is not set, back to this same instruction." The "$" operand
means, in most assemblers, the address of the current instruction. Thus as long as the timer
has not overflowed and the TF0 bit has not been set the program will keep executing this
same instruction. After 1/20th of a second timer 0 will overflow, set the TF0 bit, and
program execution will then break out of the loop.
Timing the length of events
The 8051 provides another cool toy that can be used to time the length of events.
For example, let's say we're trying to save electricity in the office and we're interested in
how long a light is turned on each day. When the light is turned on, we want to measure
time. When the light is turned off we don't. One option would be to connect the
lightswitch to one of the pins, constantly read the pin, and turn the timer on or off based on
the state of that pin. While this would work fine, the 8051 provides us with an easier
method of accomplishing this.
Looking again at the TMOD SFR, there is a bit called GATE0. So far we've always
cleared this bit because we wanted the timer to run regardless of the state of the external
pins. However, now it would be nice if an external pin could control whether the timer
was running or not. It can. All we need to do is connect the lightswitch to pin INT0 (P3.2)
on the 8051 and set the bit GATE0. When GATE0 is set Timer 0 will only run if P3.2 is
high. When P3.2 is low (i.e., the lightswitch is off) the timer will automatically be stopped.
Thus, with no control code whatsoever, the external pin P3.2 can control whether or not
our timer is running or not.
USING TIMERS AS EVENT COUNTERS
We've discussed how a timer can be used for the obvious purpose of keeping track of time.
However, the 8051 also allows us to use the timers to count events.
How can this be useful? Let's say you had a sensor placed across a road that would send a
pulse every time a car passed over it. This could be used to determine the volume of traffic
on the road. We could attach this sensor to one of the 8051's I/O lines and constantly
monitor it, detecting when it pulsed high and then incrementing our counter when it went
back to a low state. This is not terribly difficult, but requires some code. Let's say we
hooked the sensor to P1.0; the code to count cars passing would look something like this:
JNB P1.0,$
JB P1.0,$

;If a car hasn't raised the signal, keep waiting


;The line is high which means the car is on the sensor right
now

INC
;The car has passed completely, so we count it
COUNTER
As you can see, it's only three lines of code. But what if you need to be doing other
processing at the same time? You can't be stuck in the JNB P1.0,$ loop waiting for a car to
pass if you need to be doing other things. Of course, there are ways to get around even this
limitation but the code quickly becomes big, complex, and ugly.
Luckily, since the 8051 provides us with a way to use the timers to count events we don't
have to bother with it. It is actually painfully easy. We only have to configure one
additional bit.
Let's say we want to use Timer 0 to count the number of cars that pass. If you look back to
the bit table for the TCON SFR you will there is a bit called "C/T0"--it's bit 2 (TCON.2).
Reviewing the explanation of the bit we see that if the bit is clear then timer 0 will be
incremented every machine cycle. This is what we've already used to measure time.
However, if we set C/T0 timer 0 will monitor the P3.4 line. Instead of being incremented
every machine cycle, timer 0 will count events on the P3.4 line. So in our case we simply
connect our sensor to P3.4 and let the 8051 do the work. Then, when we want to know
how many cars have passed, we just read the value of timer 0--the value of timer 0 will be
the number of cars that have passed.
So what exactly is an event? What does timer 0 actually "count?" Speaking at the
electrical level, the 8051 counts 1-0 transitions on the P3.4 line. This means that when a
car first runs over our sensor it will raise the input to a high ("1") condition. At that point
the 8051 will not count anything since this is a 0-1 transition. However, when the car has
passed the sensor will fall back to a low ("0") state. This is a 1-0 transition and at that
instant the counter will be incremented by 1.
It is important to note that the 8051 checks the P3.4 line each instruction cycle (12 clock
cycles). This means that if P3.4 is low, goes high, and goes back low in 6 clock cycles it
will probably not be detected by the 8051. This also means the 8051 event counter is only
capable of counting events that occur at a maximum of 1/24th the rate of the crystal
frequency. That is to say, if the crystal frequency is 12.000 Mhz it can count a maximum
of 500,000 events per second (12.000 Mhz * 1/24 = 500,000). If the event being counted
occurs more than 500,000 times per second it will not be able to be accurately counted by
the 8051.
One of the 8051s many powerful features is its integrated UART, otherwise known as a
serial port. The fact that the 8051 has an integrated serial port means that you may very
easily read and write values to the serial port. If it were not for the integrated serial port,
writing a byte to a serial line would be a rather tedious process requring turning on and off
one of the I/O lines in rapid succession to properly "clock out" each individual bit,
including start bits, stop bits, and parity bits.
However, we do not have to do this. Instead, we simply need to configure the serial ports
operation mode and baud rate. Once configured, all we have to do is write to an SFR to
write a value to the serial port or read the same SFR to read a value from the serial port.
The 8051 will automatically let us know when it has finished sending the character we
wrote and will also let us know whenever it has received a byte so that we can process it.

We do not have to worry about transmission at the bit level--which saves us quite a bit of
coding and processing time.
Setting the Serial Port Mode
The first thing we must do when using the 8051s integrated serial port is, obviously,
configure it. This lets us tell the 8051 how many data bits we want, the baud rate we will
be using, and how the baud rate will be determined.
First, lets present the "Serial Control" (SCON) SFR and define what each bit of the SFR
represents:
Bit

Name

Bit
Addres

SM0

9Fh

Serial port mode bit 0

SM1

9Eh

Serial port mode bit 1.

SM2

9Dh

Mutliprocessor Communications Enable (explained


later)

REN

9Ch

Receiver Enable. This bit must be set in order to


receive characters.

TB8

9Bh

Transmit bit 8. The 9th bit to transmit in mode 2


and 3.

RB8

9Ah

Receive bit 8. The 9th bit received in mode 2 and


3.

TI

99h

Transmit Flag. Set when a byte has been


completely transmitted.

RI

98h

Receive Flag. Set when a byte has been completely


received.

Explanation of Function

Additionally, it is necessary to define the function of SM0 and SM1 by an additional table:
SM0

SM1

Serial Mode

Explanation

Baud Rate

8-bit Shift Register

Oscillator / 12

8-bit UART

Set by Timer 1 (*)

9-bit UART

Oscillator / 64 (*)

9-bit UART

Set by Timer 1 (*)

(*) Note: The baud rate indicated in this table is doubled if PCON.7 (SMOD) is set.
The SCON SFR allows us to configure the Serial Port. Thus, well go through each bit and
review its function.
The first four bits (bits 4 through 7) are configuration bits.

Bits SM0 and SM1 let us set the serial mode to a value between 0 and 3, inclusive. The
four modes are defined in the chart immediately above. As you can see, selecting the
Serial Mode selects the mode of operation (8-bit/9-bit, UART or Shift Register) and also
determines how the baud rate will be calculated. In modes 0 and 2 the baud rate is fixed
based on the oscillators frequency. In modes 1 and 3 the baud rate is variable based on
how often Timer 1 overflows. Well talk more about the various Serial Modes in a moment.
The next bit, SM2, is a flag for "Multiprocessor communication." Generally, whenever a
byte has been received the 8051 will set the "RI" (Receive Interrupt) flag. This lets the
program know that a byte has been received and that it needs to be processed. However,
when SM2 is set the "RI" flag will only be triggered if the 9th bit received was a "1". That
is to say, if SM2 is set and a byte is received whose 9th bit is clear, the RI flag will never
be set. This can be useful in certain advanced serial applications. For now it is safe to say
that you will almost always want to clear this bit so that the flag is set upon reception
of any character.
The next bit, REN, is "Receiver Enable." This bit is very straightforward: If you want to
receive data via the serial port, set this bit. You will almost always want to set this bit.
The last four bits (bits 0 through 3) are operational bits. They are used when actually
sending and receiving data--they are not used to configure the serial port.
The TB8 bit is used in modes 2 and 3. In modes 2 and 3, a total of nine data bits are
transmitted. The first 8 data bits are the 8 bits of the main value, and the ninth bit is taken
from TB8. If TB8 is set and a value is written to the serial port, the datas bits will be
written to the serial line followed by a "set" ninth bit. If TB8 is clear the ninth bit will be
"clear."
The RB8 also operates in modes 2 and 3 and functions essentially the same way as TB8,
but on the reception side. When a byte is received in modes 2 or 3, a total of nine bits are
received. In this case, the first eight bits received are the data of the serial byte received
and the value of the ninth bit received will be placed in RB8.
TI means "Transmit Interrupt." When a program writes a value to the serial port, a certain
amount of time will pass before the individual bits of the byte are "clocked out" the serial
port. If the program were to write another byte to the serial port before the first byte was
completely output, the data being sent would be garbled. Thus, the 8051 lets the program
know that it has "clocked out" the last byte by setting the TI bit. When the TI bit is set, the
program may assume that the serial port is "free" and ready to send the next byte.
Finally, the RI bit means "Receive Interrupt." It funcions similarly to the "TI" bit, but it
indicates that a byte has been received. That is to say, whenever the 8051 has received a
complete byte it will trigger the RI bit to let the program know that it needs to read the
value quickly, before another byte is read.
Setting the Serial Port Baud Rate
Once the Serial Port Mode has been configured, as explained above, the program must
configure the serial ports baud rate. This only applies to Serial Port modes 1 and 3. The
Baud Rate is determined based on the oscillators frequency when in mode 0 and 2. In

mode 0, the baud rate is always the oscillator frequency divided by 12. This means if
youre crystal is 11.059Mhz, mode 0 baud rate will always be 921,583 baud. In mode 2 the
baud rate is always the oscillator frequency divided by 64, so a 11.059Mhz crystal speed
will yield a baud rate of 172,797.
In modes 1 and 3, the baud rate is determined by how frequently timer 1 overflows. The
more frequently timer 1 overflows, the higher the baud rate. There are many ways one can
cause timer 1 to overflow at a rate that determines a baud rate, but the most common
method is to put timer 1 in 8-bit auto-reload mode (timer mode 2) and set a reload value
(TH1) that causes Timer 1 to overflow at a frequency appropriate to generate a baud rate.
To determine the value that must be placed in TH1 to generate a given baud rate, we may
use the following equation (assuming PCON.7 is clear).
TH1 = 256 - ((Crystal / 384) / Baud)
If PCON.7 is set then the baud rate is effectively doubled, thus the equation becomes:
TH1 = 256 - ((Crystal / 192) / Baud)
For example, if we have an 11.059Mhz crystal and we want to configure the serial port to
19,200 baud we try plugging it in the first equation:
TH1 = 256 - ((Crystal / 384) / Baud)
TH1 = 256 - ((11059000 / 384) / 19200 )
TH1 = 256 - ((28,799) / 19200)
TH1 = 256 - 1.5 = 254.5
As you can see, to obtain 19,200 baud on a 11.059Mhz crystal wed have to set TH1 to
254.5. If we set it to 254 we will have achieved 14,400 baud and if we set it to 255 we will
have achieved 28,800 baud. Thus were stuck...
But not quite... to achieve 19,200 baud we simply need to set PCON.7 (SMOD). When we
do this we double the baud rate and utilize the second equation mentioned above. Thus we
have:
TH1 = 256 - ((Crystal / 192) / Baud)
TH1 = 256 - ((11059000 / 192) / 19200)
TH1 = 256 - ((57699) / 19200)
TH1 = 256 - 3 = 253
Here we are able to calculate a nice, even TH1 value. Therefore, to obtain 19,200 baud
with an 11.059MHz crystal we must:
1. Configure Serial Port mode 1 or 3.
2. Configure Timer 1 to timer mode 2 (8-bit auto-reload).
3. Set TH1 to 253 to reflect the correct frequency for 19,200 baud.
4. Set PCON.7 (SMOD) to double the baud rate.
Writing to the Serial Port
Once the Serial Port has been propertly configured as explained above, the serial port is
ready to be used to send data and receive data. If you thought that configuring the serial
port was simple, using the serial port will be a breeze.
To write a byte to the serial port one must simply write the value to the SBUF (99h) SFR.
For example, if you wanted to send the letter "A" to the serial port, it could be
accomplished as easily as:

MOV SBUF,#A
Upon execution of the above instruction the 8051 will begin transmitting the character via
the serial port. Obviously transmission is not instantaneous--it takes a measureable amount
of time to transmit. And since the 8051 does not have a serial output buffer we need to be
sure that a character is completely transmitted before we try to transmit the next character.
The 8051 lets us know when it is done transmitting a character by setting the TI bit in
SCON. When this bit is set we know that the last character has been transmitted and that
we may send the next character, if any. Consider the following code segment:
CLR TI ;Be sure the bit is initially clear
MOV SBUF,#A ;Send the letter A to the serial port
JNB TI,$ ;Pause until the TI bit is set.
The above three instructions will successfully transmit a character and wait for the TI bit
to be set before continuing. The last instruction says "Jump if the TI bit is not set to $"--$,
in most assemblers, means "the same address of the current instruction." Thus the 8051
will pause on the JNB instruction until the TI bit is set by the 8051 upon successful
transmission of the character.
Reading the Serial Port
Reading data received by the serial port is equally easy. To read a byte from the serial port
one just needs to read the value stored in the SBUF (99h) SFR after the 8051 has
automatically set the RI flag in SCON.
For example, if your program wants to wait for a character to be received and
subsequently read it into the Accumulator, the following code segment may be used:
JNB RI,$ ;Wait for the 8051 to set the RI flag
MOV A,SBUF ;Read the character from the serial port
The first line of the above code segment waits for the 8051 to set the RI flag; again, the
8051 sets the RI flag automatically when it receives a character via the serial port. So as
long as the bit is not set the program repeats the "JNB" instruction continuously.
Once the RI bit is set upon character reception the above condition automatically fails and
program flow falls through to the "MOV" instruction which reads the value.

8.Explain ADC and DAC of 8051

ANALOG DIGITAL TO CONVERTER ADC

Commonly used ADC device ADC804

ABOUT IC
PinOut
CS Chip Select , active low
RD Read Digital data from ADC, H-L edge triggered
WR -- Start conversion, L-H pulse edge triggered
INTR -- end of conversion, Goes low to indicate conversion done
Data bits -- D0-D7
CLK IN & CLK R
CLK IN is an input pin connected to an external clock source when an external clock is
used for timing. However, ADC804 has an internal clock

generator.
To use the internal clock generator of the ADC804, the CLK IN and CLK R pins are
connected to a capacitor and a resistor. In that case, the
clock frequency is determined by the equation.
f = 1/1.1RC
R=10K and C=150pF f=606Hz
the conversion time is 110us.
Input Voltage range
Default 0-5V. Can be changed by setting
different value for Vref/2 pin.
Vin=Vin(+) Vin (-)
Range = 0 to 2x Vref/2.
for Vin = 2x Vref/2. we get 256 as a digital
output on D0-D7. (Refer Table)

Vref/2
(Volts)

Vin
(Volts)

Open (2.5)

0 to 5

2.56
1.28

0 to
5.12
0 to
2.56
0 to 1

Step size
(mV)
5/256 =
19.53
5.12/256
=20
2.56/256 =
10
1/256=3.90

Step Size a Smallest change


0.5
(2 x Vref/2)/ 256 for ADC804
for eg for step size 10mv ,digital output on D0-D7 changes by one count for every 10mv
change of the input analog voltage.
Data Out
Dout = Vin / Step Size
for input vtg. of 2.56 volts (Vref=1.28 volts) and stepsize of 10mv Dout =2560/10
=256 or FF that is full scale output.
Conversion Time
Greater than 110us for ADC804
Resolution
8 bits for ADC804

INTERFACING ADC804 TO 8051


Signals to be interfaced (on the ADC804)
D0-D7, RD, WR, INTR, CS
Can do both Memory mapping and IO mapping

Memory Mapping (timing is critical)


Connect D0-D7 of ADC804 to the data bus of the 8051 system
Connect RD, WR of the ADC804 to the 8051 system (ensure polarity)
Connect CS of ADC804 to an appropriate address decoder output
Connect INTR of ADC804 to an external interrupt Pin on the 8051 (INT0 or INT1)

IO Mapping (easiest - I prefer )


Connect D0-D7, RD, WR, CS, INTR to some port bits on the 8051 (12 in all).

Algorithm
Make CS=0 and send a low-to-high to pin WR to start the conversion.
Keep monitoring INTR
If INTR =0, the conversion is finished and we can go to the next step.
If INTR=1, keep polling until it goes low.
After INTR=0, we make CS=0 and send a high-to-low pulse to RD to get the data out of
the ADC804 chip.

ASSEMBLY LANGUEGE

(A51)

ADC_IO:
mov P1, #0xff ; To configure as input
AGAIN
clr p3.7 ;Chip select
setb P3.6 ;RD=1
clr P3.5 ;WR=0
setb P3.5 ;WR=1- low to high transition
WAIT:
jb P3.4, WAIT ;wait for INTR
clr p3.7 ;generate cs to ADC
clr P3.6 ;RD=0 -High to low transition
mov A, P1 ;read digital o/p
sjmp AGAIN

INTERFACING ADC804 TO 8051


ADC808/809 Chip with 8 analog channel. This means this kind of chip allows to monitor
8 different transducers.
ADC804 has only ONE analog input: Vin(+).
ALE: Latch in the address
Start : Start of conversion (same as WR in 804)
OE: output enable (same as RD in 804)
EOC: End of Conversion (same as INTR in 804)
Channel

CBA

IN0
IN1
IN2
IN3
IN4
IN5
IN6
IN7

000
001
010
011
100
101
110
111

Algorithm
Notice that the ADC808/809 that there is no self-clocking and the clock must be provided
from an external source to the CLK pin. (you can use programmable clock oscillator to
enable or disable clock by programmable bit. )
Select an analog channel by provide bits to A, B, C.
Enable clock
Activate ALE with a low-to-high pulse.
Activate SC with a high-to-low pulse (start conversion) The conversion is begun on the
falling edge of the start conversion pulse. you can use circuit like
Monitor EOC Pin .After conversion this pin goes high.
Activate OE with a high-to-low pulse to read data out of the ADC chip.

DIGITAL TO ANALOG CONVERTER - DAC


Commonly used DAC808 (MC1408)
R/2R ladder
Iout = Iref (D7/2 + D6/4 + D5/8 + + D0/256)
Iout converted to voltage by a resistive load or op-amp based isolator (Rf from Vout to
V- and V+ to GND)
PinOut
D0-D7 Connected to the Processors IO port
Vref+, Vref-, Vee

Usage:
Just write a byte to the IO port and the DAC converts it to an
analog value
Some 8051 clones have ADCs and DACs in built

S-ar putea să vă placă și