Sie sind auf Seite 1von 67

U n i tV MICROCONTROLLERS

5.1 INTRODUCTION are small controllers. They are like single Microcontrollersas the name suggests, / controlling to functionasprocessing systems into other embedded often that chip computers hasa CPU A microcontroller are single chip Microcomputers. unit, i.e., Microcontrollers (a microprocessor) in additionto a fixed amountof RAM, ROM andI/O partsanda timer on a single chip. The fixed amount of on - chip RAM, ROM, timer and I/O parts in are less. in which cost and space makesthemideal for many applications microcontrollers is shownin Fig' 5. I . The internalblock diagramof microcontroller

Mlcrocontroller
Fig. 5.1 Microcontroller Internal Block Diagram

a CPU only. The functionalblockslike memoryand means The word microprocessor chip to makea complete to a microprocessor externally areto be connected otherperipherals arehavingall thesefacilities in a singlechip. The But the microcontrollers microcomputer. that they are user in the sense are used for generalpurposeapplications microcontrollers general requirement. design more to meeta blockssuitable programmable andhavefunctional - purpose productsaswell. The and application specificmicrocontroller Thesearegeneral (8051), 89 C XX, Motorola Atmel MCS 5l are Intel for microcontrollers examples 68HCX I lXX, PIC family by microchip(PIC l6C64X).
Microcontrollerc

5.3

5.1.1 Differences between Microprocessors and Microcontrollers The fundamental differences between microprocessors andmicrocontrollers arethese: L 2. Microprocessors are intendedto be general- purposedigital computerswhereas microcontrollers are intendedto be special- purpose digital controllers. Microprocessors containa CPU, memoryaddressing circuits and interrupthandling circuits. Microcontrollers havethesefeatures aswell as timers,paralleland serialI/O and internalRAM and ROM. Many microcontrollers featureprogrammable pins that allow externalmemoryto be addedwith the loss of I/O capability.

3. 4.

Microcontrollermodelsvary in datasizefrom 4 to 32 bits. 4 bit units areproduced in hugevolumesfor very simpleapplications and 8 bit units are the most versatile.l6 and32 bit units are usedin high - speed control and signalprocessing applications. 5.1.2 Features of Microcontrollers The features of microcontrollers are : 1. High integration of functionality : Microcontrollersare called as single chip computers because they haveon - chip memoryand I/O circuitry and other circuitriesthat enable themto functionas small stand- alonecomputers without other supporting circuitry. 2. f ield programmability flexibility : Microcontrollers oftenuseEPROMoi E2PROM as their storage deviceto allow field programmability so they are flexible to use. Oncethe programis testedto be correctthenlargequantities of microcontrollers canbe programmed to be usedin embedded systems. 3. Easy to use. 5.1.3 Advantages of Microcontrollers l. 2. 3. 4. 5. The overall systemcost is low, as the peripherals are integrated in a singlechip. The productis of small size as compared to the microprocessor basedsystemand is very handy. The system is morereliable. The systemis easyto troubleshoot and maintain.

If requiredadditionalRAM, RoM and vo portsmay be interfaced. 5.1.4 Intel 8051Microcontroller The 8 bit microcontroller 8051family hasnumbers rangingfrom 8031to 8751andare availablein N-channelMetal Oxide Semiconductor (NMOS) and Complementary MOS in a variety of package ICMOS] construction types. The intel corporationintroducedan 8 bit microcontroller8051 in 1981. This microcontroller had 128 bytesof RAM, 4k bytesof on - chip ROM, two timers,one serial port and 4 eight bit ports all on a singlechip. The 8051is the original memberof the 8051 family. Intel refersto it as MCS - 51. 5.4
22

Microprocessons and Microcunnollers

to of the 8051family is the 8031chip. This chip is referred The mostpopularmember between comparison The ROM. chip as a ROM less8051,sinceit has0 kilo bytesof on 8051and8031is givenin Table5.1. 8051and t031 Tabte5.1 Comparisonbetween Feature On chip ROM RAM Timers VO pins SerialPort Intemrptsources

8051
4k bytes 128bytes 2 32 I 6

8031 0 kilo bytes bytes 128 2 32 I 6

8051is availablein differentmemorytlpes suchas UV-EPROM,FlashandNV-RAM, partnumbers. TheUV-EPROMversionof the 8051is the 8751.The all of whichhavedifference The Atmel Flash8051is AT89C5I. The by manycompanies. flashROM versionis marketed is calledDS 5000. TheTable24.2 IW-RAM versionof the 8051madeby Dallas semiconductor givesthe various8051microcontrollers. Table 5.2. 805f Microcontrollers Company Atmel corporation Dallassemiconductor Intel corporation Philipssemiconductor Siliconsystems 5.2 ARCHITECTURE OF 8051 Version AT 89C51 DS 5000 I 805 8xC75l 8052

busesfor both programand data. So, it has two The intel 8051 containstwo separate of 64K x 8 size for both programand data. It is basedon an 8 bit distinctivememoryspaces 8 bit B registerasmainprocessing andanother unit with an 8 bit accumulator centralprocessing and8 bit memory includefew 8 bit and 16bit registers blocks.Otherportionsof the architecture This area locations. It hassomeamountof dataRAM built in thedevicefor intemalprocessing. penpheral with on-chip of data.805I is supported andtemporary storage is usedfor stackoperations port. Fig. 5.2 showstheblock serialcommunication functionslike VO ports,Timers/ Counters, 8051. diagramofthe
Mlcrocpntrollers

The features of the g05l are :

5.2.1 Centralprocessing Unit The cPU is the brain of the microcontro-llers readinguser'sprograms and executing expected taskasperinstructions the stored therein. It's primaryZlements areanAccumulator (ACC),

,?l1Tbt3+f,':::,H'fr",n*j".ffi".."J;,;;da;;;|amstatusword(psw
5.2.2 Accumulator Theaccumulatorperforms arithemetic andlogicfunctions on g bit inputvariables. operations Arithmetic includebasicaddition,,uu*ui,lon, muriipricai."."a division.Logicaroperations AND' oR xoR asw.ell"tt"t"t";;;;;;;ll.pt".*tio-Gn are *m a, theabove, accumurator is o".irion,

;?ilfi:'ll"#ffHHT:tranching
5.2.3 B Register B registeris usedin multiply

"'d pr;;o!;'u,"-poruryprace in adatatransrer

fi:::ff;-,[:[Ulut'
pointer 5.2.4Stack

"nJ;;;';;;;;'

and divide operations.During

either aportion ortheresurt. Forotherinstructio'ns itis used

executionB register

stackPointer . bir.*gt:*r. keeps trackof memory lmportant l?:::: I stored Thispoinrer space register where information the are when the progru,n flI*-gets into Thesrack executing portion a subroutine. mavbepr"""d;;;;il; i" th. ;t;;-nala. Butnormarysp is initiarized to07Hafter adevice reset andgrows up'from the location Ogi{. Th; sp is automaticaily or decremented incranented for all PUSH"orpop'iffioions andro. "ii ,ubooutin" caus and returns. 5.2.5Program Counter TheProgram counter(PC)is tn" t1,.9.1l.l"gister givingaddress execured of nextinstruction during program to be execution andit arways pointsiothJprogammemory space.
5.6 Micr oprocessors and Mirrlorrtn roil

P0.0-P0.7

P2.O-P2.7

Vcc

Port0

Porl2

Vss

Eg
eg rRAM

ft{}
Port0 | LatchI

{,lPort2 I Latch

n
;1

el

I
B Registr

Stack Pointer

1I
\
hJ

tl
Brfi',

{ ,

THO

T--L
Program Counter

THI ITLI I IEI IP


Inlerrupt, Serial Port& Timer Blocks
Timino

PSEN .ob
<)o c

EA

Control

EF

,
Port1 Latch

Oscillator

]L
Port1

XTAL 1

tflr

-'-"-'-'-lI^tI.ilJJJ" "-'-'-"' U^rililF


XTAL 2 P1.0-P1.7 P3.0-P3.7 Fig. 5.2 805 I Architecturc

IE
t3 ch )| Port3

t 1

DPTR

5.2.6 Data PointerRegister TheDataPointerRegister (DPTR)is the 16bit addressing register thatcanbe used to fetch any 8 bit datafrom the datamemoryspace.Whenit is not beingusedfor this purpose, it canbe usedastwo eightbit registers, DPH andDPL. 5.2.7 Program StatusWord The ProgramStatusWord (PSW) keepsthe current statusof the arithmeticand logic operations in differentbits. The 805I hasfour mathflagsthatrespond automatically to theoutcomes of arithmetic andlogic operations and3 general purpose userflagsthat canbe set I or cleared to 0 by the progralnmer as desired. The math flags are carry (C), auxiliary carry (AC), overflow (OV) andparity (P). Userflagsarenamedflag 0 (F0),Register bankselectbits RSOandRSl.
Misocontrollers

5.7

CY

AC

FO

RS1 RSO OV

Carryl..Use1
Carry ftas

| frao-orrf,",flaeo I
| t 0 0 1 1

loverftow

I
| j 0 1 0 1

ftas

parity

nas

- Select register bank0 - Select register bank1 - Select register bank2 - Select register bank3

5.2.8 Input / Output Ports 8051has32VO pinsconfigured as4 eightbit parallel ports(p0, pl,p2and p3). Each pin be used as an input or as an output underthesoftware control.These VO pins.un 6" accessed 9an directlyby memoryinstructions duringprogram execution to getrequireReiiUitity. These port linescanbe operated in differentmodes andall thepinscanbemadeto do many differenttasksapart from their regularVO functionexecutions.port 0 used as a multiplexed address / databus. At the beginingof an extemalmemorycycle,low order8 bits of the address busareoutputonP0. Thesame pinstransfer data byteat thi laierstage of theinstruction execution. Any instructionthat accesses externalprogrammemorywill outputthe higherorderbyte (A8 - Al5) on Port2 duringreadcycle. Port I andPort3 areavailable for standard VO functions. Port 3 pins hasthe additionalfunctions: 2 externalintemrptlines,2 counter inputs,2 serialport datalinesand2 timingcontrolstorbe lines. 5.2.9 fimers / Counters 8051hastwo l6 bit Timers / Counters, T0 andTl capable of workingin different modes. Eachconsists of a 'HIGH' byteanda 'LOW' bytewhich "un b" accessed undersoftware.There is a modecontrol register(TMOD) and a control register(TCON) to configurethesetimers/ counters in numberof ways. These timersareusedto measure time intervals, determine pulsewidthsor initiateevents with onemicrosecond resolutionuptoa maximum65ms.use software to get longerdelays. 5.2.10SerialPort The 8051hasa highspeed full duplexserial portwhichis software configurable in 4 basic modes: Shift registermode Standard UART mode Multiprocessor mode 9 bit UARTmode. FuIl duplexmeans the datacango bothwaysat the same time.
5.8 Microprocessorsand Miqocontrollers

InterruPts 5.2.11 : Onefrom theserialport (RI / TI) whena transmission The 8051hasfive intemrptsources : two from the timers(TFO,TFI) when overflow occursand is execuied operation or reception or enabled independently two comefrom the two input pins INT0, INTI. Eachintemrptmaybe priority' low or high as and eachmay be classified disabledto allow polling on samesources (IE) andIntemrptPriority (IP) registers' Enable by Intemrpt areselJcted operations These Oscillatorand Clock 5.2.12 are synchronized' the clock pulsesby which all internaloperations The g05l generates networkto form anoscillator'A PinsXTAL I andXTAL 2 areprovid.d for.orrn"ctinga resonant of clock frequency quartzcrystalis usedfor osciliator.The crystalfrequincyis thebasicinternal themicrocontroller. MEMORYORGANIZATION several It supports capabilities' expansion provide bothonchipmemory Theg05l architecture different by 'physical' address level hardware the at functionallyseparated spaces, distinctive or both : write controlssignals and read mechanisms, addressing 5.3

memoryor Flash/ EPROMincase of external TheprogramMemoryarea(EPROMincase Program whenthepoweris removed. andneverloseinformation of intemalone)is extremelyiarge Calibration values, : Initialization timepoweris applied each needed for information Memoryis used hasa l6 bit Memory The Program itself. program with the etcalong lookuptables data,Keyboard and Counter Program bit 16 usingthe and any particularmemorylocationis addressed address a 16bit address. which generate instructions Memory and it goes quickerthan Program OnchipDatamemoryis smallerandtherefore whicharecalculated for variables RAM is used Onchip whenpoweris removed. state intoa random whentheprogramis executed. needa single8 bit In contrastto the ProgramMemory On chip Data Memory accesses 8 bits aremore Since location. to specifua unique variable) or another value(maybe a constant registeris generating the onchipRAM address than suflicient to address128 RAM locations, singlebytewide. andthis differentmemoryspaces these to access areused mechanisms Differentaddressing effrciency' operating to microcomputer's greatlycontributes portion. memory of anintemalandanexternal consists Memoryspace The64K byteProgram address the unless Memory out of InternalProgram 11 *rr ne pin is heldhigh, the 8031executes gFFFH and locations1000HthroughFFFFHare then fetchedfrom externalProgram exceeds
Miqocontrollers

from the externalProgram all instructions Memory. lf tnr fn pin is held low, the 8051fetches mechanism. the addressing is Counter the 16bit Program Memory.In eithercase, of an intemal and an externalmemoryspace. space consists The DataMemory address is executed. whena MOVX instruction ExtemalDataMemoryis accessed FFFF

FFFF

60K Bytes External


1000 A ND 000F

| 4KBytes I Internal I J 0000 il=1

l-""0000

64K Bytes External

EA= 0

FiS.5.3 PrcgrantMemeory

bytes,total sizeof DataMemorycanbe Apart from onchipDataMemoryof size 128/256 upto64K usingextemalRAM devices. expanded TotalinternalDataMemoryis dividedinto threeblocks: Lower 128bytes Higher128bytes. SPace. FunctionRegister Special only in 8032/ 8052devices. Higher 128bytesareavailable

FFHl----

FFH

Upper 128 Bytes


80H 7FH Lower 128Bytes 00H

Special Function Registers 80H

* Ports * Status Bits andControl * Timers


* Registers * StackPointer * Accumulator, etc.

Fig. 5.4 InternalData Menory

5.10

Mir:roprue ssorsond Micr.mntr ollers

locations,they areaccessed address EventhroughtheupperRAM areaandSFRareashare SFRmemoryspace Directaddresses higherthan7FH access modes. through differentaddressing (in / bytes 8032 8052). 7FH access higher 128 indirect addressing above and

FFFFH

SFRs Direct Addressing Only Direct & Indirect Addressing

-AND

>

64K Bytes External

0000H DataMemory Internal


Fig. 5.5Data Memory

The figure5.6indicates thelayoutof lower 128bytes.Thelowest32 bytes(from address grouped Program instructions referthese registers as 00H to IFH) are into 4 banksof8 registers. Word indicates which registerbankis beingusedat anypoint of R0 throughR7. Program Status time.
7FH

30H Bank Select -r v Bitsin PSW 11 1 0 10H 01


08H 2FH

20H
1FH 18H 17H

Scratch PadArea Bit Addressable Space(Bit Addresses 0-7F)

4 Banks of 8

OFH
07H

Reoisters (Ro--R7)

07H

00

00H

Reset Value of Stack Pointer

Fig. 5.6 Lower 128Bytesof InternalRAM

MX:rocontrollers

5.11

memory space. Thenext 16bytesabove these register banksfroma blockofbit addressable processing and these instructions The instructionsetof 8051contains a wide rangeof singlebit instructions the 128bits of this area. candirectly access port latches, All themembers TheSFRspace includes timerandperipheral controlregisters. of 8051family havesameSFRat the sameSFRlocations.Thereare some16 uniquelocations whichcanbe accessed asbytesandasbits. s.4 SPECIAL FUNCTION REGISTERS (SFRs)

00H to areabove80H, sincethe addresses The address of the SpecialFunctionRegisters 80HandFFH. But all 7FHaretheaddresses ofRAM memory.TheSFRs haveaddresses between locationsarereserved and theaddress of 80H to FFH is not usedby the SFRs.The unused space aregivenin Table5.3. mustnot be usedby the programmer. The SFRsandtheir addresses Table5.3.Special FunctionRegisters
Name

Function Accumulator Arithmetic (DataPointerHigh byte)Addressing externalmemory DataPointerLow byte Intem.rpt EnableControl Intemrpt Priority Control VO Port 0 Latch VO Port I Latch VO Port 2Latch VO Port 3 Latch PowerControl Program Status Word SerialPort Conhol SerialPortDataBuffer StackPointer Timer/ CounterModeControl Timer/ CounterControl Timer 0 low byte Timer 0 high byte Timer I low byte Timer I high byte

Address(Hex) EO FO 83 82 A8 B8 80 90 AO BO 87 DO 98 99 8l 89 88 8A 8C 8B 8D
Miooprocessorsand Misocontrollers

Acc (A) B DPH DPL IE IP PO PI P2 P3 PCON PSW SCON SBUF SP TMOD TCON TLO THO TLI THl 5.' t2

5.5

PIN DETAILS OF 8O5T

P1.0 P1,1 P1.2 P1.3 P1.4 P1.5 P1.6 P1.7 VPD/RST P3.0/RxD P3.1/TxD P3.2/INTO P3.3/lNTl P3.4lT0 P3.5/T1

Vr" P0.0 P0.1 PO.2 P0.3 P0.4 P0.5 P0.6 P0.7 VDD/EA

11

8051

30

PROG/ALE PSEN P2.7 P2.6 P2.5 P2.4 P2.3 P2.2 P2.1 P2.O

ru.6m
P3.7/RD XTAL2 XTALl V,,
Fig. 5.7 8051PinoutDiagram

suchasDIP,QFPandLLC andtheyhave40 pinsfor in differentpackages, The 8051comes pin 40 DIP pinout diagramand Fig 5.8 showsthe logic 5.7 shows The Fig variousfunctions. Atotalof32pinsareusedforfourportsP0,Pl,P2andP3,whereeachporttakesSpins. symbol.

Micr.oanttollers

5.13

VSS Vcc RSTNPD

Ef
XTAL2

PoRro (Po.o_Po.7) ,,|

enlvoo

ALE/PROG

l PoRrl
J

ter.eeo.zl

nxo

IE PoRr3
1T;
l*t

I rxD

It'
\RD
Fig. 5.8 8051Logic Symbol

PoRr2

)(P2.o-P2.7)

8 pinsareV.", GND,XTALI, XTAL2, RSI EA, PSEN andALE / PROG Theremaining pins aredescribed as follows : andALE / . The functionsof these 1'V"" Pin 40 of 8051providessupplyvoltageto the chip from the +5V voltagesource. 2. GND Pin 20 is the groundfor the chip, 3. RST (highpulse) asa powercn reset.Whenactivating Pin 9 is theRESETpin. This is referred givesthe Table to lost. 5.4 in theregisters be will resetandall values thispin themicrocontroller resetvalues of someregisters.
5.14 ors and Micr. uonttoller s Microprocess

Table 5.4 RESET Value Register PC ACC B PSW DPTR SP 4. frlExternal Access) ResetValue

H 0000 0000 H H 0000 H 0000 H 0000 H 0007

hasON - CHIP to eitherV""or GND. The 8051family members This inputpin is connected there to V.. in 8051. For 803I family members, ROM to storeprogramr. gA pin (3I ) is connected by 8031. 11.ts, EA pin on an extemalROM andis fetched is no ON-CHIPROM, codeis stored externally. is connected to GND to indicatethat thecodeis stored 5. StoreEnable) PSEN(Program

in which an external system is 29. In an 8051- based This is an outputpin andpin number pin ROM. of the to the OE ROM holdstheprogramcode,this pin is connected 6. ALE (AddresLatch Enable) memory an 8051to external This is anoutputpin (30) andis activehigh. Whenconnecting and data through address multiplexes otherwords, 8051 port 0 provides anddata. In both address = (A.port 0 to save pins. If ALE 0, Port0 provides data(D0 D7). If ALE=I, it hadaddress 4). 7. XTALl andXTAL2 anextemalclock to returnit. Thequartz The8051hasanon - chip oscillatorandit requires to XTAL I (pin l9) andXTAL 2 (pin 18)with crystaloscillator(lZMHz I 20MHz) is connected asshownin Fig 5.9. two 30pFcapacitors

c1

XTALl I-,T]

F,4xrAL2
Fig.5.9XruL connected to 805l Microantrollers 5.15

8.

Port 0 (P0.0- 0.7)

chipis anddatabus(ADo- ADr). Whenthemicrocontroller Port0 is usedfor bothaddress pin if Port indicates ALE anddata. bothaddress memoryPort0 provides connected to anexternal or data. 0 hasaddress data(Do- Dr) When ALE :0, Port0 provides : 1, Port 0 provides (4 - Ar) address 9. anddatawith the help of a latch. address ALE is usedfor demultiplexing Port I (P1.0- P0.7)

Port I pins areusedasinput or output. To makeport I asan input port, write 1 to all its 8 bits. To makeport I as output port, write 0 to all its 8 bits. Thus port I pins haveno dual functions. 10. Port 2 (P2.0-P2,7) useof to port l. Thealternate Port2 pinsareusedasinput/ outputpinssimilarin operation to is connected port2 is to supplya high orderaddress byte (A8 A,5)whenthe microconffoller extemalmemory. 11. Port 3 (P3.0- P3.7) Port3 pinsareusedasinput or output.Port3 hastheadditionalfunctionsasgivenin Table 5.5. Table5.5Port 3 Functions Pin Function Serialdatainput Serialdataoutput Extemalintemrpt0 Externalintemrpt I Externaltimer 0 input I input Externaltimer Externalmemorywrite pulse Extemalmemoryreadpulse

- RxD P3.0 P3.l- TxD - INTO P3.2 - INTI P3.3 - T0 P3.4 - Tl P 3 .5 - WR P3.6 - RD P3.7
5.6 ADDRESSINGMODES

Theaddressing modes or beprovided arethewaysof accessing datain register or in memory named first. asanimmediate value. The 8051mnemonics address arewrittenwith thedestination followedby the source address.
5.16 Micr:oprocessorsand Microcuntrollers

data: areusedto access modes The following addressing mode addressing l. Immediate 2. mode addressing Register mode 3.. Direct addressing mode indirectaddressing 4. Register 5. mode. addressing Indexed Mode 5.6.1 ImmediateAddressing canbeembedded ratherthana variable,thentheconstant is a constant operand Whena source the specifies one first and bytes two into the instnrctionitself. This kind of instmctionstake the after comesimmediately byte givesthe requiredconstant.The operand and second opcode modecanbe datais the poundsign (fl. This addressing The mnemonicfor immediate opcode. register. DPTR including usedto load informationinto any of theregisters Examples: MOV A. # 18H

[t-l-MOV B, # 65H

l8H

lrl.MOV DPTR,#2O4OH DPL DPH 5.6.2 RegisterAddressingMode

65H

40H 20H

register (Ro- R ) of the selected the eight working registers accesses addressing Register to beused is which register indicate opcode bank.Theleastsignificantthreebits of theinstruction in the PSWbeforeusing is to be predefined for the operation.Oneof the four banksof registers in this mode' be addressed can also DPTR B and ACC, instruction. addressing register Examples: MOV A. R3

H
R O
\/

R3

MOV RO.A

rilE

ADDA,*o [-ffi+f
Microcpntrollers

xxl
5.17

R6

Mode 5.6.3 Direct Addressing maybeaddressed RAM andtheSFRs mode, all I 28bytesof internal In thedirectaddressing to eachRAM locationand eachSFR.Intemal assigned directly usingthe single- byte address exist from 80H to eachbyte.The SFRaddresses from 00H to 7FH to address RAM usesaddress Table5.3). FFH.'(Refer Examples
60H

MOV R2,6lH MOV 6F H, A

61H 61H

6FH Mode Indirect Addressing 5.6.4 Register In this modea registeris usedasa pointerto the data. If the datais insidethe CPU,only of RAM R0 and Rl are usedfor this purpose. When R0 and Rl hold the addresses registers "@" sign. by the theymustbe preceded locations, Examples

MOV @ Rl, A MOV B, @ Ro

: :

of A into RAM locationwhosead&essis held Move contents byRl. is heldby R0 of RAM locationwhoseaddress Move contents into B.

Mode 5.6.5 IndexedAddressing for reading by thismode.This modeis intended memory canbeaccessed Only theprogram points to the baseof (DPTR or PC) register program 16 bit base A memory. lookuptablesin the address The indicatingtableentrynumber. theconstant carries thelookuptablesandaccumulator datato thebasepointer. of theexactlocationof the tableis formedby addingthe accumulator Example MOVC A, @A+ DPTR : 5.7 INSTRUCTION SET formthe16bit addedtotheDPTRto ThecontentsofAare 'C' code. data. means of theneeded address

on to perform a specifiedoperation given to the computer An instmctionis a command is designed thatthemicrocontroller setis thecollectionof instmctions givendata.Theinstruction instructions. language usingthese in assembly canwrite theprogram to execute. Theprogrammer havebeenclassifiedinto the following groups. These insffuctions l. Datatransfergroup 2. Arithmeticgroup
5.18 and Microcpntnollerc Miooproces.sors

3. 4. 5.

Logicalgroup BooleanvariablemaniPulation Programbranching Description


A +Rn 4 + (addr) 4 + (Ri) A + data Rn +A p1 + (addr) Rn <- data (addr) + 6 (addr) e P1 (addr l) <- (addr 2) (addr) e (Ri) (addr) <- 61" (Ri) <- 4 (Ri) <- (addr) DPTR <- data 16 [+ (A+DPTR)

Instructions 5.7.1 Dnta Thansfer Mnemonic


MOV A, RN MOV A, direct MOV A, @ Ri MOV A, # data MOV Rn, A MOV Rn, direct MOV Rn, #data MOV direct,A MOV direct,Rn MOV direct,direct MOV direct,@Ri MOV direct,#data MOV @ Ri, A MOV @ Ri, direct MOV DPTR,# data16 MOV C A, @A + DPTR MOVC A, @A + PC MOVXA,@Ri MOVXA,@DPTR MOVX@Ri,A MOVX@DPTR,A PUSHdirect

Operation
to accumulator Move register Move directbyte to accumulator Move indirectRAM to accumulator datato accumulator Move immediate to register Move accumulator Move directbyte to register datato register Move immediate to directbYte Move accumulator to directbYe Move register Move directbye to directbYe Move indirectRAM to directbYte datato directbyte Move immediate to indirect RAM Move accumulator Move directbye into indirectRAM Load datapointerwith 16bit constant Move codebyte relativeto DPTR to accumulator Move codebyte relative to PC to accumulator. tc RAM (8 bit address) Move external accumulator RAM (16 bit address) Move external to accumulator. RAM to external Move accumulator (8 bit address) RAM to external Move accumulator (16 bit address) Pushdirectbyte onto stack

A c- (A + PC) A + (Ri)^

(DPTR)"
(Ri)" <- 4

(DPTR)^ + (SP)+- ADDR

Miclrocplltrollqs

5.19

Mnemonic
POP direct XCH A, RN XCH A, direct

Description
(addr) + (SP) A eRn 4e (addr) 4 e (Ri) (Ri)L

Operation
POPdirectbyte from stack register with accumulator Exchange Exchange direct bye with accumulatol indirectRAM with Exchange accumulator low orderdigit indirect Exchange RAM with accumulator

xcH A, @Ri xcHD A, @Ri

41e

Note: Rn: Any of theeightregisters, bank. \ to &,in theselected Roto R, in the selected bank. R, : Eitherof the pointingregisters addr= Address of the internalRAM from 00H to FFH. L : Leastsignificantnibble. ^ = Externalmemorylocation. ( ) = Contents of the locationinsidetheparentheses. Examples:

(i)

Mov A, # 38H Acc e 38(data) E Mov A, 18H Acc

(ii)

tll

18 H

Ixxlo",.
\/

(iii)

Mov A, Rl Acc

R1

[-'l -\,/

xxlo.t" I 7
copycarrybit to port bit PI.2.

(iv)

MOV PI.2,C

P1.2

Car

5.20
23

and Mkrocunnolbs Micr. oprocessors

(v)

MOVA,#51H;A:5lH MOVF.2,#22H;R2:22H XCH A, R2 ; A:22H andR2 = 51H Description


A e-A+Rn A *A+(addr) A*A+(Ri) A+A+data A-A+Rn +C

5.7.2 Arithmeticlnstructions
Mnemonic ADD, A, RN ADD A, direct ADD A, @Ri ADD A, # data ADDC A, RN ADDC A, direct ADDC A, @Ri ADDC A, # data SUBBA, Rn SUBBA, direct suBB A, @ Ri SUBBA, # data INC A INC Rn INC direct rNC @Ri INC DPTR DECA DEC Rn DECdirect DEC@ Ri MUL AB DIVAB DAA

Operation
Add register to accumulator Add direct byte to accumulator Add indirect RAM to accumulator Add immediate data to accumulator Add register to accumulator with carry Add direct bye to accumulator with carry Add indirect RAM to accumulator with carry Add immediate data to accumulator with carry Subtractregister from accumulator with borrow Subtract direct bye from accumulator with borrow Subhact indirect RAM from accumulator with borrow Subtract immediate data from accumulatorwith borrow Increment accumulator Increment register Increment direct byte Increment indirect RAM Increment data pointer Decrementaccumulator Decrementregister Decrement direct byte Decrement indirect RAM Multiply A and B Divide A by B Decimal adjust accumulator

A+A+(addr)+c A+A+(Ri)+C A+A+data A<-A-Rn-C A <- A -(addr) - C

A + A -(Ri)-C
A+ A-data-C

A <-A+l Rn +Rn+ I (addr) * (addr) +

(Ri)*(Ri)+l DPTR +- DPTR +1 A <-A- I Rn*Ra-1 (addr) * (addr) -1

(Ri) <- (Rr) -l AB*AxB AB <- A,/B A .off + [ . bm .

Mioocontrolle,r:s

5.21

Examples: (i) . Mov A, # +5 MOV R0, # +3 ADD A, RO 0000 0000 AA Answer +@ (ii) Mov A, # 50H CLR C SUBBA, # 3OH A C Y A 0000 0l0l 0 0 1I 1000

@ - 3 0- E : l t o ]
A Answer +

(iii)

Mov A, # 78H MOV B, # 25H MUL AB 78Hx 2 5 H = l l 5 8 H B


Answer + A

E E

(iv)

MOV A, # 89H M O V B , #I I H DIVAB B Answer +


A

@ @

5.22

Micr oprx essorscnd Micr ocontrollq s

5.7.3 LogicalInstructions Mnemonic


ANL, A, RN ANL A,'direct ANL A, @Ri ANL A, #data ANL direct,A ANL direct,#data ORLA, RN ORL A, direct oRL A, @Ri ORL A, #data ORL direct,A ORL direct,# data XRLA, RN XRL A, direct xRL A, @Ri XRL A, #data XRL direct,A XRL direct,#data RLA RLC A RRA RRC A CLRA CPLA SWAPA

Description
(A) AND (Rn) (A) AND (addr) (A) AND (RD) (A) AND data (addr)AND (A) (addr)AND data (A) oR(Rn) (A) oR (addr) (A) oR ((Ri)) (A) OR data (addr)oR (A) (addr)OR data (A) xoR (Rn) (A) XoR (addr)

Operation
to accumulator AND register AND directbyteto accumulator AND indirect RAM to accumulator AND immediatedatato accumulator to direct bYte AND accumulator AND immediatedatato direct bYte to accumulator OR register OR directbyteto accumulator OR indirectRAM to accumulator OR immediatedatato accumulator to directbYte OR accumulator datato directbYte OR immediate to accumulator Ex - OR register EX - OR directbyte to accumulator EX - OR indirectRAM to accumulator datato accumulator EX - OR immediate to directbYte EX - OR accumulator datato directbYe EX - OR immediate
Ao

(A)xoR(Ri))
(A) XOR daa (addr)XoR (A) (addr)XOR data
Ao-A'+A.....+-A,+ C*Ar*A0....*Ao-C Ao+Ar+A0....-A,*Ao C-rAr-Au....*Ao-C A-00

left Rotate accumulator Rotateaccumulatorleft throughcarry right Rotateaccumulator right throughcarry Rotate accumulator Clearaccumulator accumulator Complement Swapnibbleswithin the accumulator.

n*A
Ar-A"

Microcontrollers

5.23

Examples:

(i)

Mov A, # 39H
ORL A. # O9H 39H+0011l00l 0 9 H+ 0 0 0 0 1 0 0 1 001I 1001

* F9HI Answer
(ii) Mov A, # 32H MOV RO, # 5OH XRL A, RO 3 2 H- 0 0 1 1 0 0 1 0 5 0 H+ 0 1 0 1 0 0 0 0
0 1l 0 0 0 1 0

Answer - loznI
(iii) cLR c MOV A, # B8H RLC A (iv) MOV A, # l8H SWAPA The SWAPinstructioninterchanges the lower nibble (D0 - D3) with the upper nibble(D4 - D7) insideregister A. Answer =) A=8lH(1000 0001).

5.7.4 Boolean VariableManipulationInstructions Mnemonic CLR C cLRbit SETBC SETBbit


5.24

Description c <-0 bit <- 0 c <-l bit <- I Clearcarry

Operation

Cleardirectbit Setcarry Setdirectbit


Micr oprocessors and Micto con trollers

CPLC cPL bit ANL C bit


ANL C, blt

c <-e
bit e bit (C)AND bit (C)AND brt

carry Complement directbit Complement AND directbit to carry of directbit to carry AND complement OR directbit to carry of directbit to carry OR complement Move directbit to carry Move carryto directbit Jumpif carryis set Jumpif carryis not set. Jumpif directbit is set Jumpif directbit is not set Jumpif directbit is setandclearbit

oRL C,bit
ORL C, bit MOV C, bit MOV bit, C JC radd JNCradd JB bit, radd JNB bit, radd JBCbit, radd Note:

(C) oR bit (c) oR bit C <- bit bit <- c [C=l];PC<-PC+2+radd [C : 0]; PC +- PC+2+ radd [bit: l]; PC <- PC+3+ radd [bit = 0]; PC <- PC+3+ radd [bit: l]; PC <- PC+3+ radd

is true [ ] : : IF the conditioninsidethebrackets THEN the actionlistedwill occur, ELSEgo to thenextinstruction. from- l28d to a signed number address, radd: Relative +127 d. bit in internalRAM or a SFR. bit = Addressable C Examples (i) cLR Pl.2 Pl.Z:0 (ii) sET B P2.4 P2.4:I (iii) low, send37 H to P3. Whenit becomes Monitorbit2.6 continously. SETB HERE: P2.6 ; makeP2.6an inputbit ; stayhereaslongasP2.6: I 37 H to P3. P2.6=0, send ; since
5.25

: Carry falg.

JBP2.6, HERE MOV P3, #37H

Microcontrollers

5.7.5 ProgramBranchingInstructions
Mnemonic ACAI J sadd

Description

Operation call Absolutesubroutine call Long subroutine Returnfrom sub- routine Retumfrom intemrp jump Absolute Longjump

(sP)<-pc + 2;
PC <- sadd (sP) <- PC+ 3; PC <- ladd PC +- (SP) PC <- (SP);EI PC <- sadd PC <- ladd

LCALL ladd

RET RETI AJUMP sadd LIUMP ladd SJUMPradd JMP@A+DPTR JZradd JNZ radd

p C < _ p C + 2 + r a d d Shortjump (relativeaddress) PC <_DPTR+ A [A:00]; PC <- PC+ 2 + radd [A > 00]; PC<-PC+2+radd Jumpindirectrelativeto the DPTR is zero Jumpif accumulator is not zero. Jumpif accumulator

CJNEA, direct,radd CJNEA, # data,radd CJNERn,# data, radd DJNZ Rn, radd DJNZ direct,radd NOP Note :

to Acc andjumpifnot directbyte Compare lA < > (addr)l; P C < - P C + 3 + r a d d equal. datato Acc andjump Compareimmediate [A < > (data)]; P C < - P C + 3 + r a d d ifnot equal. immediate datato registerand Compare t(\). > datal; P C < - P C + 3 + r a d d jump if not equal. registerandjump if not zero. Decrement [R"-l < > 00]; PC<-PC+3+radd Decrement directbyteandjump ifnot zero. [ ( a d d ) - l< > 0 0 ] ; P C< - P C + 3 + r a d d PC <_PC+1 No operation.

ladd : Longaddress of 16bits from 0000Hto FFFFH. sadd: Shortaddress of 11bits.

5.26

Microprocessors and trylbocontrollers

Examples (i) ' 40H - 4FH to find how manyof themhavethe value0. RAM locations Search MOV R5, 16 MOV R3, #0 MOV Rl, #40H LOOPI : MOV A, @Rl JNZ LOOP 2 INC R3 LOOP2 : INC Rl ;point to nextlocation ;repeatfor all locations. ; setcounter ; R3 holdsnumberof zeros ;address ;bring datato accumulator

DJNZ R5, LOOP 1

jumps if register A hasa valueotherthanzero I JNZ = This instruction address]. andif theresultis not zeroit will jump to target DJNZ :+ A byteis decremented, (ii) CJNEA, # data,radd andjump if not equal. + Compare dataandaccumulator KeepmonitoringP2 indefinitely for the valueof AB H. Get out only when P2 hasthe valueAB H. MOV P2, PASS: MOV A CJNE A, OFF H P2 ; makeP2 asinput port ;read,P2

# ABH, PASS ; keepmonitoring.

8051 - Instruction Set in Alphabetical Descriptions order


l. ACALL addr (AbsoluteSubroutine Call) In ACALL, thetargetaddress is within 2K bytesfrom theprogramcounter(PC). ACALL is a 2 byteinstruction, in which 5 bits areusedfor the opcode andthe remainingI I bits areused for thetargetsubroutine address.An I I bit address limits therangeto 2K bytes Exemple: 2. ACALL LOOP

ADD A, Rn (Add registerto Accumulator)

The contents of the accumulator are addedwith the contents of registerand the resultis stored in accumulator. Rn indicates that R0 to R7. (A) e (A)+(Rn)

Microconnollers

5.27

Example:

ADD A, R3 A A

R3

@ < - @ ] +
3. ADD A, direct (Add directbyte to the Accumulator)

with the datain RAM memorylocation. areadded of the accumulator The contents (A) <-(A) + (directbyte) Example: ADD A, l8H A A 18H

@
4. ADD A, # data

(Add immediate datato accumulator) and the result is storedin the The given data is addedwith the contentsof the accumulator accumulator. (A) <- (A) + data Example ADD A, #37H A
A

@
5. ADD A, @Ri

e t r + 3 7

(Add indirectRAM to the accumulator) with thecontents of RAM locationpointedto by Thecontents of theaccumulator areadded R0 or Rl andtheresultis storedin accumulator (A) <- (A) + (R) Example 6. ADD A, @ R0

ADDC A. Rn (Add registerto Accumulator with Carry)

Add thecontents of Rn, thecarryflag andtheaccumulator andtheresultis stored contents in accumulator. Rn indicates that R0 to R7 (A) <- (A) + (cY) +(Rn) Example 7.
5.28

ADDC A, R3

ADDC A. direct (Add register with Carry) byte to accumulator


Mirlroprocessorsand Mioocontr ollers

and the contents of RAM location,the carry flag and the accumulator Add the contents resultis storedin accumulator. (A) <- (A) + (CY) +(directbyte) Example . 8. ADDC A, 18H

ADDC A, #data with Carrl') (Add immediate datato accumulator

andthe carryflag. Theresult of theaccumulator with the contents Thegivendatais added in accumulator. is stored (A) <- (A) + (CY) +data Example 9. ADDC A, #39H

ADDC A, @Ri with Carry) (Add indirectRAM to accumulator

of carry flag andthe datain with the contents are added of the accumulator The contents RAM locationpointedby Ri. Thentheresultis storedin accumulator. (A) <- (A) + (cY) +((Ri)) Example 10. ADDC A, @Rl

AJMP addr (AbsoluteJump)

The unconditionally. to the targetaddress execution theprogram The instructiontransfers program memory' for this instructionmustbe within 2K bytesof targetaddress Example 11. AJMP LOOP 1

ANL A, Rn (AND Register to Accumulator)

and theregisterandaccumulator between This performs thebitwiselogicalAND operation stores theresultin accumulator. Example ANL A, R4 (A) :) 23H 00100011 05H 00000101 0 0 0 00 0 0 1 in theaccumulator TheresultOlH is stored 12. ANL A, direct (AND directbyte to Accumulator)
5.29

(R4) :)

Miqocontrollers

This performsthebitwiselogicalAND operation between thedirectbyte andtheaccumulator andstores theresultin accumulator. Example ANL A, 20H

The datain RAM location20H is ANDed with the contents of the accumulator and the resultis'stored in accumulator. 13. AflL A, @Ri (AND indirectRAM to Accumulator) This performs thebitwiselogicalAND operation between theRAM locationpointedto by Ri andthe accumulator andstores theresultin accumulator. Example 14. ANL A, @ R0 ANL A, #data (AND immediate datato Accumulator) This performsthe bitwise logicalAND operation between the givendataandthe contents of accumulator and stores theresultin accumulator. Example ANL A, # 44H (A) :+ 17H 00010111 MH 0 1 0 00 1 0 0

0 0 0 00 1 0 0 : 0 4 H
15. ANL direct,A (AND accumulator to directbyte) This performsthe bitwiselogicalAND operation between the datain RAM locationand thecontents of accumulator andstores theresultin thedestination RAM location.Theaccumulator content remains same. Example (A) (A) ANL l8H, A =) + 45H = 01000101 l0l00tll

A7H +

0 0 0 00 1 0 1: 0 5 H
After theexecution of this instruction thelocationl8H contains 05H andtheaccumulator content (45H). remains same 16. ANL direct, # data (AND immediate datato directbyte) This performsthe bitwiselogicalAND operation between the datain RAM locationand givendataandstores the resultin destination RAM location. Example ANL 44H, #32H
Mictoprocessors and Microcontrollers

( 4 4 H )+ data +

50H 32H

+ +

01010000 00110010

0 0 0 10 0 0 0 : l O H
theresult lOH' Now the location44H contains I7. AI\L C, bit (AND directbit to carry) bit andtheresultis placedin carryflag. The carry flag is ANDed with a source

Ifsource': :: I il: ::T::".hanged


Example 18. ANL C, ANL C, PZ.l Ibit

of directbit to carry) (AND complement bit andthe resultis placedin of the source The carry flag is ANDed with the complement carryflag. Example 19. CJIYEA, ANL C, lPz.l direct, rel

andJumpif Not Equal) (Compare directbyte to accumulator byte of the sourcebyte and destination the magnitudes This instructioncompares (accumulator). If they arenot equal,it jumps to the targetaddress' Example CJNE A, 3lH, LOOP andlocation3lH arecompared.If they arenot equal,thenit of accumulator The contents jumpsto labelLOOP. 20. CJNE A, # data, rel andJumpif Not Equal) (Compare datato accumulator immediate If they arenot of accumulator. the givendataandthe contents This instructioncompares equal,it jumps to the targetaddress. Example CJNE A, #15H,LOOP For example, (Acc): 50H data :15H jump to (50H) is not equalto the givendata(l5H). Therefore The contentof accumulator labelLOOP. the specified 21. CJI\"ERn, # data, rel andJumpif Not Equal) (Compare datato accumulator immediate
Micr:ocontrollers 5.31

data. If they are not equal,it with the immediate of regiserare compared The contents jumpsto the targetaddress. Example CJNE R5, # 33H,LOOP ofR5 is 20H,it is not equalto thegivendata33H. Thentheinstructionjumps If thecontent LOOP. label to the dpecified 22. CJNE @Ri, # data, rel (Compare datato indirectRAM andJumpif Not Equal) immediate with the givendata. If of the memorylocationpointedby Ri arecompared The contents theyarenot equal,it jumps to the targetaddress. Example CJNE @R0, # 18H,LOOP R0 = 28 H For example, 28H = 55H Location

with thegivendata(l8H). They location 28H (55H)is compared Thecontent of memory jump to specified labelLOOP. arenot equal,therefore 23. CLR A (ClearAccumulator) aresetto 0. i.e.,all bits of theaccumulator is cleared, Theaccumulator A +-0 24. CLRC (ClearCarry flag) i.e.,resetto zero. The carryflag is cleared

(c) <-0
25. CLR bit (Clear directbit) location. This instructionclearsa singlebit. Thebit maybe anybit - addressable (bit) +-0 Example: 26. CPLA (Complement Accumulator) 0's. I's and I's become arecomplemented 0's become Thecontents of theaccumulator (A) <- (A) (A) = I I I I 0000 ( A ) + 0 0 0 0l l l l 5.32
Miooprocessorc and Microcontrolters

CLR CLR

P1.4 ACC.5

27.

CPL bit (Complement directbit)

bit. Thebit canbe thecarryflag or any of a single thecontent complements This instruction location. bit - addr.essable Example CPL CPL 28. DA A C P2.6

(DecimalAdj ust Accumulator) from a binaryvalueto two 4 bit binary-codedarechanged of theaccumulator Thecontents is four bits (D3- Do) in the accumulator low order of the (BCD) value digits. If the decimal (06) four bits. to the low order adds greater than9 or if AC flag is set,the instruction than9, or if is greater If the valueof the high orderfour bits (D7 - D4) in the accumulator thecarryflag is set,the instnrctionadds(60) to the high orderfour bits. Example MOV A, ADD DAA (A) + 3 9 r . o: * 1 2 " . o: 5 1 " . o= 00111001 00010010 0100 1011 +4BH A. # 39H # I2H

Thebinarysumis 48 H. The valueof the low orderfour bits is largerthan9. Therefore add06 to the low orderfour bits. : 0 1 0 0l 0 l l 4B + 06 00000110 0 1 0 1 0 0 0 1+ 5 1 39 + 12: 5l 29, DEC A (DecimalAccumulator) is decremented bv I of the accumulator The contents (A) +- (A) - I A
Before execution : 30. DEC Rn

(Result in BCD).

A : After executron

@
5.33

(Decrement Register)
Microcontrollers

This instruction decrementsI from the content of the reeister.

(Rn)-(Rn)-l Example DEC R2

R2
Before execution : 31. DEC direct (Decrement direct byte)

R2
After execution :

This instmction decrementsI from the content of the location. Example

D E CI I H ltH
llH

Before execution : 32. DEC @Ri

After execution :

(Decrement indirectRAM) This instructiondecrements I from thecontentin locationpointedto by Ri. Example

DEC@R0

((R0)) <- ((R0)) - I 33. DIV AB (DivideA by B) This instructiondividesthe content of accumulator by thecontentof registerB. After the divisionthe quotientwill be in accumulator andtheremainder in registerB. Example DIV AB Beforeexecution After execution

DJNZ Rn, rel (Decrement registerandJumpif Not Zero) This instructiondecrements I from the contentof registerR0 to R7. If the contentis not zero,it will jump to thetarget address. Example DJNZ R3. LOOP 35. DJNZ direct,rel (Decrement directbyte andJumpif not zero) This instruction decrements I from thecontent of givenlocation. If thecontentis not zero, it will jump to thetarget address"
5.34 Microprrcessorsand Microconffollers

34.

Example 36.INCA

DJNZ l8H,

LOOP

(Increment Accumulator) of accumulator. I to the content This instructionincrements (A) <- (A) + I
A

: Beforeexecution 37.INCRn

: [iElE.| Afterexecution

(Increment Register) of register. I to the content increments This instruction (Rn) +- (Rn) + I Example INC R3 R3 Beforeexecution, 38.INC direct (Increment directbYte) of the location. I to the content increments This instruction Example INC Fl H E6-g-l After Execution:

R3

FIH ' execution Before 39.rNC @Ri


(Increment indirectRAM)

FlH

ljonl

: AfterExecution

of RAM locationpointedto by Ri. I to the content This instructionincrements Example INC @R0 (R0)) e(R0))+ I

thedata 47 H andtheinternalmemorylocation47H contains thepointerR0 contains For example, t2H. 47H , Beforeexecution 40.INC DPTR (Increment DataPointer) the datapointerby l. increments This instruction
Microcontrollers

47H After Execution:

FZftl

5.35

(DPTR) <- (DPTR)+ l


Before execution : DPH DPL

After Execution : DPH DPL

4f . JB bit, rel (Jumpif directBit is set) If thegivenbit is l(set),it will jump to atarget address. Example: JB JB 42. JNB bit, rel (Jumpif directBit is Not set) If thegivenbit is 0, it will jump to a target address. Example: JNB JNB 43.JC rel (Jumpif Carryis set) If thecarryflag is I (set),it will jump to a targetaddress. Example 44.JNC rel (Jumpif Carry is Not Set) If the carryflag is 0, it will jump to a targetaddress. Example: 45. JBC bit, rel (Jumpif directBit is set& Clearbit) If thegivenbit is I (set),it will jump to thetargetaddress while at the same time thebit is cleared to zero. Example: 46.JZ rel (Jumpif accumulator is Zero) jumps to the targetaddress, This instruction if all bits of the Examplez JZ LOOPI
and Mirroffiolirrx Mirrroprocessors

Acc.O. LOOP PI.5. LOOP

Acc.Z, LOOPI P2.2. LOOP2

JC

LOOPI

JNC

LOOP2

JBC

Acc.S. LOOP

accumulator arezero.

s.36

47. JNZ rel (Jumpif accumulator is Not Zero) jumps to the targetaddress, This instruction if all bits of the accumulator havea value otherthanzero. Example JNZ LOOP?

48.JMP @A+ DPTR (Jumpindirectrelativeaddress to theDPTR) jump to a targetaddress.The contents This instructionis an unconditional of the accumulator areadded with thecontents of thedatapointerandthetotal sumis thetargetaddress. (PC) <- (A) + (DPrR) 49.LCALL addr (LongSubroutine Call) It is a 3 byteinstruction.The first byteis theopcode andtheothertwo bytesarethe 16bit address of the targetsubroutine.The targetaddress is within 2K bytesof the programcounter. Thesubroutine maybeanywhere in 64K byteprogram memory address space. Thelastinstruction of subroutine mustbe RET. Example: LCALL LOOP1

50.LJMP addr (LongJump) It is a 3 byte instruction.The first byteis theopcode andthenext two bytesarethe l6 bit address of the targetaddress.It is usedto jump to any address location within the 64K bvte address space.It will not returnaslike LCALL instruction. Example: LJMP LOOP2

51.MOV A, Rn (Move registerto Accumulator) Move datafrom source location(register) to destination location(accumulator). (A) <- (Rn) Example MOV A, R4 -

52.MOV A, direct (Move directbyte to Accumulator) Move the datafrom source location(directbyte)to destination location(Accumulator). (A) <- (directbyte)
Mlqocontrollerc 5.37

Example:

MOV A, 18H A l8H

53. MOV A, @Ri (Move indirectRAM to accumulator) Move datafrom source location(pointedto by Ri) to thedestination location(accumulator). A <- (Ri)) Example MOV A, @R0 R0 e 22H

For example

54.MOV A. # data (Move immediate datato Accumulator) Move the givendatato the accumulator. (A) <-data Example MOV A, # FA H. (Move Accumulator to Register) Movethedatafrom source (accumulator) location (Register'n'). to destination location (Rn)<- (A) Example: MOV R3, A

55.MOV Rn, A

56.MOV Rn, direct (Move directbye to Register) 'n'). Movethedatafrom source location(directbye) to destination location(Register (Rn) <- (directbyte)

5.38

Microprocessors and Microcontrollerc

Example:

MOV R4, 18H R4 18H.

57.MOV Rn, # data datato register) (Move immediate register' Move the given datato the destination (Rn) <- data Example: MOV R5,# E2H

58.MOV direct' A to directbYte) (Move Accumulator Movethedatafromsourcelocation(accumulator)todestinationlocation(directbyte). (directbYte) <- (accumulator) Example MOV l2H, A IzH A

59. MOV direct, Rn (Move registerto directbYte) location(directbyte)' to destination location(register) Move thedatafrom source (directbYte) <- (Rn) Example MOV 4AH, R6 4AH R6

60.MOV direct,direct (Move directbYteto directbYte) directbyte' directbyte to destination Move the datafrom source (directbYte) <- (directbYte) MOV AAH, BB H Example

5.39
MicrocpRtrollers

61.I\fOV direct,@Ri (Move indirectRAM to directbyte) Move the datafrom the locationpointedby Ri to the destination (directbyte) - ((Ri)) Example MOV Al H, @R0 location(directbyte).

For example, R0 + 37 H AIH 37H

62.MOV direct,#data (Move immediate datato directbyte) Move the givendatato destination location(directbyte) (directbyte) +-- data Example MOV B.2,#77H 63. MOV @Ri, A (Move accumulator to indirectRAM) Move the datafrom accumulator to an indirectaddress heldbv R0 or Rl. ((Ri)) <- (A) Example MOV @Rl, A

64.MOV @Ri, direct (Move directbyte to indirectRAM) Move the data from sourcelocation (direct byte) to destination location,which is an indirect address heldby R0 or Rl. ((Ri)) <- (directbyte) Example
5.40

MOV @R0,15H
Microprocessors ond Misocontrollers

For example R0 contains D4 H

D4H

n l

15H

65.MOV @Ri, #data (Move immediate datato indirectRAM) held by R0 or location,which is an indirect address Move the given datato destination Rl. ((Ri)) <- data Example MOV @P.l,#75H E7 H Rl contains For example, The data75 H is loadedinto the intemalmemorylocationE7 H. 66.MOV C, bit (Movedirectbit to carry) of bit is copiedinto carryflag. Thecontent

cY <- (bio
Example MOV C,P2.5

67.MOV bit. C (Move carryto directbit) bit location. into the specified Thecontent of carryflag (l or 0) is copied

(biD<- cY
Example

MOVP|.2,C
7 6 5 4 2 1 0

68.MOV DPTR, # data


(Load datapointer with a l6 bit content) The l6 bit datapointer registeris loadedwith a l6 bit immediatevalue" (DPTR) <- 16 bit data
Microcontrollers

5.41

Exampfe

MOV DPTR,#1234H

After execution :

'

69.MOV A, @A+ DPTR

DPH

DPL

(Move code byte relative to DpTR to accumulator) This instruction moves a byte of data located in the program (code) area to accumulator. The addressof the desired byte in onchip RoM is formed by adding the DprR to the content of the accumulator.

(A) +- ((A) + (DPrR))


This instruction allowsto put shings of datasuchaslook - up tableelements in thecode space (on - chip ROM) andreadtheminto theCpU. 70.MOV A, @A + PC (Move codebyterelativeto pC to accumulator) This instruction moves a byteof datalocated in thecodeareato accumulator. Theaddress of thedesired byte of datais formedby addingtheprogram counterregisterto the contentof the accumulator. (A) <- ((A) + (PC))

7r.Mov x A, @Ri
(Moveextemal RAM (g bit address) to accumulator) This instruction moves a byteof datafromexternal memory whoseg bit address is pointed to by R0 or Rl into theaccumulator. (A) <- ((Ri)) Examples: MOVX A, @R0 MOVX A, @Rl 72.MOVXA, @DPTR (Moveextemal RAM (16 bit address) to accumulator) Thisinstruction moves a bytefromexternal memory whosel6 bit address is pointed to by DPTRinto theaccumulator. (A) <- (DPrR)) 73.MOVX, @Ri, A (Moveaccumulator ro external RAM (g bit address)) This instructionmovesa byte from the accumulator to an extemalmemorywhoseg bit address is pointed to by R0 or Rl. ((Ri)) e (A)
5.42
Microprocessors and Misoconffollers

Exemples:

MOVX @R0,A MOVX @R1,A

74. MOVX, @DPT& A (Morreaccumulator RAM (16 bit address)) to external is copiedinto any locationof 64K in Using this instruction,the contentof accumulator memorypointedby DPTRregister. external ((DPrR)) <- (A) 75.MUL AB (Multiply A & B) andthe B register by thecontent.of of accumulator multipliesthecontent This instruction resultis storedin A andB. A hasthe lower byteandB hasthe higherbyte. Exemple : MUL AB Beforeexecution After execution

il
25H 76. NOP

E]
78H

ilE
llH 58H

2 5 H x 7 8H = l l 5 8 H .

(No operation) performs with thenextinstruction. continuous This instruction no operation andexecution It is usedfor timing delaysto wasteclock cycles. 77. ORL A, Rn (OR registerto accumulator) This performsthe bitwise logical OR operationbetweenthe contentsof registerand the resultin accumulator. accumulator andstores Exernple: ORL A, R3 1 0 0 01 1 1 1 01110101 l11l 1ll1:FFH The resultFF H is storedin the accumulator.

(A)=8FH+ (R3)=+75H-

Microontrollers

5.43

78.ORL A, direct (OR directbyte to accumulator) of directbyte and the contents between This performsthe bitwise logical OR operation theresultin accumulator. andstores theaccumulator Example: ORL A, 78 H (A) +0FH> 0000 ll11 01010101 0l0l llll=5FH Theresult5F H is storedin the accumulator. 79. ORL A, @Ri (OR directRAM to accumulator) the RAM locationpointedto by between This performsthebitwiselogicalOR operation theresultin accumulator. andstores Ri andthe accumulator Example: ORL A, @R0

(7BH)-55H=

80.ORL A, # data (OR immediate datato accumulator) between the given dataandthe contents This performsthe bitrviselogicalOR operation theresultin accumulator. of accumulator andstores Example: ORL A, B0 H (A) 3 A r {= I 010 10l0 10110000 l01l1010:BAH The resultBA H is storedin accumulator. 8f . ORL direct,A (OR accumulator to directbyte) This instructionperformsthe bitwise logical OR operationbetweenthe data in RAM RAM location. locationandthe contents of accumulator. The resultis storedin the destination The accumulator contentremainssame. Example: ORL C2H, A 0l0l l0l0 (c2H)=5AI{+ (A) =+OBH=

BOH +80+

0000 l01l 0101l01l:5BH

After execution of this instruction the locationC2 H contains theresult58 H.


5.44 Micr oprocessorsand Micr. rcontr ollers

82.ORL direct,# data (OR immediate datato directbYte) This instructionperformsthe bitrviselogical OR operationbetweenthe datain RAM RAM location. theresultin destination locationandgivendataand stores Example: ORL 18H, # 18H ( l 8 H )+ 7 0 H + 18H+ 01110000 00011000 0lll1000=78H of 70 H. in thelocation18H instead Theresult78 H is stored 83.POP direct (POPdirectbyte from stack) byte This instructioncopiesthe datapointedto by stackpointerto the directly addressed stackpointerby 1. indicated anddecrements (directbyte) <- ((SP)

(sP)+- (sP)- l
Example POP 03 84.PUSHdirect (Pushdirectbyteonto stack) byte onto the stackpointer and . This instructioncopiesthe indicateddirect addressed increments the stackpointerby l. (SP)) <- (directbyte)

-.

+1 (sP)<-(sP)
Example 85.RET (Returnfrom subroutine) previouslyenteredby CALL This instructionis used to return from a subroutine continues at into PC andprogramexecution instructions.The top two bytesof stackarepopped by two. this new address.After poppingthe stackpointeris decremented 86. RETI (Return from Intemrpt) This instructionis usedat the endof an ISR. The top two bytesof the stackarepopped After popping, theSPis decremented at thisnewaddress. execution continues intoPCandprogram 2. bv
Micy.rontrollqs

PUSH 03

5.45

87. RL A left) (Rotate accumulator is rotatedleft by oneposition. MSB is placedin the Eachbinarybit of the accumulator position.of LSB. Example (A) MSB I RLA I 0 I D2H LSB

Beforeexecution

:D2H

After Execution MSB


I

LSB I 0

:A5H

88.RLC A (Rotateaccumulator left throughcarry) is rotatedleft by onepositionthroughthe carryflag. Eachbinarybit of the'accumulator MSB is placedin the carry flag andthe carryflag is placedin LSB. Example Before execution (A) A7H
= CY

(c)

0 ACC I

tr
RLC A After Execution

0 l r l 0 l 0 I

l ll

tr
5.46

CY

ACC 0 0

and Misocontrollers Microprocessors

89.RR A right) (RotateAccumulator right by oneposition. The LSB is placedin is rotated Eachbinarybit of the accumulator of MSB. theposition Example Beforeexecution MSB (A)+ 33H RRA LSB

0l0l I ll lo lo ll ll

After Execution MSB LSB l l 0 l 0 | I I I l 0 l 0 | I :99 H

90. RRC A (RotateAccumulatorRrghtthroughCarrl') right by onepositionthroughthe carryflag. is rotated Eachbinarybit of the accumulator placed in MSB. flag is the carry LSB is placedin the carry flag and Example Beforeexecution (A) + + A7H 0 ACC I RRC A
MSB LSB

(c)
0

CY
I
I

After Execution ACC 0 l l l 0 l l l 0 l 0 l l l l


Microantrollqs

CY

tr
5.47

(A):53H

(c):t
9I. SET B bit ' (SetdirectBit) Oit) * t Examples SETB Acc. 5 SETB P2.2 92.SETB C (SetCarry) This instructionsetsthe carryflag to I (HIGH) level. (C)*t 93. SJMP rel (ShortJump) byte is the This is a two byte instruction. The first byte is the opcodeand the second which is added numberdisplacement, to the PC of the instructionfollowing the SJMPto signed getthetarget address (-128to + 127), Example SJMP LOOP bit to logic I level (HIGH). This instructionsetsthe indicated

94. SUBB A, Rn (Subtract with Borrow) Register from Accumulator This instructionsubtracts of the contents of registerandthe carry flag from the contents accumulator andstores theresultin the accumulator. (A) <- (A) - (Rn) - (C) Example SIIBB A, A 95.SUBB A, direct (Subtract directbyte from Accumulator with Borrow) This instructionsubtracts the contents of memorylocationand the carry flag from the accumulator andstores theresultin accumulator. (A) <-(A) - (directbyte)- (C) Example: s.48 SUBB A, 65 H
Mirrroprocessors and Misocontrolbrs

R4 R 4

tr

E q - E -tr
96. SUBB A, @Ri

65H

CY

with Borrow) (Subtract indirectRAM from Accumulator thedatain RAM locationpointedto by R0 or Rl andthecarry This instructionsubffacts theresultin accumulator' andstores of accumulator flag from the contents (A) <-(A) - ((Ri)) - (c) Example SUBB A, @R0 CY
A

R0 register = 58 H For example, A 58H

@ - @ 97.SUBB A, #data

tr

with Borrow) datafrom Accumulator (Subtract immediate and the given dataand the carry flag from the accumulator This instructionsubtracts theresultin accumulator. stores (A) <-(A) - data- (C) Example SUBB A,
A

# 4lH CY
A

lffil - +tH -E]


98. SWAP A

(Swap within theAccumulator) nibbles the lowernibble(D0 - D3) with the uppernibble (D4 - D7) This instructioninterchanges rnside the accumulator. (A3 - A0) <-r (A7 - Aa) Example Beforeexecution A-42H After execution A+24H = 00100100 _ = 01000010

Microconrollers

5.49

99. XCH A, R3 (Exchange registerwith Accumulator) Rn. of register with the contents of accumulator the contents This instructionexchanges ' Example (A) <+ (Rn) XCH A, R3 After execution A

Before execution

R3
l:l I:J

E E
100.XCH A, direct

(Exchange direct by1 direct byte with Accumulator) change

of accumulator. of directbytewith the contents the contents This instructionexchanges (A) e (directbyte) Example XCH A, 38 H After execution A

Before execution

3BH

3BH

E @

tr

l0l. xcH A, @Ri (Exchange RAM withAccumulator) indirect


This instructionexchanges the datain RAM locationpointedto by R0 or Rl with the accumulator. (A) ++ ((Ri)) Example: XCH A, @R0

Forexample, R0 + 4A H Beforeexecution A 4A H After execution A 4A H

E
102. xcHD A, @Ri

tr

(Exchange low orderdigits indirectRAM with accumulator) This instruction exchanges only thelowernibble(D0 - D3) of accumulator with thelower nibbleof the RAM locationpointedto by Ri. Example: XCH A, @R0

R0 + l8 H (RAM location)
5.50 Micrr oprocessors ond Miqwntollers

Beforeexecution 18H+01011111:5F A +10100000:A0

After execution l 8 H+ 0 1 0 1 0 0 0 0 : 5 0 A 103.XRL A, Rn - OR registerto accumulator) (Exclusive andaccumulator theregister between bitwiselogicalEX - OR operation performs This instruction theresultin accumulator. andstores Example: XRL A, R2 01010101 l l l l lolt TheresultBA H is storedin the accumulator. 104.XRL A, direct (EX - OR directbyte Accumulator) This instructionperformsbitwise logical EX - OR operationbetweenthe direct byte and the accumulator. the resultin andstores accumulator Example: XRL A, 18H = : 00010000 01000011 0l0l00ll:53H Theresult53 H is storedin the accumulator. 105.xRL A, @Ri (EX - OR indirectRAM to Accumulator) the RAM locationpointedto by between performs thebitwiseEX - OR operation This instruction theresultin accumulator. andstores R0 or Rl andthe accumulator Example: XRL xRL A, A, @R0 @Rl l l l l tolo=BAH (A)=45H = A = F F H : =l010l1ll =AF

(A) +10H ( l 8 H )+ 4 3 H

Micr:oantrollqs

5.51

106.XRL A, # data (EX - OR immediate datato Accumulator) between the givendata This instructionperformsthebitwise logicalEX - OR operation andtheaccumulator and stores theresultin accumulator. Example: (A) XRL A, #55H = = 00100111 01010101 =72H 01110010 Theresult72H is stored in Accumulator. 107.XRL direct,A (Ex - OR Accumulator to dlrectbyte) performs This instruction thebitrviselogicalEX - OR operation between thedatain RAM locationandthe contents of accumulator RAM location. and stores the resultin the destination Theaccumulator contentremains same. Example: XRL 32 H. A (A) +l8H: = >4 4 A : (32H) 00011000 0100 0100 01011100=5CH 108.XRL direct.# data (EX - OR immediate datato directbyte) This performsthe bitwiselogicalEX - OR operation between the datain RAM location andgivendataandstores the resultin destination RAM location. Example: XRL 55H, #FFH : = 0lll000l llll llll 1 0 0 0l l l 0 = 8 E H =+7lH (55H) d a t a= F F H

+27H 55H

Theresult8EH is stored in location 55H. 5.8 INTERRUPTS An intemrptis an internalor extemaleventthat intemrpts the microcontroller to inform it that a deviceneeds its service. Whenever any deviceneeds its service, the devicenotifiesthe microcontroller by sendingit an interruptsignal. Upon receivingan interrupt signal,the microcontrollerinterruptswhateverit is doing and servesthe device.The programwhich is
25

5.52

Miooprocessors and Misocontrollers

can Routine(ISR).The microcontroller with the intemrpt is calledinterruptService associated to it' on thepriorityassigned based manydevices serve of an InterruPt 5.8.1 Execution mustbe taken. ln orderto useany interrupt,the following steps (PC) of thenextinstruction theaddress andsaves it is executing theinstruction It finishes l. on the stack.

2. 3.
4.

internally. ofall the interrupts the currentstatus It alsosaves the It jumps to a fixed locationin memorycalledthe interruptvector or table that holds Routine[SR)' of the InterruptService address of theISR fromtheintemrptvectortableandjumpsto getstheaddress Themicrocontroller of the lastinstruction until it reaches subroutine the intemrptservice to execute it. It starts which is RET I. the subroutine returnsto the placewhereit was the microcontroller RET I instruction, Upon executing from the stackby poppingthe intemrpted.First it getsthe programcounter(PC) address from that address. top two byes of the stackinto thePC. Thenit startsto execute

5.

MainProgram

CallISR

Fig. 5. l0 Interrupt slructure

Microcontrollers

5.53

5.8.2 Interruptsin 8051 by internaloperations: Five interrupts areprovidedin the 805l. Threeofthesearegenerated Timer flag I and the serialport intemrpt (RI or TI). Two intemrptsare triggeredby external signalsprovidedbycircuitrythatisconnectedtopins nfTQ andINTI (portpinsP3.2andP3.3). Table33.1Interrupt Vector l}pes lnternal Interrupts TFO Timer flag 0 intemrpt TF1 Timer flag I intemrpt RYTI Serialport intemrpt
Extemal Vector address

OOOB H OOIB H 0023H 0003H 0013 H

Itrn0 Externalintemrpt0 rNT' Extemalinterrupt1

a)

Timer flag interrupts

When a timer / counteroverflows,the corresponding timer flag TFOor TFI (location: a intemrptgenerates 0008 H or 0018 H) is setto l. The flag is cleared to 0 whentheresulting program call to the appropriate timer subroutine in memory. (b) Externalinterrupts

Theexternal hardware interrupts INTOandINT I arelocated onpinsP3.2andP3.3.Inputs pinscansettheintemrptflagsIEOandIEI in theTCONregister on these to I by leveltriggering of or edge triggering.Fig 5.I I shows theactivation the activation of INTO andFig. 5.I 2 shows INTT. Leveltriggered

INTO

Edgetriggered

Fig. 5.ll Activation of INTO

5.54

and Microcontrollers Microprocessors

Levetriggered

INTl

Edgetriggered

Fig. 5.12Activationof INTI

(c)

SerialPort Interrupt In SCON,if RI = l, TI : 1,

a databyte is received a databytehasbeentransmitted.

to providea singleintemrptto the processor. These areORedtogether data.If IE.4 [ES- Enable is used to bothsendandreceive Theintemrptbit in theIE register whenRJor TI is raisedand 8051getsintemrptedandjumps to serialport intemrptl is enabled, the serialintemrptis H theISR. TheFig. 5.13shows location 0023 to execute memory address invokeby TI or RI flags.
TI

Fig.5.l3

Serial Port Interrupt

5.8.3 InterruptControl is ableto All intemrpt functionsare underthe control of the program. The programmer altercontrolbits in the (IE) InterruptEnableRegister (IP) and IntemrptPriority Register (TCON). TimerControlRegister 5.8.3.1 Interrupt EnableRegister(IE) The IE registerholdstheprogrammble bits thatcanenable or disableall the intemrpts.
Misocontrollers 5.55

Bit D7 of theIE register (EA) mustbe sethighto allow therestof theregister to takeeffect. IfEA: l, intemrpts areenabled andwill beresponded to if theircorrespondingbits in IE arehigh. If EA :0, no intem:ptwill be responded to, evenif theassociated bit in theEl register is high. TheFig. 5.14shows thebits in theIntemrpt (IE) register. Enable D6 is unused. D5 [ET2] is used ohly by the8052. IE is bit addressable. D7 EA D6 D5 D4 ES D3 ETl D2 EXI Dl ETO DO EXO

Fig.5.l4lE Register

EA Enable intemrptbits. Setto I to permitindividual intemrpts to be enabled by their enable bits. Cleared to 0 by programto disableall intemrpts. ES Enableserialport intemrpt. Setto I to enable by program. Cleared to 0 to disableserialport intem.rpt. ETI Enable / disable theTimer I overflowintemrpt. EXI Enable extemal intemrptl. Setto I by programto enableffi intenupt.

Cleaied to 0 to disablefNTl int"*rpt. ETO Enable / disablethe Timer 0 overflowinterrupt. EXO Enable / disable theextemal intemrpt 0. Setto I by programto enableffi interrupt.

Cleared to 0 to disableINT0 intemrpt.

5.56

Microprocessors and Microcontrollers

5.8.3.2Interrupt Priority Register(IP) setto 1 the interruptpriority. Bits in IP registers determines Intemrptpriority (IP) register a lorv priority' Intemrptswith a high ittt.ttupt a high priority,a 0 assigns givethe accompanyln! after intemrptwith a lowerpriority andthelowerpriority continues priority capintimrpt alnother they then priority occurat the sametime, with the same it. njn"r'i. finished. If two interrupts havethe following ranking: I. IEO

2. TFO 3. IE1 4. TFI 5. RI/TI intemrpts I 5. If thebit is 0, thecorresponding in Fig.5. is shown IP register Thebit addressable priority' higher hasa lower priority, otherwise
7 6 5 4

0 interruPt External priority level level 0 interrupt Timer Priority level 1 priority interrupt External level 1 interrupt Timer Priority priority port level Serial interrupt
Fig.5.l5 IP Register

5.9 8051PROGRAMS l. 8 bit Addition


oRG 8000H CLR MOV ADD MOV MOVX LCALL Data : Sample Data I : Data2:
Micr.oantrollers

C A, # DataI A,#Data2 H DPTR, # 9OOO A @DPTR, OOBBH


; Break Point

03H 04H s.57

2. l6 Bit Addition

H oRG 8000
CLR MOV ADDC MOV MOVX INC MOV ADDC MOVX HLT: SJMP Sample Data : Data I : Data2: A1B2H 1573 H C A, # MSD of DataI A, # MSD of Data2 H DPTR,# 9OOO @DPTR,A DPTR A, # LSD of dataI A, # LSD of data2 A @DPTR, HLT

3.8 Bit Subtraction oRG 8000H CLR MOV SUBB MOV MOVX HLT:SJMP C A, # DataI A,#Data2 H DPTR,# 9OOO A @DPTR, HLT

4.8 Bit Multiplication

H oRG 8000
MOV MOV MUL MOV MOVX INC MOV MOVX HLT:SJMP A , # D a t aI B #Data2 AB H DPTR, # 9OOO A @DPTR, DPTR A,B A @DPTR, HLT

5.58

Microprocessors and Microcontrollers

5.8 Bit Division oRG 8000H MOV MOV DtV MOV MOVX INC MOV MOVX HLT:SJMP 6. BCD Addition oRG 8000H ; LoadPointer MOV R2, # OAH ; LoadCounter CLR A LOOP2 : ADD A, @PR0 D A A INC LOOPI INC R7 LOOPI: INC R0 DJNZR2,LOOP2 7. Sumof the Elements in an Array oRG 8000H MOV DPTR,#8500H MOV A, @DPTR MOV RO,A MOV B, #O MOV RI, B LOOP 1: CLR C MOVXA,@DPTR ADD A, B MOV B, A TNC LOOP2 INC RI
Microcontrollers

A, # DataI B,#Data2 AB DPTR, # 9OOO H @DPTR,A DPTR A,B A @DPTR, HLT

MOV R0,#50H

5.59

LOOP2 :

INC DJNZ MOV MOV MOVX INC MOV MOVX

DPTR RO, LOOP1 DPTR,#9OOO A, RI A @DPTR, DPTR A. B @DPTR,A HLT

HLT:

SJMP

at 8501H. Thearraystarts in the array. thenumberof elements location8500H contains The address at 9000Hand9001H. Theresultis to be stored Sample Data H] [8500 H] [8501 H] [8502 H] [8503 H] [8504 H] [850s = : : = : 05 H 0A H 0B H 0C H 0D H oE H

8. Ascending Order oRG 8000H

MOV R0, #Data MOV Rl, #Data MOV A, SUBB JNC MOV MOV HLT: SJMP RO A, RI HLT A, RO R2, A HLT

9. ASCII To DecimalConversion

oRG 8000 H MOV MOVX s.60 DPTR.# 9OOO H A. # Data


Micr oprocessors and Micro conffollers

CLR SUBB JC MOV SJMP LOOP1: LOOP2: HLT : ADD MOVX SJMP

C A, # OA LOOP 1 A, # OFF LOOP2 A, # 0A @DPTR'A HLT

30 from it' to decimalby subtracting Any ASCII numbercanbe converted Data Sample DATA= 31 Result[9000]= 01 If the decimalnumbergot is not a valid one;FF will be storedas a result to indicatethe
elTor.

10.HEX to DecimalConversion oRG 8000H MOV MOVX MOV DTV MOV MOVX MOV MOV DIV INC MOVX INC MOV MOVX HLT:SJMP H DPTR, # 9OOO A, @DPTR B,# 64 AB DPTR,#9001 @DPTR,A A,B B,#OA AB DPTR @DPTR DPTR A,B @DPTR,A HLT

Mitocontrollers

5.61

5.10 MICROCONTROLLER APPLICATIONS aregivenasfollowing': of microcontrollers of theapplications A few examples l. Buildingcontrol Access control - Temperature control - Lighting - Fire detection 2. Industrialcontrol - Process control 3. control Motor speed - AC motorcontrol - DC motors - Stepper motors 4. HandheldInstruments - Handheld thermometer Digital levelmeter - IC tester - Electronic planimeter - High performance talkingmultimeter - Wind speed / Temperature meter - Numericdisplay pager radio 5. Peripheral devices - Keyboard controller - Printerbuffer - Colourplotters - Modem 6. Standalonedevices - Colourxeroxmachine - Fishfinder - Lawn sprinkler - CableT.V.terminal - Charge - cardphones 7. Instrument sub functions - Digitaloscilloscope - Spectrum analyzer
5.62 Microprocessors and Microcontrollers

- Microwavecounter - High performance multimedia - Touchsensitive LCD 8. Automobileapplications - Electronicpowersteering - Collisionavoidance system - Multiplexedwiring system - Transmission controller - Electronicinstrument panel - Electronicentryandsecuritysystem 9. HomeAppliances - Securitysystem - Washing machine - CableTV tuner - Remote control - Intercom - Cellularphone - TV VCR - Sewing machine - Light control - Paging, videogames etc. camera, 10.Office - Fax machine - Xerox machine - Telephones - Computers - Laserprinters - Colourprinter - Securitysystems : now we will discuss aboutonly threeimportantapplications In theseapplications, (i) Analog- to - Digital Converter (ii) Frequency counter (iii) Sequentialcontroller - to - Digital Conversion using8051 5.10.1Analog so that themicrocontroller ADCs areusedto convertthe analogsignals to digital numbers canreadthem.Analogto digitalconversion is shown in figure5.16.
Mioocontrollers 5.63

Analog quantities (Temp.pressureetc.)

Transducer

Signalconditioning

ADC

Microcontroller

Fig. 5. I 6 Analog - to- digital conversiott

ADC fiike ADC 804 IC] works with +5 volts and has a resolution of 8 bits. Conversion time is defined as the time taken to convert the analog input to digital (binary) number. The conversiontime varies dependingupon the clock signals;it cannotbe fasterthan 110ps . * * * * Analog input is given to the pins Vi" (+) and V," (-). V,n(-) is connectedto ground. Digital output prns are Do - Dr. D, is the MSB and Do is the LSB. There are two pins for ground, analog ground and digital ground. Analog ground is connected to the ground of the analog V." and digital ground is connected to the ground of the V.. pin.

at

WR Do-D7 | r |
t

Dataour I :__
l

INTR RD
I

t Read il Fig. 5.17 Read and Write timing

5.64

Microprocessors and Misocontrollers

The followrng stepsare followed for data converslon : 1. 2. 3. Makechipselect(CS )=0andsendalow-to-highpulsetopinWR tostarttheconversion. is finishedand go to thenext Keep monitoring the INTR pin. If INTR is low, the conversion goes low. step.If INTR is high, keep polling until it After the INTR hasbecomelow, we make f$ = 0 and senda high- toJow pulse to the RD pin to get the data out. The timing for this processis shown in figure 5.17. with ADC is shown in figure 5.18. The clock in for The 8051 microcontrolleris connected ADC is coming from the crystal of the microcontroller. Since this frequencyis too high, we use 'D' flip flop divides the frequencyby 2 if we two D flip flops to divide the frequencyby 4. A usemore flip flops. connectits Q to the D input. For a higher frequency,
P2.5 P2.6

XTAL1

XTAL2 P1.0 P1.1 P1.2 P1.3 P1.4 P1.5 P1.6 P1.V P2.7

DO
nl v i

Dz
ne D4
ntr

V i n( + )
Vin (-)

AGND D6 YretlZ D7 I N T R_ 6 p 9 CS

74L574
Fig. 5. I 8 805I connected with ADC

The Program presentsthe concept to monitor the INTR pins and bring an analog rnput into continuously. registerA. Then call a hex - to - ASCII conversionand data display subroutines

needs P2.6: WR (startconversion to low - to - highpulse) P2.7: INTR, whenlow, end- of - conversron will readthedatafrom ADC chip) P25 = RD (a high-to-low Pl.0 - Pl.7 : Do- D, of ADC 804 H ; make Pl : input MOV Pl, # OFF BACK : CLRP2.6 ;WR: Q conversion. SETB P2.6:WR: I Low - to - highto start
Microconrrollers

5.6s

HERE :

JB P2.7,HERE CLR P2.5

; Wait for endof conversion RD finished,enable ; Conversion

MOVA,PI; readthedata A CALL CONVERSION : hex - to - ASCII conversion A CALL the data DATA-DISPLAY ; disPlaY SETB P2.5 ; makeRD = 1 for nextround SJMPBACK counter Frequency 5.10.2 unknownfrequency'The main partsarea counteris usefulfor measuring The frequencv circuit for the incomingsignalanda displayportionalongwith themicrocontroller waveshaping in figure5.19. by theblockdiagram asindicated circuit and the input signalis by the waveshaping The incomingsignalis conditioned by findingthetime thewave canbemeasured wave. Thepulsefrequency into a square converted is then, is high(Th). The frequency UF: Thx 2 I f T h = 2 0 0p s , U F : = 2500H2.
I

200 x 10'6x2

will fall asthe inputwavedepartfrom a 50%duty cycle. The accuracyof the measurement

Unknown waveform

tr+

Microcontroller 8051

Fig. 5. I 9 Frequency counter - Block diagram

5.66

and Microcontrollers Microprocessors

only whenthecorresponding clockis counted sothattheinternal Timer I maybeconfigured is within of themeasurement ft tf t pin is high by settingtheGAIE 1 bit in TMOD. Theaccuracy canonly be attained for a l2MHz crystal.This accuracy onetimerclockperiod,or I microsecond whenthe input next goes is startedwhenthe input waveis low and stopped if the measurement for a 12 milliseconds 65'54 is which thanthe capacityof the counter, low. Pulsewidths greater final the by countingthe overflow of the timer flag and adding MHz crystal,can be measured in the counter. contents a timer whenthepulsegenerates by enabling The width of an unknownpulseis measured to occuron a high - to - low an interrupton oneof the fNf t pins. The intemrptis programmed high,enabling pulsegoes whentheunknown beginscounting edge on ttt" fNf t pin. The counter the counterto countwhen NT t goeshigh. The nextpulseedgestopsthe couriter.The counter for a l2MHz crystal. microsecond will containthe width of thepulseto the nearest in fig'5.20 is shown counter using8051microcontroller circuitfor frequency An example on port 1 (LSB)andport 2 (MSB). Thewidth of thepulseis displayed
Vcc

I
Mlcrocontroller p2.g P2.1 P2.2 P2.3 P2.4 P2.5

,r'""
Digltal Display

l usa
f
)

RSr/vPP

,r7.9

cND T1lP3.5

lNIolpe.e INT1lpg,s

RXD/P3.0 TXD/P3.1

counter Fig. 5.20Frequency

Micr.oantrollers

5.67

5.10.3 Eight ChannelSequential Controller Theeightchannel sequential controller is anusefulindustrial controllermeant for switching ON / OFFmanyoperations in anequipment. For example in a textilemill thesequential controller is requiiedto activatelot of solenoids to evacuate thewasteaccumulated undereveryprocessing machine.The solenoids predefined operate at timesanda motor sucksout the wastefrom every periodically. The controlleris responsible machine for coordinating all the operations of this wasteevacuating system. Hereimportanttaskfor the controlleris switchingon solenoids at the correcttime andat the correctsequence at everymachine and alsoactivatingother solenoids at everymachine andalsoactivating othersolenoids at othersffategic locations to guidethewaste in to theduct till it reaches thepackingsection. Similarly,in a bag- seating environment, a controller hasto operate manyrelays,solenoids, contactors at the correcttime to finish thejob of filling up the bagwith the requiredquantityof materials.If theprecisionfilling is required, we canin corporate a weighingloadcell to monitor thequantity.

4x4Keymatrix
Fig. 5.2 | Sequential contrcller - Block diagram

The8 channel sequential controlleris shownif figure5.21. lthas controlfor 8 outputs.We can connectrelays, solenoids,solid staterelays,contactors and etc. User interactioncan be established usingthe LCD moduleandthe keypad.This devicealsosportson chip E2PROMto keepreference valuesof timing, etc., Microcontroller'sinternaltimer is usedto keephack of timingrequirements.

26

5.68

Miooprocessorsand Misxontrollqs

P1.7 P1.6 P1.5 P1.4 P1.3 P|.2 P1.1

4x4Keymatrx

8051 P1.0 Microcontroller XTALl

P3.5 P3.6 P3.7 P2.0 P2.1 P2.2 P2.3 P2.4 P2.5 P2.6 P2.7

BAdi RS R/VV E Do LcD D1 D2 D3 D4 D5 D6 D7

P0.0 P0.1 P0.2 P0.3 P0.4 P0.5 P0.6 PO.7


GND

t Realv I

8J Realv

t I

Output drivers

Fig. 5.22 Eight channel sequential controller

(i)

with 8051usingport 2 and3' is interfaced The LCD module directlywith Port l. and4 rowsis connected (ii) Thekey matrixwith 4 columns theoperation with port0 andcontrols is interfaced (IILN 2003) (iii) Thecontroldriverdevice etc. lamPs solenoids, of relays,

time or sequentially for a spectfic on any of iheseoutputdevices So the 8051switches oneby oneasperthetimingrequirement. all thedevices activates also. Applications Note : Referthe Appendix- Microprocessor (i) motor control Stepper control (ii) DC motorspeed (iii) Process control

Microcontrollers

5.69

Das könnte Ihnen auch gefallen