Your SlideShare is downloading. ×
The 8051 microcontroller and embedded systems using assembly and c 2nd-ed by mazidi
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

The 8051 microcontroller and embedded systems using assembly and c 2nd-ed by mazidi

4,798
views

Published on

Published in: Technology, Business

0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
4,798
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
313
Comments
0
Likes
3
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. The 8051 Microcontroller and EmbeddedSystemsUsing Assembly and CSecond EditionMuhammad Ali MazidiJanice Gillispie MazidiRolin D. McKinlayCONTENTSIntroduction to ComputingThe 8051 Microcontrollers8051 Assembly Language ProgrammingBranch InstructionsI/O Port Programming8051 Addressing ModesArithmetic & Logic Instructions And Programs8051 Programming in C8051 Hardware Connection and Hex File8051 Timer/Counter Programming in Assembly and C8051 Serial Port Programming in Assembly and CInterrupts Programming in Assembly and C8051 Interfacing to External Memory8051 Real World Interfacing I: LCD,ADC ANDSENSORSLCD and Keyboard Interfacing8051 Interfacing with 8255
  • 2. Home Automation, Networking, and Entertainment LabDept. of Computer Science and Information EngineeringNational Cheng Kung University, TAIWANChung-Ping Young楊中平INTRODUCTION TOCOMPUTINGThe 8051 Microcontroller and EmbeddedSystems: Using Assembly and CMazidi, Mazidi and McKinlay
  • 3. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 2HANELOUTLINESNumbering and coding systemsDigital primerInside the computer
  • 4. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 3HANELNUMBERINGAND CODINGSYSTEMSDecimal andBinary NumberSystemsHuman beings use base 10 (decimal)arithmeticThere are 10 distinct symbols, 0, 1, 2, …,9Computers use base 2 (binary) systemThere are only 0 and 1These two binary digits are commonlyreferred to as bits
  • 5. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 4HANELNUMBERINGAND CODINGSYSTEMSConvertingfrom Decimalto BinaryDivide the decimal number by 2repeatedlyKeep track of the remaindersContinue this process until the quotientbecomes zeroWrite the remainders in reverse orderto obtain the binary numberEx. Convert 2510 to binaryQuotient Remainder25/2 = 12 1 LSB (least significant bit)12/2 = 6 06/2 = 3 03/2 = 1 11/2 = 0 1 MSB (most significant bit)Therefore 2510 = 110012
  • 6. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 5HANELNUMBERINGAND CODINGSYSTEMSConvertingfrom Binary toDecimalKnow the weight of each bit in a binarynumberAdd them together to get its decimalequivalentUse the concept of weight to convert adecimal number to a binary directlyEx. Convert 110012 to decimalWeight: 24 23 22 21 20Digits: 1 1 0 0 1Sum: 16 + 8 + 0 + 0 + 1 = 2510Ex. Convert 3910 to binary32 + 0 + 0 + 4 + 2 + 1 = 39Therefore, 3910 = 1001112
  • 7. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 6HANELNUMBERINGAND CODINGSYSTEMSHexadecimalSystemBase 16, thehexadecimal system,is used as aconvenientrepresentation ofbinary numbersex.It is much easier torepresent a string of 0sand 1s such as100010010110 as itshexadecimal equivalent of896HF111115E111014D110113C110012B101111A101010910019810008701117601106501015401004300113200102100011000000HexBinaryDecimal
  • 8. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 7HANELNUMBERINGAND CODINGSYSTEMSConvertingbetween Binaryand HexTo represent a binary number as itsequivalent hexadecimal numberStart from the right and group 4 bits at atime, replacing each 4-bit binary numberwith its hex equivalentTo convert from hex to binaryEach hex digit is replaced with its 4-bitbinary equivalentEx. Convert hex 29B to binary2 9 B= 0010 1001 1011Ex. Represent binary 100111110101 in hex1001 1111 0101= 9 F 5
  • 9. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 8HANELNUMBERINGAND CODINGSYSTEMSConvertingfrom Decimalto HexConvert to binary first and thenconvert to hexConvert directly from decimal to hexby repeated division, keeping track ofthe remaindersEx. Convert 4510 to hex32 16 8 4 2 11 0 1 1 0 1 32 + 8 + 4 + 1 = 454510 = 0010 11012 = 2D16Ex. Convert 62910 to hex512 256 128 64 32 16 8 4 2 11 0 0 1 1 1 0 1 0 162910 = 512+64+32+16+4+1 = 0010 0111 01012 = 27516
  • 10. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 9HANELNUMBERINGAND CODINGSYSTEMSConvertingfrom Hex toDecimalConvert from hex to binary and then todecimalConvert directly from hex to decimalby summing the weight of all digitsEx. 6B216 = 0110 1011 001021024 512 256 128 64 32 16 8 4 2 11 1 0 1 0 1 1 0 0 1 01024 + 512 + 128 + 32 + 16 + 2 = 171410
  • 11. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 10HANELNUMBERINGAND CODINGSYSTEMSAddition of HexNumbersAdding the digits together from theleast significant digitsIf the result is less than 16, write that digitas the sum for that positionIf it is greater than 16, subtract 16 from itto get the digit and carry 1 to the nextdigitEx. Perform hex addition: 23D9 + 94BE23D9 LSD: 9 + 14 = 23 23 – 16 = 7 w/ carry+ 94BE 1 + 13 + 11 = 25 25 – 16 = 9 w/ carryB897 1 + 3 + 4 = 8MSD: 2 + 9 = B
  • 12. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 11HANELNUMBERINGAND CODINGSYSTEMSSubtraction ofHex NumbersIf the second digit is greater than thefirst, borrow 16 from the precedingdigitEx. Perform hex subtraction: 59F – 2B859F LSD: 15 – 8 = 7– 2B8 9 + 16 – 11 = 14 = E162E7 5 – 1 – 2 = 2
  • 13. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 12HANELNUMBERINGAND CODINGSYSTEMSASCII CodeThe ASCII (pronounced “ask-E”) codeassigns binary patterns forNumbers 0 to 9All the letters of English alphabet,uppercase and lowercaseMany control codes and punctuationmarksThe ASCII system uses 7 bits torepresent each codez7AZ5Ay79Y59….........d64D44c63C43b62B42a61A41SymbolHexSymbolHexSelected ASCII codes
  • 14. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 13HANELDIGITALPRIMERBinary LogicTwo voltage levels can be representedas the two digits 0 and 1Signals in digital electronics have twodistinct voltage levels with built-intolerances for variations in the voltageA valid digital signal should be withineither of the two shaded areas012345Logic 0Logic 1
  • 15. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 14HANELDIGITALPRIMERLogic GatesAND gateOR gateComputer Science Illuminated, Dale and LewisComputer Science Illuminated, Dale and Lewis
  • 16. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 15HANELDIGITALPRIMERLogic Gates(cont’)Tri-state bufferInverterXOR gateComputer Science Illuminated, Dale and LewisComputer Science Illuminated, Dale and Lewis
  • 17. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 16HANELDIGITALPRIMERLogic Gates(cont’)NAND gateNOR gateComputer Science Illuminated, Dale and LewisComputer Science Illuminated, Dale and Lewis
  • 18. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 17HANELDIGITALPRIMERLogic DesignUsing GatesHalf adderFull adderDigital Design, Mano
  • 19. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 18HANELDIGITALPRIMERLogic DesignUsing Gates(cont’)4-bit adderDigital Design, Mano
  • 20. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 19HANELDIGITALPRIMERLogic DesignUsing Gates(cont’)DecodersDecoders are widely used for addressdecoding in computer designAddress decoder for 9 (10012)The output will be 1 if andonly if the input is 10012Address decoder for 5 (01012)The output will be 1 if andonly if the input is 01012Address Decoders
  • 21. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 20HANELDIGITALPRIMERLogic DesignUsing Gates(cont’)Flip-flopsFlip-flops are frequently used to store dataDigital Design, Mano
  • 22. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 21HANELINSIDE THECOMPUTERImportantTerminologyThe unit of data sizeBit : a binary digit that can have the value0 or 1Byte : 8 bitsNibble : half of a bye, or 4 bitsWord : two bytes, or 16 bitsThe terms used to describe amounts ofmemory in IBM PCs and compatiblesKilobyte (K): 210 bytesMegabyte (M) : 220 bytes, over 1 millionGigabyte (G) : 230 bytes, over 1 billionTerabyte (T) : 240 bytes, over 1 trillion
  • 23. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 22HANELINSIDE THECOMPUTERInternalOrganization ofComputersCPU (Central Processing Unit)Execute information stored in memoryI/O (Input/output) devicesProvide a means of communicating withCPUMemoryRAM (Random Access Memory) –temporary storage of programs thatcomputer is runningThe data is lost when computer is offROM (Read Only Memory) – containsprograms and information essential tooperation of the computerThe information cannot be changed by use,and is not lost when power is off– It is called nonvolatile memory
  • 24. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 23HANELINSIDE THECOMPUTERInternalOrganization ofComputers(cont’) CPUMemory(RAM, ROM)Peripherals(monitor,printer, etc.)Address busData bus
  • 25. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 24HANELINSIDE THECOMPUTERInternalOrganization ofComputers(cont’)The CPU is connected to memory andI/O through strips of wire called a busCarries information from place to placeAddress busData busControl busCPURead/WriteRAMAddress busData busROM Printer Disk Monitor KeyboardControl bus
  • 26. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 25HANELINSIDE THECOMPUTERInternalOrganization ofComputers(cont’)Address busFor a device (memory or I/O) to berecognized by the CPU, it must beassigned an addressThe address assigned to a given device mustbe uniqueThe CPU puts the address on the address bus,and the decoding circuitry finds the deviceData busThe CPU either gets data from the deviceor sends data to itControl busProvides read or write signals to thedevice to indicate if the CPU is asking forinformation or sending it information
  • 27. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 26HANELINSIDE THECOMPUTERMore aboutData BusThe more data buses available, thebetter the CPUThink of data buses as highway lanesMore data buses mean a moreexpensive CPU and computerThe average size of data buses in CPUsvaries between 8 and 64Data buses are bidirectionalTo receive or send dataThe processing power of a computer isrelated to the size of its buses
  • 28. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 27HANELINSIDE THECOMPUTERMore aboutAddress BusThe more address buses available, thelarger the number of devices that canbe addressedThe number of locations with which aCPU can communicate is always equalto 2x, where x is the address lines,regardless of the size of the data busex. a CPU with 24 address lines and 16data lines can provide a total of 224 or 16Mbytes of addressable memoryEach location can have a maximum of 1byte of data, since all general-purposeCPUs are byte addressableThe address bus is unidirectional
  • 29. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 28HANELINSIDE THECOMPUTERCPU’s Relationto RAM andROMFor the CPU to process information,the data must be stored in RAM orROM, which are referred to as primarymemoryROM provides information that is fixedand permanentTables or initialization programRAM stores information that is notpermanent and can change with timeVarious versions of OS and applicationpackagesCPU gets information to be processedfirst form RAM (or ROM)if it is not there, then seeks it from a massstorage device, called secondary memory, andtransfers the information to RAM
  • 30. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 29HANELINSIDE THECOMPUTERInside CPUsRegistersThe CPU uses registers to storeinformation temporarilyValues to be processedAddress of value to be fetched from memoryIn general, the more and bigger theregisters, the better the CPURegisters can be 8-, 16-, 32-, or 64-bitThe disadvantage of more and bigger registersis the increased cost of such a CPU
  • 31. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 30HANELINSIDE THECOMPUTERInside CPUs(cont’)Flags ALUProgram CounterInstruction RegisterInstruction decoder,timing, and controlRegister ARegister BRegister CRegister DAddressBusControlBusDataBusInternalbuses
  • 32. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 31HANELINSIDE THECOMPUTERInside CPUs(cont’)ALU (arithmetic/logic unit)Performs arithmetic functions such as add,subtract, multiply, and divide, and logicfunctions such as AND, OR, and NOTProgram counterPoints to the address of the nextinstruction to be executedAs each instruction is executed, the programcounter is incremented to point to the addressof the next instruction to be executedInstruction decoderInterprets the instruction fetched into theCPUA CPU capable of understanding moreinstructions requires more transistors to design
  • 33. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 32HANELINSIDE THECOMPUTERInternalWorking ofComputersEx. A CPU has registers A, B, C, and D and it has an 8-bitdata bus and a 16-bit address bus. The CPU can accessmemory from addresses 0000 to FFFFHAssume that the code for the CPU to move a value toregister A is B0H and the code for adding a value toregister A is 04HThe action to be performed by the CPU is to put 21H intoregister A, and then add to register A values 42H and 12H...
  • 34. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 33HANELINSIDE THECOMPUTERInternalWorking ofComputers(cont’)Ex. (cont’)Action Code DataMove value 21H into reg. A B0H 21HAdd value 42H to reg. A 04H 42HAdd value 12H to reg. A 04H 12HMem. addr. Contents of memory address1400 (B0) code for moving a value to register A1401 (21) value to be moved1402 (04) code for adding a value to register A1403 (42) value to be added1404 (04) code for adding a value to register A1405 (12) value to be added1406 (F4) code for halt...
  • 35. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 34HANELINSIDE THECOMPUTERInternalWorking ofComputers(cont’)Ex. (cont’)The actions performed by CPU are as follows:1. The program counter is set to the value 1400H,indicating the address of the first instruction code tobe executed2.The CPU puts 1400H on address bus and sends itoutThe memory circuitry finds the locationThe CPU activates the READ signal, indicating tomemory that it wants the byte at location 1400HThis causes the contents of memory location1400H, which is B0, to be put on the data bus andbrought into the CPU...以動畫表示
  • 36. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 35HANELINSIDE THECOMPUTERInternalWorking ofComputers(cont’)Ex. (cont’)3.The CPU decodes the instruction B0The CPU commands its controller circuitry to bringinto register A of the CPU the byte in the nextmemory locationThe value 21H goes into register AThe program counter points to the address of thenext instruction to be executed, which is 1402HAddress 1402 is sent out on the address bus tofetch the next instruction...
  • 37. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 36HANELINSIDE THECOMPUTERInternalWorking ofComputers(cont’)Ex. (cont’)4.From memory location 1402H it fetches code 04HAfter decoding, the CPU knows that it must add tothe contents of register A the byte sitting at thenext address (1403)After the CPU brings the value (42H), it providesthe contents of register A along with this value tothe ALU to perform the additionIt then takes the result of the addition from theALU’s output and puts it in register AThe program counter becomes 1404, the addressof the next instruction...
  • 38. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 37HANELINSIDE THECOMPUTERInternalWorking ofComputers(cont’)Ex. (cont’)5.Address 1404H is put on the address bus and thecode is fetched into the CPU, decoded, andexecutedThis code is again adding a value to register AThe program counter is updated to 1406H6.The contents of address 1406 are fetched in andexecutedThis HALT instruction tells the CPU to stopincrementing the program counter and asking forthe next instruction
  • 39. Home Automation, Networking, and Entertainment LabDept. of Computer Science and Information EngineeringNational Cheng Kung University, TAIWANChung-Ping Young楊中平8051 MICROCONTROLLERSThe 8051 Microcontroller and EmbeddedSystems: Using Assembly and CMazidi, Mazidi and McKinlay
  • 40. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 2HANELOUTLINESMicrocontrollers and embeddedprocessorsOverview of the 8051 family
  • 41. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 3HANELMICRO-CONTROLLERSANDEMBEDDEDPROCESSORSMicrocontrollervs. General-PurposeMicroprocessorGeneral-purpose microprocessorscontainsNo RAMNo ROMNo I/O portsMicrocontroller hasCPU (microprocessor)RAMROMI/O portsTimerADC and other peripherals
  • 42. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 4HANELMICRO-CONTROLLERSANDEMBEDDEDPROCESSORSMicrocontrollervs. General-PurposeMicroprocessor(cont’)SerialCOMPortTimerI/OROMRAMCPUMicrocontrollerCPURAMAddress busData busROMI/OPortSerialCOMPortTimerGeneral-purposeMicro-Processor
  • 43. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 5HANELMICRO-CONTROLLERSANDEMBEDDEDPROCESSORSMicrocontrollervs. General-PurposeMicroprocessor(cont’)General-purpose microprocessorsMust add RAM, ROM, I/O ports, andtimers externally to make them functionalMake the system bulkier and much moreexpensiveHave the advantage of versatility on theamount of RAM, ROM, and I/O portsMicrocontrollerThe fixed amount of on-chip ROM, RAM,and number of I/O ports makes them idealfor many applications in which cost andspace are criticalIn many applications, the space it takes,the power it consumes, and the price perunit are much more critical considerationsthan the computing power
  • 44. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 6HANELMICRO-CONTROLLERSANDEMBEDDEDPROCESSORSMicrocontrollersfor EmbeddedSystemsAn embedded product uses amicroprocessor (or microcontroller) todo one task and one task onlyThere is only one application software thatis typically burned into ROMA PC, in contrast with the embeddedsystem, can be used for any number ofapplicationsIt has RAM memory and an operatingsystem that loads a variety of applicationsinto RAM and lets the CPU run themA PC contains or is connected to variousembedded productsEach one peripheral has a microcontroller insideit that performs only one task
  • 45. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 7HANELMICRO-CONTROLLERSANDEMBEDDEDPROCESSORSMicrocontrollersfor EmbeddedSystems(cont’)HomeAppliances, intercom, telephones, security systems,garage door openers, answering machines, faxmachines, home computers, TVs, cable TV tuner,VCR, camcorder, remote controls, video games,cellular phones, musical instruments, sewingmachines, lighting control, paging, camera, pinballmachines, toys, exercise equipmentOfficeTelephones, computers, security systems, faxmachines, microwave, copier, laser printer, colorprinter, pagingAutoTrip computer, engine control, air bag, ABS,instrumentation, security system, transmissioncontrol, entertainment, climate control, cellularphone, keyless entry
  • 46. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 8HANELMICRO-CONTROLLERSANDEMBEDDEDPROCESSORSx86 PCEmbeddedApplicationsMany manufactures of general-purposemicroprocessors have targeted theirmicroprocessor for the high end of theembedded marketThere are times that a microcontroller isinadequate for the taskWhen a company targets a general-purpose microprocessor for theembedded market, it optimizes theprocessor used for embedded systemsVery often the terms embeddedprocessor and microcontroller are usedinterchangeably
  • 47. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 9HANELMICRO-CONTROLLERSANDEMBEDDEDPROCESSORSx86 PCEmbeddedApplications(cont’)One of the most critical needs of anembedded system is to decreasepower consumption and spaceIn high-performance embeddedprocessors, the trend is to integratemore functions on the CPU chip and letdesigner decide which features he/shewants to useIn many cases using x86 PCs for thehigh-end embedded applicationsSaves money and shortens developmenttimeA vast library of software already writtenWindows is a widely used and well understoodplatform
  • 48. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 10HANELMICRO-CONTROLLERSANDEMBEDDEDPROCESSORSChoosing aMicrocontroller8-bit microcontrollersMotorola’s 6811Intel’s 8051Zilog’s Z8Microchip’s PICThere are also 16-bit and 32-bitmicrocontrollers made by various chipmakers
  • 49. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 11HANELMICRO-CONTROLLERSANDEMBEDDEDPROCESSORSCriteria forChoosing aMicrocontrollerMeeting the computing needs of thetask at hand efficiently and costeffectivelySpeedPackagingPower consumptionThe amount of RAM and ROM on chipThe number of I/O pins and the timer onchipHow easy to upgrade to higher-performance or lower power-consumptionversionsCost per unit
  • 50. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 12HANELMICRO-CONTROLLERSANDEMBEDDEDPROCESSORSCriteria forChoosing aMicrocontroller(cont’)Availability of software developmenttools, such as compilers, assemblers,and debuggersWide availability and reliable sourcesof the microcontrollerThe 8051 family has the largest number ofdiversified (multiple source) suppliersIntel (original)AtmelPhilips/SigneticsAMDInfineon (formerly Siemens)MatraDallas Semiconductor/Maxim
  • 51. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 13HANELOVERVIEW OF8051 FAMILY8051MicrocontrollerIntel introduced 8051, referred as MCS-51, in 1981The 8051 is an 8-bit processorThe CPU can work on only 8 bits of data at atimeThe 8051 had128 bytes of RAM4K bytes of on-chip ROMTwo timersOne serial portFour I/O ports, each 8 bits wide6 interrupt sourcesThe 8051 became widely popular afterallowing other manufactures to makeand market any flavor of the 8051, butremaining code-compatible
  • 52. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 14HANELOVERVIEW OF8051 FAMILY8051Microcontroller(cont’)InterruptControlBusControlCPUOSC I/OPortsSerialPortEtc.Timer 0Timer 1On-chipRAMOn-chipROMfor codeP0 P1 P2 P3Address/DataTXD RXDCounterInputsExternalInterrupts
  • 53. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 15HANELOVERVIEW OF8051 FAMILY8051 FamilyThe 8051 is a subset of the 8052The 8031 is a ROM-less 8051Add external ROM to itYou lose two ports, and leave only 2 portsfor I/O operations686Interrupt sources111Serial port323232I/O pins232Timers128256128RAM (bytes)0K8K4KROM (on-chip programspace in bytes)803180528051Feature
  • 54. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 16HANELOVERVIEW OF8051 FAMILYVarious 8051Microcontrollers8751 microcontrollerUV-EPROMPROM burnerUV-EPROM eraser takes 20 min to eraseAT89C51 from Atmel CorporationFlash (erase before write)ROM burner that supports flashA separate eraser is not neededDS89C4x0 from Dallas Semiconductor,now part of Maxim Corp.FlashComes with on-chip loader, loading program toon-chip flash via PC COM port
  • 55. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 17HANELOVERVIEW OF8051 FAMILYVarious 8051Microcontrollers(cont’)DS5000 from Dallas SemiconductorNV-RAM (changed one byte at a time),RTC (real-time clock)Also comes with on-chip loaderOTP (one-time-programmable) versionof 80518051 family from PhilipsADC, DAC, extended I/O, and both OTPand flash
  • 56. Home Automation, Networking, and Entertainment LabDept. of Computer Science and Information EngineeringNational Cheng Kung University, TAIWANChung-Ping Young楊中平8051 ASSEMBLYLANGUAGEPROGRAMMINGThe 8051 Microcontroller and EmbeddedSystems: Using Assembly and CMazidi, Mazidi and McKinlay
  • 57. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 2HANELINSIDE THE8051RegistersRegister are used to store informationtemporarily, while the informationcould bea byte of data to be processed, oran address pointing to the data to befetchedThe vast majority of 8051 register are8-bit registersThere is only one data type, 8 bits
  • 58. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 3HANELINSIDE THE8051Registers(cont’)The 8 bits of a register are shown fromMSB D7 to the LSB D0With an 8-bit data type, any data largerthan 8 bits must be broken into 8-bitchunks before it is processedD0D1D2D3D4D5D6D78 bit Registersmostsignificant bitleastsignificant bit
  • 59. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 4HANELINSIDE THE8051Registers(cont’)The most widely used registersA (Accumulator)For all arithmetic and logic instructionsB, R0, R1, R2, R3, R4, R5, R6, R7DPTR (data pointer), and PC (programcounter)R6R5R4R3R2R1R0BAR7DPTRPC PC (Program counter)DPH DPL
  • 60. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 5HANELINSIDE THE8051MOVInstructionMOV destination, source ;copy source to dest.The instruction tells the CPU to move (in reality,COPY) the source operand to the destinationoperandMOV A,#55H ;load value 55H into reg. AMOV R0,A ;copy contents of A into R0;(now A=R0=55H)MOV R1,A ;copy contents of A into R1;(now A=R0=R1=55H)MOV R2,A ;copy contents of A into R2;(now A=R0=R1=R2=55H)MOV R3,#95H ;load value 95H into R3;(now R3=95H)MOV A,R3 ;copy contents of R3 into A;now A=R3=95H“#” signifies that it is a value
  • 61. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 6HANELINSIDE THE8051MOVInstruction(cont’)Notes on programmingValue (proceeded with #) can be loadeddirectly to registers A, B, or R0 – R7MOV A, #23HMOV R5, #0F9HIf values 0 to F moved into an 8-bitregister, the rest of the bits are assumedall zeros“MOV A, #5”, the result will be A=05; i.e., A= 00000101 in binaryMoving a value that is too large into aregister will cause an errorMOV A, #7F2H ; ILLEGAL: 7F2H>8 bits (FFH)If it’s not preceded with #,it means to load from amemory locationAdd a 0 to indicate thatF is a hex number andnot a letter
  • 62. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 7HANELINSIDE THE8051ADDInstructionADD A, source ;ADD the source operand;to the accumulatorThe ADD instruction tells the CPU to add the sourcebyte to register A and put the result in register ASource operand can be either a register orimmediate data, but the destination must alwaysbe register A“ADD R4, A” and “ADD R2, #12H” are invalidsince A must be the destination of any arithmeticoperationMOV A, #25H ;load 25H into AMOV R2, #34H ;load 34H into R2ADD A, R2 ;add R2 to Accumulator;(A = A + R2)MOV A, #25H ;load one operand;into A (A=25H)ADD A, #34H ;add the second;operand 34H to AThere are alwaysmany ways to writethe same program,depending on theregisters used
  • 63. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 8HANELStructure ofAssemblyLanguageIn the early days of the computer,programmers coded in machine language,consisting of 0s and 1sTedious, slow and prone to errorAssembly languages, which providedmnemonics for the machine code instructions,plus other features, were developedAn Assembly language program consist of a seriesof lines of Assembly language instructionsAssembly language is referred to as a low-level languageIt deals directly with the internal structure of theCPU8051ASSEMBLYPROGRAMMING
  • 64. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 9HANELStructure ofAssemblyLanguage8051ASSEMBLYPROGRAMMINGAssembly language instruction includesa mnemonic (abbreviation easy to remember)the commands to the CPU, telling it what thoseto do with those itemsoptionally followed by one or two operandsthe data items being manipulatedA given Assembly language program isa series of statements, or linesAssembly language instructionsTell the CPU what to doDirectives (or pseudo-instructions)Give directions to the assembler
  • 65. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 10HANELStructure ofAssemblyLanguageORG 0H ;start(origin) at location0MOV R5, #25H ;load 25H into R5MOV R7, #34H ;load 34H into R7MOV A, #0 ;load 0 into AADD A, R5 ;add contents of R5 to A;now A = A + R5ADD A, R7 ;add contents of R7 to A;now A = A + R7ADD A, #12H ;add to A value 12H;now A = A + 12HHERE: SJMP HERE ;stay in this loopEND ;end of asm source file8051ASSEMBLYPROGRAMMINGAn Assembly language instructionconsists of four fields:[label:] Mnemonic [operands] [;comment]MnemonicsproduceopcodesThe label field allowsthe program to refer to aline of code by nameComments may be at the end of aline or on a line by themselvesThe assembler ignores commentsDirectives do notgenerate any machinecode and are usedonly by the assembler
  • 66. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 11HANELASSEMBLINGAND RUNNINGAN 8051PROGRAMThe step of Assembly languageprogram are outlines as follows:1) First we use an editor to type a program,many excellent editors or wordprocessors are available that can be usedto create and/or edit the programNotice that the editor must be able to producean ASCII fileFor many assemblers, the file names followthe usual DOS conventions, but the source filehas the extension “asm“ or “src”, dependingon which assembly you are using
  • 67. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 12HANELASSEMBLINGAND RUNNINGAN 8051PROGRAM(cont’)2) The “asm” source file containing theprogram code created in step 1 is fed toan 8051 assemblerThe assembler converts the instructions intomachine codeThe assembler will produce an object file anda list fileThe extension for the object file is “obj” whilethe extension for the list file is “lst”3) Assembler require a third step calledlinkingThe linker program takes one or more objectcode files and produce an absolute object filewith the extension “abs”This abs file is used by 8051 trainers thathave a monitor program
  • 68. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 13HANELASSEMBLINGAND RUNNINGAN 8051PROGRAM(cont’)4) Next the “abs” file is fed into a programcalled “OH” (object to hex converter)which creates a file with extension “hex”that is ready to burn into ROMThis program comes with all 8051 assemblersRecent Windows-based assemblers combinestep 2 through 4 into one step
  • 69. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 14HANELASSEMBLINGAND RUNNINGAN 8051PROGRAMSteps to Createa ProgramEDITORPROGRAMASSEMBLERPROGRAMLINKERPROGRAMOHPROGRAMmyfile.asmmyfile.objmyfile.absmyfile.lstOther obj filesmyfile.hex
  • 70. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 15HANELASSEMBLINGAND RUNNINGAN 8051PROGRAMlst FileThe lst (list) file, which is optional, isvery useful to the programmerIt lists all the opcodes and addresses aswell as errors that the assembler detectedThe programmer uses the lst file to findthe syntax errors or debug1 0000 ORG 0H ;start (origin) at 02 0000 7D25 MOV R5,#25H ;load 25H into R53 0002 7F34 MOV R7,#34H ;load 34H into R74 0004 7400 MOV A,#0 ;load 0 into A5 0006 2D ADD A,R5 ;add contents of R5 to A;now A = A + R56 0007 2F ADD A,R7 ;add contents of R7 to A;now A = A + R77 0008 2412 ADD A,#12H ;add to A value 12H;now A = A + 12H8 000A 80EF HERE: SJMP HERE;stay in this loop9 000C END ;end of asm source fileaddress
  • 71. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 16HANELPROGRAMCOUNTER ANDROM SPACEProgramCounterThe program counter points to theaddress of the next instruction to beexecutedAs the CPU fetches the opcode from theprogram ROM, the program counter isincreasing to point to the next instructionThe program counter is 16 bits wideThis means that it can access programaddresses 0000 to FFFFH, a total of 64Kbytes of code
  • 72. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 17HANELPROGRAMCOUNTER ANDROM SPACEPower upAll 8051 members start at memoryaddress 0000 when they’re poweredupProgram Counter has the value of 0000The first opcode is burned into ROMaddress 0000H, since this is where the8051 looks for the first instruction when itis bootedWe achieve this by the ORG statement inthe source program
  • 73. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 18HANELPROGRAMCOUNTER ANDROM SPACEPlacing Code inROMExamine the list file and how the codeis placed in ROM1 0000 ORG 0H ;start (origin) at 02 0000 7D25 MOV R5,#25H ;load 25H into R53 0002 7F34 MOV R7,#34H ;load 34H into R74 0004 7400 MOV A,#0 ;load 0 into A5 0006 2D ADD A,R5 ;add contents of R5 to A;now A = A + R56 0007 2F ADD A,R7 ;add contents of R7 to A;now A = A + R77 0008 2412 ADD A,#12H ;add to A value 12H;now A = A + 12H8 000A 80EF HERE: SJMP HERE ;stay in this loop9 000C END ;end of asm source fileHERE: SJMP HERE80EF000AADD A, #12H24120008ADD A, R72F0007ADD A, R52D0006MOV A, #074000004MOV R7, #34H7F340002MOV R5, #25H7D250000Assembly LanguageMachine LanguageROM Address
  • 74. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 19HANELPROGRAMCOUNTER ANDROM SPACEPlacing Code inROM(cont’)After the program is burned into ROM,the opcode and operand are placed inROM memory location starting at 0000FE000B80000A1200092400082F00072D00060000057400043400037F00022500017D0000CodeAddressROM contents
  • 75. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 20HANELPROGRAMCOUNTER ANDROM SPACEExecutingProgramA step-by-step description of theaction of the 8051 upon applyingpower on it1. When 8051 is powered up, the PC has0000 and starts to fetch the first opcodefrom location 0000 of program ROMUpon executing the opcode 7D, the CPUfetches the value 25 and places it in R5Now one instruction is finished, and then thePC is incremented to point to 0002, containingopcode 7F2. Upon executing the opcode 7F, the value34H is moved into R7The PC is incremented to 0004
  • 76. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 21HANELPROGRAMCOUNTER ANDROM SPACEExecutingProgram(cont’)(cont’)3. The instruction at location 0004 isexecuted and now PC = 00064. After the execution of the 1-byteinstruction at location 0006, PC = 00075. Upon execution of this 1-byte instructionat 0007, PC is incremented to 0008This process goes on until all the instructionsare fetched and executedThe fact that program counter points at thenext instruction to be executed explains somemicroprocessors call it the instruction pointer
  • 77. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 22HANELPROGRAMCOUNTER ANDROM SPACEROM MemoryMap in 8051FamilyNo member of 8051 family can accessmore than 64K bytes of opcodeThe program counter is a 16-bit registerByte Byte Byte00000FFF0000 00003FFF7FFF8751AT89C51DS89C420/30DS5000-32
  • 78. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 23HANEL8051 DATATYPES ANDDIRECTIVESData Type8051 microcontroller has only one datatype - 8 bitsThe size of each register is also 8 bitsIt is the job of the programmer to breakdown data larger than 8 bits (00 to FFH,or 0 to 255 in decimal)The data types can be positive or negative
  • 79. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 24HANEL8051 DATATYPES ANDDIRECTIVESAssemblerDirectivesThe DB directive is the most widelyused data directive in the assemblerIt is used to define the 8-bit dataWhen DB is used to define data, thenumbers can be in decimal, binary, hex,ASCII formatsORG 500HDATA1: DB 28 ;DECIMAL (1C in Hex)DATA2: DB 00110101B ;BINARY (35 in Hex)DATA3: DB 39H ;HEXORG 510HDATA4: DB “2591” ;ASCII NUMBERSORG 518HDATA6: DB “My name is Joe”;ASCII CHARACTERSThe “D” after the decimalnumber is optional, but using“B” (binary) and “H”(hexadecimal) for the others isrequiredThe Assembler willconvert the numbersinto hexPlace ASCII in quotation marksThe Assembler will assign ASCIIcode for the numbers or charactersDefine ASCII strings largerthan two characters
  • 80. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 25HANEL8051 DATATYPES ANDDIRECTIVESAssemblerDirectives(cont’)ORG (origin)The ORG directive is used to indicate thebeginning of the addressThe number that comes after ORG can beeither in hex and decimalIf the number is not followed by H, it is decimaland the assembler will convert it to hexENDThis indicates to the assembler the end ofthe source (asm) fileThe END directive is the last line of an8051 programMean that in the code anything after the ENDdirective is ignored by the assembler
  • 81. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 26HANEL8051 DATATYPES ANDDIRECTIVESAssemblerdirectives(cont’)EQU (equate)This is used to define a constant withoutoccupying a memory locationThe EQU directive does not set asidestorage for a data item but associates aconstant value with a data labelWhen the label appears in the program, itsconstant value will be substituted for the label
  • 82. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 27HANEL8051 DATATYPES ANDDIRECTIVESAssemblerdirectives(cont’)EQU (equate) (cont’)Assume that there is a constant used inmany different places in the program, andthe programmer wants to change its valuethroughoutBy the use of EQU, one can change it once andthe assembler will change all of its occurrencesCOUNT EQU 25... ....MOV R3, #COUNTUse EQU for thecounter constantThe constant is used toload the R3 register
  • 83. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 28HANELFLAG BITS ANDPSW REGISTERProgram StatusWordThe program status word (PSW)register, also referred to as the flagregister, is an 8 bit registerOnly 6 bits are usedThese four are CY (carry), AC (auxiliary carry), P(parity), and OV (overflow)– They are called conditional flags, meaningthat they indicate some conditions thatresulted after an instruction was executedThe PSW3 and PSW4 are designed as RS0 andRS1, and are used to change the bankThe two unused bits are user-definable
  • 84. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 29HANELFLAG BITS ANDPSW REGISTERProgram StatusWord (cont’)P--OVRS0RS1F0ACCYCY PSW.7 Carry flag.AC PSW.6 Auxiliary carry flag.-- PSW.5 Available to the user for general purposeRS1 PSW.4 Register Bank selector bit 1.RS0 PSW.3 Register Bank selector bit 0.OV PSW.2 Overflow flag.-- PSW.1 User definable bit.P PSW.0 Parity flag. Set/cleared by hardware eachinstruction cycle to indicate an odd/evennumber of 1 bits in the accumulator.18H – 1FH31110H – 17H20108H – 0FH11000H – 07H000AddressRegister BankRS0RS1Carry out from the d7 bitA carry from D3 to D4Reflect the number of 1sin register AThe result ofsigned numberoperation is toolarge, causingthe high-orderbit to overflowinto the sign bit
  • 85. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 30HANELFLAG BITS ANDPSW REGISTERADDInstruction AndPSWXCJNEXMOV C, bitXORL C, /bitXORL C, bitXANL C, /bitXANL C, bitXCPL C0CLR C1SETB CXPLCXRPCXDAX0DIVX0MULXXXSUBBXXXADDCXXXADDACOVCYInstructionInstructions that affect flag bits
  • 86. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 31HANELFLAG BITS ANDPSW REGISTERADDInstruction AndPSW(cont’)Example 2-2Show the status of the CY, AC and P flag after the addition of 38Hand 2FH in the following instructions.MOV A, #38HADD A, #2FH ;after the addition A=67H, CY=0Solution:38 00111000+ 2F 0010111167 01100111CY = 0 since there is no carry beyond the D7 bitAC = 1 since there is a carry from the D3 to the D4 biP = 1 since the accumulator has an odd number of 1s (it has five 1s)The flag bits affected by the ADDinstruction are CY, P, AC, and OV
  • 87. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 32HANELFLAG BITS ANDPSW REGISTERADDInstruction AndPSW(cont’)Example 2-3Show the status of the CY, AC and P flag after the addition of 9CHand 64H in the following instructions.MOV A, #9CHADD A, #64H ;after the addition A=00H, CY=1Solution:9C 10011100+ 64 01100100100 00000000CY = 1 since there is a carry beyond the D7 bitAC = 1 since there is a carry from the D3 to the D4 biP = 0 since the accumulator has an even number of 1s (it has zero 1s)
  • 88. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 33HANELFLAG BITS ANDPSW REGISTERADDInstruction AndPSW(cont’)Example 2-4Show the status of the CY, AC and P flag after the addition of 88Hand 93H in the following instructions.MOV A, #88HADD A, #93H ;after the addition A=1BH, CY=1Solution:88 10001000+ 93 1001001111B 00011011CY = 1 since there is a carry beyond the D7 bitAC = 0 since there is no carry from the D3 to the D4 biP = 0 since the accumulator has an even number of 1s (it has four 1s)
  • 89. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 34HANELREGISTERBANKS ANDSTACKRAM MemorySpaceAllocationThere are 128 bytes of RAM in the8051Assigned addresses 00 to 7FHThe 128 bytes are divided into threedifferent groups as follows:1) A total of 32 bytes from locations 00 to1F hex are set aside for register banksand the stack2) A total of 16 bytes from locations 20H to2FH are set aside for bit-addressableread/write memory3) A total of 80 bytes from locations 30H to7FH are used for read and write storage,called scratch pad
  • 90. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 35HANEL8051REGISTERBANKS ANDSTACKRAM MemorySpaceAllocation(cont’)Scratch pad RAMBit-Addressable RAMRegister Bank 3Register Bank 2Register Bank 1 (stack)Register Bank 00007080F1017181F202F307FRAM Allocation in 8051
  • 91. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 36HANEL8051REGISTERBANKS ANDSTACKRegister BanksThese 32 bytes are divided into 4banks of registers in which each bankhas 8 registers, R0-R7RAM location from 0 to 7 are set aside forbank 0 of R0-R7 where R0 is RAM location0, R1 is RAM location 1, R2 is RAMlocation 2, and so on, until memorylocation 7 which belongs to R7 of bank 0It is much easier to refer to these RAMlocations with names such as R0, R1, andso on, than by their memory locationsRegister bank 0 is the default when8051 is powered up
  • 92. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 37HANEL8051REGISTERBANKS ANDSTACKRegister Banks(cont’)R7R6R5R4R3R2R1R0Bank 0 Bank 1 Bank 2 Bank 376543201FEDCBA891F1E1D1C1B1A18191716151413121011R7R6R5R4R3R2R1R0R7R6R5R4R3R2R1R0R7R6R5R4R3R2R1R0Register banks and their RAM address
  • 93. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 38HANEL8051REGISTERBANKS ANDSTACKRegister Banks(cont’)We can switch to other banks by useof the PSW registerBits D4 and D3 of the PSW are used toselect the desired register bankUse the bit-addressable instructions SETBand CLR to access PSW.4 and PSW.311Bank 301Bank 210Bank 100Bank 0RS0(PSW.3)RS1(PSW.4)PSW bank selection
  • 94. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 39HANEL8051REGISTERBANKS ANDSTACKRegister Banks(cont’)Example 2-5MOV R0, #99H ;load R0 with 99HMOV R1, #85H ;load R1 with 85HExample 2-6MOV 00, #99H ;RAM location 00H has 99HMOV 01, #85H ;RAM location 01H has 85HExample 2-7SETB PSW.4 ;select bank 2MOV R0, #99H ;RAM location 10H has 99HMOV R1, #85H ;RAM location 11H has 85H
  • 95. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 40HANEL8051REGISTERBANKS ANDSTACKStackThe stack is a section of RAM used bythe CPU to store informationtemporarilyThis information could be data or anaddressThe register used to access the stackis called the SP (stack pointer) registerThe stack pointer in the 8051 is only 8 bitwide, which means that it can take valueof 00 to FFHWhen the 8051 is powered up, the SPregister contains value 07RAM location 08 is the first location begin usedfor the stack by the 8051
  • 96. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 41HANEL8051REGISTERBANKS ANDSTACKStack(cont’)The storing of a CPU register in thestack is called a PUSHSP is pointing to the last used location ofthe stackAs we push data onto the stack, the SP isincremented by oneThis is different from many microprocessorsLoading the contents of the stack backinto a CPU register is called a POPWith every pop, the top byte of the stackis copied to the register specified by theinstruction and the stack pointer isdecremented once
  • 97. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 42HANEL8051REGISTERBANKS ANDSTACKPushing ontoStackExample 2-8Show the stack and stack pointer from the following. Assume thedefault stack area.MOV R6, #25HMOV R1, #12HMOV R4, #0F3HPUSH 6PUSH 1PUSH 4Solution:2512F3After PUSH 4SP = 0A08090A0BSP = 09SP = 08Start SP = 072508250808120909090A0A0A0B0B0BAfter PUSH 1After PUSH 6
  • 98. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 43HANEL8051REGISTERBANKS ANDSTACKPopping FromStackExample 2-9Examining the stack, show the contents of the register and SP afterexecution of the following instructions. All value are in hex.POP 3 ; POP stack into R3POP 5 ; POP stack into R5POP 2 ; POP stack into R2Solution:6CAfter POP 2SP = 0808090A0BSP = 09SP = 0AStart SP = 0B6C086C086C087609760976090AF90AF90A0B0B540BAfter POP 5After POP 3Because locations 20-2FH of RAM are reservedfor bit-addressable memory, so we can change theSP to other RAM location by using the instruction“MOV SP, #XX”
  • 99. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 44HANEL8051REGISTERBANKS ANDSTACKCALLInstruction AndStackThe CPU also uses the stack to savethe address of the instruction justbelow the CALL instructionThis is how the CPU knows where toresume when it returns from the calledsubroutine
  • 100. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 45HANEL8051REGISTERBANKS ANDSTACKIncrementingStack PointerThe reason of incrementing SP afterpush isMake sure that the stack is growingtoward RAM location 7FH, from lower toupper addressesEnsure that the stack will not reach thebottom of RAM and consequently run outof stack spaceIf the stack pointer were decrementedafter pushWe would be using RAM locations 7, 6, 5, etc.which belong to R7 to R0 of bank 0, the defaultregister bank
  • 101. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 46HANEL8051REGISTERBANKS ANDSTACKStack and Bank1 ConflictWhen 8051 is powered up, registerbank 1 and the stack are using thesame memory spaceWe can reallocate another section of RAMto the stack
  • 102. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 47HANEL8051REGISTERBANKS ANDSTACKStack And Bank1 Conflict(cont’)Example 2-10Examining the stack, show the contents of the register and SP afterexecution of the following instructions. All value are in hex.MOV SP, #5FH ;make RAM location 60H;first stack locationMOV R2, #25HMOV R1, #12HMOV R4, #0F3HPUSH 2PUSH 1PUSH 4Solution:2512F3After PUSH 4SP = 6260616263SP = 61SP = 60Start SP = 5F256025606012616161626262636363After PUSH 1After PUSH 2
  • 103. Home Automation, Networking, and Entertainment LabDept. of Computer Science and Information EngineeringNational Cheng Kung University, TAIWANChung-Ping Young楊中平JUMP, LOOP AND CALLINSTRUCTIONSThe 8051 Microcontroller and EmbeddedSystems: Using Assembly and CMazidi, Mazidi and McKinlay
  • 104. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 2HANELLOOP ANDJUMPINSTRUCTIONSLoopingRepeating a sequence of instructions acertain number of times is called aloopLoop action is performed byDJNZ reg, LabelThe register is decrementedIf it is not zero, it jumps to the target addressreferred to by the labelPrior to the start of loop the register is loadedwith the counter for the number of repetitionsCounter can be R0 – R7 or RAM location;This program adds value 3 to the ACC ten timesMOV A,#0 ;A=0, clear ACCMOV R2,#10 ;load counter R2=10AGAIN: ADD A,#03 ;add 03 to ACCDJNZ R2,AGAIN ;repeat until R2=0,10 timesMOV R5,A ;save A in R5A loop can be repeated amaximum of 255 times, ifR2 is FFH
  • 105. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 3HANELLOOP ANDJUMPINSTRUCTIONSNested LoopIf we want to repeat an action moretimes than 256, we use a loop inside aloop, which is called nested loopWe use multiple registers to hold thecountWrite a program to (a) load the accumulator with the value 55H, and(b) complement the ACC 700 timesMOV A,#55H ;A=55HMOV R3,#10 ;R3=10, outer loop countNEXT: MOV R2,#70 ;R2=70, inner loop countAGAIN: CPL A ;complement A registerDJNZ R2,AGAIN ;repeat it 70 timesDJNZ R3,NEXT
  • 106. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 4HANELLOOP ANDJUMPINSTRUCTIONSConditionalJumpsMOV A,R0 ;A=R0JZ OVER ;jump if A = 0MOV A,R1 ;A=R1JZ OVER ;jump if A = 0...OVER:Jump only if a certain condition is metJZ label ;jump if A=0Determine if R5 contains the value 0. If so, put 55H in it.MOV A,R5 ;copy R5 to AJNZ NEXT ;jump if A is not zeroMOV R5,#55HNEXT: ...Can be used only for register A,not any other register
  • 107. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 5HANELLOOP ANDJUMPINSTRUCTIONSConditionalJumps(cont’)(cont’)JNC label ;jump if no carry, CY=0If CY = 0, the CPU starts to fetch and executeinstruction from the address of the labelIf CY = 1, it will not jump but will execute the nextinstruction below JNCFind the sum of the values 79H, F5H, E2H. Put the sum in registersR0 (low byte) and R5 (high byte).MOV A,#0 ;A=0MOV R5,A ;clear R5ADD A,#79H ;A=0+79H=79H; JNC N_1 ;if CY=0, add next number; INC R5 ;if CY=1, increment R5N_1: ADD A,#0F5H ;A=79+F5=6E and CY=1JNC N_2 ;jump if CY=0INC R5 ;if CY=1,increment R5 (R5=1)N_2: ADD A,#0E2H ;A=6E+E2=50 and CY=1JNC OVER ;jump if CY=0INC R5 ;if CY=1, increment 5OVER: MOV R0,A ;now R0=50H, and R5=02MOV R5,#0
  • 108. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 6HANELLOOP ANDJUMPINSTRUCTIONSConditionalJumps(cont’)All conditional jumps are short jumpsThe address of the target must within-128 to +127 bytes of the contents of PCJump if bit = 1 and clear bitJBCJump if bit = 0JNBJump if bit = 1JBJump if CY = 0JNCJump if CY = 1JCJump if byte ≠ #dataCJNE reg,#dataJump if A ≠ byteCJNE A,byteDecrement and Jump if A ≠ 0DJNZJump if A ≠ 0JNZJump if A = 0JZActionsInstructions8051 conditional jump instructions
  • 109. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 7HANELLOOP ANDJUMPINSTRUCTIONSUnconditionalJumpsThe unconditional jump is a jump inwhich control is transferredunconditionally to the target locationLJMP (long jump)3-byte instructionFirst byte is the opcodeSecond and third bytes represent the 16-bittarget address– Any memory location from 0000 to FFFFHSJMP (short jump)2-byte instructionFirst byte is the opcodeSecond byte is the relative target address– 00 to FFH (forward +127 and backward-128 bytes from the current PC)
  • 110. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 8HANELLOOP ANDJUMPINSTRUCTIONSCalculatingShort JumpAddressTo calculate the target address of ashort jump (SJMP, JNC, JZ, DJNZ, etc.)The second byte is added to the PC of theinstruction immediately below the jumpIf the target address is more than -128to +127 bytes from the address belowthe short jump instructionThe assembler will generate an errorstating the jump is out of range
  • 111. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 9HANELLOOP ANDJUMPINSTRUCTIONSCalculatingShort JumpAddress(cont’)Line PC Opcode Mnemonic Operand01 0000 ORG 000002 0000 7800 MOV R0,#003 0002 7455 MOV A,#55H04 0004 6003 JZ NEXT05 0006 08 INC R006 0007 04 AGAIN: INC A07 0008 04 INC A08 0009 2477 NEXT: ADD A,#77H09 000B 5005 JNC OVER10 000D E4 CLR A11 000E F8 MOV R0,A12 000F F9 MOV R1,A13 0010 FA MOV R2,A14 0011 FB MOV R3,A15 0012 2B OVER: ADD A,R316 0013 50F2 JNC AGAIN17 0015 80FE HERE: SJMP HERE18 0017 END+++
  • 112. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 10HANELCALLINSTRUCTIONSCall instruction is used to call subroutineSubroutines are often used to perform tasksthat need to be performed frequentlyThis makes a program more structured inaddition to saving memory spaceLCALL (long call)3-byte instructionFirst byte is the opcodeSecond and third bytes are used for address oftarget subroutine– Subroutine is located anywhere within 64Kbyte address spaceACALL (absolute call)2-byte instruction11 bits are used for address within 2K-byte range
  • 113. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 11HANELCALLINSTRUCTIONSLCALLWhen a subroutine is called, control istransferred to that subroutine, theprocessorSaves on the stack the the address of theinstruction immediately below the LCALLBegins to fetch instructions form the newlocationAfter finishing execution of thesubroutineThe instruction RET transfers control backto the callerEvery subroutine needs RET as the lastinstruction
  • 114. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 12HANELCALLINSTRUCTIONSLCALL(cont’)ORG 0BACK: MOV A,#55H ;load A with 55HMOV P1,A ;send 55H to port 1LCALL DELAY ;time delayMOV A,#0AAH ;load A with AA (in hex)MOV P1,A ;send AAH to port 1LCALL DELAYSJMP BACK ;keep doing this indefinitely;---------- this is delay subroutine ------------ORG 300H ;put DELAY at address 300HDELAY: MOV R5,#0FFH ;R5=255 (FF in hex), counterAGAIN: DJNZ R5,AGAIN ;stay here until R5 become 0RET ;return to caller (when R5 =0)END ;end of asm fileUpon executing “LCALL DELAY”,the address of instruction below it,“MOV A,#0AAH” is pushed ontostack, and the 8051 starts to executeat 300H.The counter R5 is set toFFH; so loop is repeated255 times.When R5 becomes 0, control falls to theRET which pops the address from the stackinto the PC and resumes executing theinstructions after the CALL.The amount of time delay dependson the frequency of the 8051
  • 115. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 13HANELCALLINSTRUCTIONSCALLInstruction andStack001 0000 ORG 0002 0000 7455 BACK: MOV A,#55H ;load A with 55H003 0002 F590 MOV P1,A ;send 55H to p1004 0004 120300 LCALL DELAY ;time delay005 0007 74AA MOV A,#0AAH ;load A with AAH006 0009 F590 MOV P1,A ;send AAH to p1007 000B 120300 LCALL DELAY008 000E 80F0 SJMP BACK ;keep doing this009 0010010 0010 ;-------this is the delay subroutine------011 0300 ORG 300H012 0300 DELAY:013 0300 7DFF MOV R5,#0FFH ;R5=255014 0302 DDFE AGAIN: DJNZ R5,AGAIN ;stay here015 0304 22 RET ;return to caller016 0305 END ;end of asm file0708SP = 0900090AStack frame after the first LCALLLow byte goes firstand high byte is last
  • 116. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 14HANELCALLINSTRUCTIONSUse PUSH/POPin Subroutine01 0000 ORG 002 0000 7455 BACK: MOV A,#55H ;load A with 55H03 0002 F590 MOV P1,A ;send 55H to p104 0004 7C99 MOV R4,#99H05 0006 7D67 MOV R5,#67H06 0008 120300 LCALL DELAY ;time delay07 000B 74AA MOV A,#0AAH ;load A with AA08 000D F590 MOV P1,A ;send AAH to p109 000F 120300 LCALL DELAY10 0012 80EC SJMP BACK ;keeping doingthis11 0014 ;-------this is the delay subroutine------12 0300 ORG 300H13 0300 C004 DELAY: PUSH 4 ;push R414 0302 C005 PUSH 5 ;push R515 0304 7CFF MOV R4,#0FFH;R4=FFH16 0306 7DFF NEXT: MOV R5,#0FFH;R5=FFH17 0308 DDFE AGAIN: DJNZ R5,AGAIN18 030A DCFA DJNZ R4,NEXT19 030C D005 POP 5 ;POP into R520 030E D004 POP 4 ;POP into R421 0310 22 RET ;return to caller22 0311 END ;end of asm fileNormally, thenumber of PUSHand POPinstructions mustalways match in anycalled subroutinePCL0B08PCL0B08PCL0B08PCH0009PCH0009PCH0009R4990AR4990A0AR5670B0B0BAfter PUSH 5After PUSH 4After first LCALL
  • 117. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 15HANELCALLINSTRUCTIONSCallingSubroutines;MAIN program calling subroutinesORG 0MAIN: LCALL SUBR_1LCALL SUBR_2LCALL SUBR_3HERE: SJMP HERE;-----------end of MAINSUBR_1: ......RET;-----------end of subroutine1SUBR_2: ......RET;-----------end of subroutine2SUBR_3: ......RET;-----------end of subroutine3END ;end of the asm fileIt is common to have onemain program and manysubroutines that are calledfrom the main programThis allows you to makeeach subroutine into aseparate module- Each module can betested separately and thenbrought together withmain program- In a large program, themodule can be assigned todifferent programmers
  • 118. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 16HANELCALLINSTRUCTIONSACALLThe only difference between ACALLand LCALL isThe target address for LCALL can beanywhere within the 64K byte addressThe target address of ACALL must bewithin a 2K-byte rangeThe use of ACALL instead of LCALLcan save a number of bytes ofprogram ROM space
  • 119. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 17HANELCALLINSTRUCTIONSACALL(cont’)ORG 0MOV A,#55H ;load A with 55HBACK: MOV P1,A ;send 55H to port 1ACALL DELAY ;time delayCPL A ;complement reg ASJMP BACK ;keep doing this indefinitely...END ;end of asm fileORG 0BACK: MOV A,#55H ;load A with 55HMOV P1,A ;send 55H to port 1LCALL DELAY ;time delayMOV A,#0AAH ;load A with AA (in hex)MOV P1,A ;send AAH to port 1LCALL DELAYSJMP BACK ;keep doing this indefinitely...END ;end of asm fileA rewritten program which is more efficiently
  • 120. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 18HANELTIME DELAYFOR VARIOUS8051 CHIPSCPU executing an instruction takes acertain number of clock cyclesThese are referred as to as machine cyclesThe length of machine cycle dependson the frequency of the crystaloscillator connected to 8051In original 8051, one machine cyclelasts 12 oscillator periodsFind the period of the machine cycle for 11.0592 MHz crystalfrequencySolution:11.0592/12 = 921.6 kHz;machine cycle is 1/921.6 kHz = 1.085μs
  • 121. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 19HANELTIME DELAYFOR VARIOUS8051 CHIPS(cont’)For 8051 system of 11.0592 MHz, find how long it takes to executeeach instruction.(a) MOV R3,#55 (b) DEC R3 (c) DJNZ R2 target(d) LJMP (e) SJMP (f) NOP (g) MUL ABSolution:Machine cycles Time to execute(a) 1 1x1.085μs = 1.085μs(b) 1 1x1.085μs = 1.085μs(c) 2 2x1.085μs = 2.17μs(d) 2 2x1.085μs = 2.17μs(e) 2 2x1.085μs = 2.17μs(f) 1 1x1.085μs = 1.085μs(g) 4 4x1.085μs = 4.34μs
  • 122. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 20HANELTIME DELAYFOR VARIOUS8051 CHIPSDelayCalculationFind the size of the delay in following program, if the crystalfrequency is 11.0592MHz.MOV A,#55HAGAIN: MOV P1,AACALL DELAYCPL ASJMP AGAIN;---time delay-------DELAY: MOV R3,#200HERE: DJNZ R3,HERERETSolution:Machine cycleDELAY: MOV R3,#200 1HERE: DJNZ R3,HERE 2RET 2Therefore, [(200x2)+1+2]x1.085μs = 436.255μs.A simple way to short jumpto itself in order to keep themicrocontroller busyHERE: SJMP HEREWe can use the following:SJMP $
  • 123. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 21HANELTIME DELAYFOR VARIOUS8051 CHIPSIncreasingDelay UsingNOPFind the size of the delay in following program, if the crystalfrequency is 11.0592MHz.Machine CycleDELAY: MOV R3,#250 1HERE: NOP 1NOP 1NOP 1NOP 1DJNZ R3,HERE 2RET 2Solution:The time delay inside HERE loop is[250(1+1+1+1+2)]x1.085μs = 1627.5μs.Adding the two instructions outside loop wehave 1627.5μs + 3 x 1.085μs = 1630.755μs
  • 124. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 22HANELTIME DELAYFOR VARIOUS8051 CHIPSLarge DelayUsing NestedLoopFind the size of the delay in following program, if the crystalfrequency is 11.0592MHz.Machine CycleDELAY: MOV R2,#200 1AGAIN: MOV R3,#250 1HERE: NOP 1NOP 1DJNZ R3,HERE 2DJNZ R2,AGAIN 2RET 2Solution:For HERE loop, we have (4x250)x1.085μs=1085μs.For AGAIN loop repeats HERE loop 200 times, sowe have 200x1085μs=217000μs. But “MOVR3,#250” and “DJNZ R2,AGAIN” at the start andend of the AGAIN loop add (3x200x1.805)=651μs.As a result we have 217000+651=217651μs.Notice in nested loop,as in all other timedelay loops, the timeis approximate sincewe have ignored thefirst and lastinstructions in thesubroutine.
  • 125. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 23HANELTIME DELAYFOR VARIOUS8051 CHIPSDelayCalculation forOther 8051Two factors can affect the accuracy ofthe delayCrystal frequencyThe duration of the clock period of the machinecycle is a function of this crystal frequency8051 designThe original machine cycle duration was set at12 clocksAdvances in both IC technology and CPUdesign in recent years have made the 1-clockmachine cycle a common feature1DS89C420/30/40/50 Dallas Semi4DS5000 Dallas Semi6P89C54X2 Philips12AT89C51 AtmelClocks per Machine CycleChip/MakerClocks per machine cycle for various 8051 versions
  • 126. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 24HANELTIME DELAYFOR VARIOUS8051 CHIPSDelayCalculation forOther 8051(cont’)Find the period of the machine cycle (MC) for various versions of8051, if XTAL=11.0592 MHz.(a) AT89C51 (b) P89C54X2 (c) DS5000 (d) DS89C4x0Solution:(a) 11.0592MHz/12 = 921.6kHz;MC is 1/921.6kHz = 1.085μs = 1085ns(b) 11.0592MHz/6 = 1.8432MHz;MC is 1/1.8432MHz = 0.5425μs = 542ns(c) 11.0592MHz/4 = 2.7648MHz ;MC is 1/2.7648MHz = 0.36μs = 360ns(d) 11.0592MHz/1 = 11.0592MHz;MC is 1/11.0592MHz = 0.0904μs = 90ns
  • 127. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 25HANELTIME DELAYFOR VARIOUS8051 CHIPSDelayCalculation forOther 8051(cont’)For an AT8051 and DSC89C4x0 system of 11.0592 MHz, find howlong it takes to execute each instruction.(a) MOV R3,#55 (b) DEC R3 (c) DJNZ R2 target(d) LJMP (e) SJMP (f) NOP (g) MUL ABSolution:AT8051 DS89C4x0(a) 1 1085ns = 1085ns 2 90ns = 180ns(b) 1 1085ns = 1085ns 1 90ns = 90ns(c) 2 1085ns = 2170ns 4 90ns = 360ns(d) 2 1085ns = 2170ns 3 90ns = 270ns(e) 2 1085ns = 2170ns 3 90ns = 270ns(f) 1 1085ns = 1085ns 1 90ns = 90ns(g) 4 1085ns = 4340ns 9 90ns = 810ns11NOP32SJMP32LJMP421180519MUL AB4DJNZ R2 target1DEC R32MOV R3,#55DSC89C4x0Instruction
  • 128. Home Automation, Networking, and Entertainment LabDept. of Computer Science and Information EngineeringNational Cheng Kung University, TAIWANChung-Ping Young楊中平I/O PORTPROGRAMMINGThe 8051 Microcontroller and EmbeddedSystems: Using Assembly and CMazidi, Mazidi and McKinlay
  • 129. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 2HANELI/OPROGRAMMING8051(8031)(89420)P1.0P1.1P1.2P1.3P1.4P1.5P1.6P1.7RST(RXD) P3.0(TXD) P3.1(-INT0) P3.2(-INT1) P3.3(T0) P3.4(T1) P3.5(-WR) P3.6(-RD )P3.7XTAL2XTAL1GNDVccP0.0 (AD0)P0.1 (AD1)P0.2 (AD2)P0.3 (AD3)P0.4 (AD4)P0.5 (AD5)P0.6 (AD6)P0.7 (AD7)-EA/VPPALE/PROG-PSENP2.7 (A15)P2.6 (A14)P2.5 (A13)P2.4 (A12)P2.3 (A11)P2.2 (A10)P2.1 (A9)P2.0 (A8)12345678910111213141516171819204039383736353433323130292827262524232221Provides+5V supplyvoltage tothe chipGrondP1P38051 Pin DiagramA total of 32pins are setaside for thefour ports P0,P1, P2, P3,where eachport takes 8pinsP0P2
  • 130. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 3HANELI/OPROGRAMMINGI/O Port PinsThe four 8-bit I/O ports P0, P1, P2 andP3 each uses 8 pinsAll the ports upon RESET areconfigured as input, ready to be usedas input portsWhen the first 0 is written to a port, itbecomes an outputTo reconfigure it as an input, a 1 must besent to the portTo use any of these ports as an input port, itmust be programmedP1.0P1.1P1.2P1.3P1.4P1.5P1.6P1.7RST(RXD)P3.0(TXD)P3.1(INT0)P3.2(INT1)P3.3(T0)P3.4(T1)P3.5(WR)P3.6(RD)P3.7XTAL2XTAL1GNDVccP0.0(AD0)P0.1(AD1)P0.2(AD2)P0.3(AD3)P0.4(AD4)P0.5(AD5)P0.6(AD6)P0.7(AD7)-EA/VPPALE/PROG-PSENP2.7(A15)P2.6(A14)P2.5(A13)P2.4(A12)P2.3(A11)P2.2(A10)P2.1(A9)P2.0(A8)123456789101112131415161718192040393837363534333231302928272625242322218051(8031)
  • 131. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 4HANELI/OPROGRAMMINGPort 0It can be used for input or output,each pin must be connected externallyto a 10K ohm pull-up resistorThis is due to the fact that P0 is an opendrain, unlike P1, P2, and P3Open drain is a term used for MOS chips in thesame way that open collector is used for TTLchipsP0.0P0.1P0.2P0.3P0.4P0.5P0.6P0.7Vcc10 K8051Port0P1.0P1.1P1.2P1.3P1.4P1.5P1.6P1.7RST(RXD)P3.0(TXD)P3.1(INT0)P3.2(INT1)P3.3(T0)P3.4(T1)P3.5(WR)P3.6(RD)P3.7XTAL2XTAL1GNDVccP0.0(AD0)P0.1(AD1)P0.2(AD2)P0.3(AD3)P0.4(AD4)P0.5(AD5)P0.6(AD6)P0.7(AD7)-EA/VPPALE/PROG-PSENP2.7(A15)P2.6(A14)P2.5(A13)P2.4(A12)P2.3(A11)P2.2(A10)P2.1(A9)P2.0(A8)123456789101112131415161718192040393837363534333231302928272625242322218051(8031)P0.X
  • 132. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 5HANELI/OPROGRAMMINGPort 0(cont’)The following code will continuously send out to port 0 thealternating value 55H and AAHBACK: MOV A,#55HMOV P0,AACALL DELAYMOV A,#0AAHMOV P0,AACALL DELAYSJMP BACKP1.0P1.1P1.2P1.3P1.4P1.5P1.6P1.7RST(RXD)P3.0(TXD)P3.1(INT0)P3.2(INT1)P3.3(T0)P3.4(T1)P3.5(WR)P3.6(RD)P3.7XTAL2XTAL1GNDVccP0.0(AD0)P0.1(AD1)P0.2(AD2)P0.3(AD3)P0.4(AD4)P0.5(AD5)P0.6(AD6)P0.7(AD7)-EA/VPPALE/PROG-PSENP2.7(A15)P2.6(A14)P2.5(A13)P2.4(A12)P2.3(A11)P2.2(A10)P2.1(A9)P2.0(A8)123456789101112131415161718192040393837363534333231302928272625242322218051(8031)
  • 133. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 6HANELI/OPROGRAMMINGPort 0 as InputIn order to make port 0 an input, theport must be programmed by writing 1to all the bitsPort 0 is configured first as an input port by writing 1s to it, and thendata is received from that port and sent to P1MOV A,#0FFH ;A=FF hexMOV P0,A ;make P0 an i/p port;by writing it all 1sBACK: MOV A,P0 ;get data from P0MOV P1,A ;send it to port 1SJMP BACK ;keep doing itP1.0P1.1P1.2P1.3P1.4P1.5P1.6P1.7RST(RXD)P3.0(TXD)P3.1(INT0)P3.2(INT1)P3.3(T0)P3.4(T1)P3.5(WR)P3.6(RD)P3.7XTAL2XTAL1GNDVccP0.0(AD0)P0.1(AD1)P0.2(AD2)P0.3(AD3)P0.4(AD4)P0.5(AD5)P0.6(AD6)P0.7(AD7)-EA/VPPALE/PROG-PSENP2.7(A15)P2.6(A14)P2.5(A13)P2.4(A12)P2.3(A11)P2.2(A10)P2.1(A9)P2.0(A8)123456789101112131415161718192040393837363534333231302928272625242322218051(8031)
  • 134. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 7HANELI/OPROGRAMMINGDual Role ofPort 0Port 0 is also designated as AD0-AD7,allowing it to be used for both addressand dataWhen connecting an 8051/31 to anexternal memory, port 0 provides bothaddress and dataP1.0P1.1P1.2P1.3P1.4P1.5P1.6P1.7RST(RXD)P3.0(TXD)P3.1(INT0)P3.2(INT1)P3.3(T0)P3.4(T1)P3.5(WR)P3.6(RD)P3.7XTAL2XTAL1GNDVccP0.0(AD0)P0.1(AD1)P0.2(AD2)P0.3(AD3)P0.4(AD4)P0.5(AD5)P0.6(AD6)P0.7(AD7)-EA/VPPALE/PROG-PSENP2.7(A15)P2.6(A14)P2.5(A13)P2.4(A12)P2.3(A11)P2.2(A10)P2.1(A9)P2.0(A8)123456789101112131415161718192040393837363534333231302928272625242322218051(8031)
  • 135. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 8HANELI/OPROGRAMMINGPort 1Port 1 can be used as input or outputIn contrast to port 0, this port does notneed any pull-up resistors since it alreadyhas pull-up resistors internallyUpon reset, port 1 is configured as aninput portP1.0P1.1P1.2P1.3P1.4P1.5P1.6P1.7RST(RXD)P3.0(TXD)P3.1(INT0)P3.2(INT1)P3.3(T0)P3.4(T1)P3.5(WR)P3.6(RD)P3.7XTAL2XTAL1GNDVccP0.0(AD0)P0.1(AD1)P0.2(AD2)P0.3(AD3)P0.4(AD4)P0.5(AD5)P0.6(AD6)P0.7(AD7)-EA/VPPALE/PROG-PSENP2.7(A15)P2.6(A14)P2.5(A13)P2.4(A12)P2.3(A11)P2.2(A10)P2.1(A9)P2.0(A8)123456789101112131415161718192040393837363534333231302928272625242322218051(8031)The following code will continuously send out to port 0 thealternating value 55H and AAHMOV A,#55HBACK: MOV P1,AACALL DELAYCPL ASJMP BACK
  • 136. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 9HANELI/OPROGRAMMINGPort 1 as InputTo make port 1 an input port, it mustbe programmed as such by writing 1to all its bitsP1.0P1.1P1.2P1.3P1.4P1.5P1.6P1.7RST(RXD)P3.0(TXD)P3.1(INT0)P3.2(INT1)P3.3(T0)P3.4(T1)P3.5(WR)P3.6(RD)P3.7XTAL2XTAL1GNDVccP0.0(AD0)P0.1(AD1)P0.2(AD2)P0.3(AD3)P0.4(AD4)P0.5(AD5)P0.6(AD6)P0.7(AD7)-EA/VPPALE/PROG-PSENP2.7(A15)P2.6(A14)P2.5(A13)P2.4(A12)P2.3(A11)P2.2(A10)P2.1(A9)P2.0(A8)123456789101112131415161718192040393837363534333231302928272625242322218051(8031)Port 1 is configured first as an input port by writing 1s to it, then datais received from that port and saved in R7 and R5MOV A,#0FFH ;A=FF hexMOV P1,A ;make P1 an input port;by writing it all 1sMOV A,P1 ;get data from P1MOV R7,A ;save it to in reg R7ACALL DELAY ;waitMOV A,P1 ;another data from P1MOV R5,A ;save it to in reg R5
  • 137. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 10HANELI/OPROGRAMMINGPort 2Port 2 can be used as input or outputJust like P1, port 2 does not need any pull-up resistors since it already has pull-upresistors internallyUpon reset, port 2 is configured as an inputportP1.0P1.1P1.2P1.3P1.4P1.5P1.6P1.7RST(RXD)P3.0(TXD)P3.1(INT0)P3.2(INT1)P3.3(T0)P3.4(T1)P3.5(WR)P3.6(RD)P3.7XTAL2XTAL1GNDVccP0.0(AD0)P0.1(AD1)P0.2(AD2)P0.3(AD3)P0.4(AD4)P0.5(AD5)P0.6(AD6)P0.7(AD7)-EA/VPPALE/PROG-PSENP2.7(A15)P2.6(A14)P2.5(A13)P2.4(A12)P2.3(A11)P2.2(A10)P2.1(A9)P2.0(A8)123456789101112131415161718192040393837363534333231302928272625242322218051(8031)
  • 138. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 11HANELI/OPROGRAMMINGPort 2 as Inputor Dual RoleTo make port 2 an input port, it mustbe programmed as such by writing 1 toall its bitsIn many 8051-based system, P2 is usedas simple I/OIn 8031-based systems, port 2 must beused along with P0 to provide the 16-bit address for the external memoryPort 2 is also designated as A8 – A15,indicating its dual functionPort 0 provides the lower 8 bits via A0 – A7P1.0P1.1P1.2P1.3P1.4P1.5P1.6P1.7RST(RXD)P3.0(TXD)P3.1(INT0)P3.2(INT1)P3.3(T0)P3.4(T1)P3.5(WR)P3.6(RD)P3.7XTAL2XTAL1GNDVccP0.0(AD0)P0.1(AD1)P0.2(AD2)P0.3(AD3)P0.4(AD4)P0.5(AD5)P0.6(AD6)P0.7(AD7)-EA/VPPALE/PROG-PSENP2.7(A15)P2.6(A14)P2.5(A13)P2.4(A12)P2.3(A11)P2.2(A10)P2.1(A9)P2.0(A8)123456789101112131415161718192040393837363534333231302928272625242322218051(8031)
  • 139. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 12HANELI/OPROGRAMMINGPort 3Port 3 can be used as input or outputPort 3 does not need any pull-up resistorsPort 3 is configured as an input port uponreset, this is not the way it is mostcommonly usedP1.0P1.1P1.2P1.3P1.4P1.5P1.6P1.7RST(RXD)P3.0(TXD)P3.1(INT0)P3.2(INT1)P3.3(T0)P3.4(T1)P3.5(WR)P3.6(RD)P3.7XTAL2XTAL1GNDVccP0.0(AD0)P0.1(AD1)P0.2(AD2)P0.3(AD3)P0.4(AD4)P0.5(AD5)P0.6(AD6)P0.7(AD7)-EA/VPPALE/PROG-PSENP2.7(A15)P2.6(A14)P2.5(A13)P2.4(A12)P2.3(A11)P2.2(A10)P2.1(A9)P2.0(A8)123456789101112131415161718192040393837363534333231302928272625242322218051(8031)
  • 140. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 13HANELI/OPROGRAMMINGPort 3(cont’)Port 3 has the additional function ofproviding some extremely importantsignalsP1.0P1.1P1.2P1.3P1.4P1.5P1.6P1.7RST(RXD)P3.0(TXD)P3.1(INT0)P3.2(INT1)P3.3(T0)P3.4(T1)P3.5(WR)P3.6(RD)P3.7XTAL2XTAL1GNDVccP0.0(AD0)P0.1(AD1)P0.2(AD2)P0.3(AD3)P0.4(AD4)P0.5(AD5)P0.6(AD6)P0.7(AD7)-EA/VPPALE/PROG-PSENP2.7(A15)P2.6(A14)P2.5(A13)P2.4(A12)P2.3(A11)P2.2(A10)P2.1(A9)P2.0(A8)123456789101112131415161718192040393837363534333231302928272625242322218051(8031)P3 Bit FunctionP3.0 RxDTxDINT0INT1T0T1WRRDP3.1P3.2P3.3P3.4P3.5P3.6P3.7Pin1011121314151617SerialcommunicationsExternalinterruptsTimersRead/Write signalsof external memoriesIn systems based on 8751, 89C51 orDS89C4x0, pins 3.6 and 3.7 are used for I/Owhile the rest of the pins in port 3 arenormally used in the alternate function role
  • 141. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 14HANELI/OPROGRAMMINGPort 3(cont’)P1.0P1.1P1.2P1.3P1.4P1.5P1.6P1.7RST(RXD)P3.0(TXD)P3.1(INT0)P3.2(INT1)P3.3(T0)P3.4(T1)P3.5(WR)P3.6(RD)P3.7XTAL2XTAL1GNDVccP0.0(AD0)P0.1(AD1)P0.2(AD2)P0.3(AD3)P0.4(AD4)P0.5(AD5)P0.6(AD6)P0.7(AD7)-EA/VPPALE/PROG-PSENP2.7(A15)P2.6(A14)P2.5(A13)P2.4(A12)P2.3(A11)P2.2(A10)P2.1(A9)P2.0(A8)123456789101112131415161718192040393837363534333231302928272625242322218051(8031)Write a program for the DS89C420 to toggle all the bits of P0, P1,and P2 every 1/4 of a secondORG 0BACK: MOV A,#55HMOV P0,AMOV P1,AMOV P2,AACALL QSDELAY ;Quarter of a secondMOV A,#0AAHMOV P0,AMOV P1,AMOV P2,AACALL QSDELAYSJMP BACKQSDELAY:MOV R5,#11H3: MOV R4,#248H2: MOV R3,#255H1: DJNZ R3,H1 ;4 MC for DS89C4x0DJNZ R4,H2DJNZ R5,H3RETENDDelay= 11 × 248 × 255 × 4 MC × 90 ns= 250,430 µs
  • 142. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 15HANELI/OPROGRAMMINGDifferent waysof AccessingEntire 8 BitsThe entire 8 bits of Port 1 are accessedBACK: MOV A,#55HMOV P1,AACALL DELAYMOV A,#0AAHMOV P1,AACALL DELAYSJMP BACKRewrite the code in a more efficient manner by accessing the portdirectly without going through the accumulatorBACK: MOV P1,#55HACALL DELAYMOV P1,#0AAHACALL DELAYSJMP BACKAnother way of doing the same thingMOV A,#55HBACK: MOV P1,AACALL DELAYCPL ASJMP BACK
  • 143. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 16HANELI/O BITMANIPULATIONPROGRAMMINGI/O Portsand BitAddressabilitySometimes we need to access only 1or 2 bits of the portBACK: CPL P1.2 ;complement P1.2ACALL DELAYSJMP BACK;another variation of the above programAGAIN: SETB P1.2 ;set only P1.2ACALL DELAYCLR P1.2 ;clear only P1.2ACALL DELAYSJMP AGAIN P0 P1 P2 P3P1.0 P2.0P2.1P2.2P2.3P2.4P2.5P2.6P2.7P1.1P3.0P3.1P3.2P3.3P3.4P3.5P3.6P1.2P1.3P1.4P1.5P1.6P1.7 P3.7P0.0P0.1P0.2P0.3P0.4P0.5P0.6P0.7Port BitD0D1D2D3D4D5D6D7
  • 144. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 17HANELI/O BITMANIPULATIONPROGRAMMINGI/O Portsand BitAddressability(cont’)Example 4-2Write the following programs.Create a square wave of 50% duty cycle on bit 0 of port 1.Solution:The 50% duty cycle means that the “on” and “off” state (or the highand low portion of the pulse) have the same length. Therefore,we toggle P1.0 with a time delay in between each state.HERE: SETB P1.0 ;set to high bit 0 of port 1LCALL DELAY ;call the delay subroutineCLR P1.0 ;P1.0=0LCALL DELAYSJMP HERE ;keep doing itAnother way to write the above program is:HERE: CPL P1.0 ;set to high bit 0 of port 1LCALL DELAY ;call the delay subroutineSJMP HERE ;keep doing it8051P1.0
  • 145. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 18HANELI/O BITMANIPULATIONPROGRAMMINGI/O Portsand BitAddressability(cont’)Instructions that are used for signal-bitoperations are as followingInstruction FunctionSETB bit Set the bit (bit = 1)CLR bit Clear the bit (bit = 0)CPL bit Complement the bit (bit = NOT bit)JB bit, target Jump to target if bit = 1 (jump if bit)JNB bit, target Jump to target if bit = 0 (jump if no bit)JBC bit, target Jump to target if bit = 1, clear bit(jump if bit, then clear)Single-Bit Instructions
  • 146. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 19HANELI/O BITMANIPULATIONPROGRAMMINGChecking anInput BitThe JNB and JB instructions are widelyused single-bit operationsThey allow you to monitor a bit and makea decision depending on whether it’s 0 or 1These two instructions can be used for anybits of I/O ports 0, 1, 2, and 3Port 3 is typically not used for any I/O, eithersingle-bit or byte-wiseMnemonic Examples DescriptionMOV A,PX MOV A,P2 Bring into A the data at P2 pinsJNB PX.Y, .. JNB P2.1,TARGET Jump if pin P2.1 is lowJB PX.Y, .. JB P1.3,TARGET Jump if pin P1.3 is highMOV C,PX.Y MOV C,P2.4 Copy status of pin P2.4 to CYInstructions for Reading an Input Port
  • 147. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 20HANELI/O BITMANIPULATIONPROGRAMMINGChecking anInput Bit(cont’)Example 4-3Write a program to perform the following:(a) Keep monitoring the P1.2 bit until it becomes high(b) When P1.2 becomes high, write value 45H to port 0(c) Send a high-to-low (H-to-L) pulse to P2.3Solution:SETB P1.2 ;make P1.2 an inputMOV A,#45H ;A=45HAGAIN: JNB P1.2,AGAIN ; get out when P1.2=1MOV P0,A ;issue A to P0SETB P2.3 ;make P2.3 highCLR P2.3 ;make P2.3 low for H-to-L
  • 148. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 21HANELI/O BITMANIPULATIONPROGRAMMINGChecking anInput Bit(cont’)Example 4-4Assume that bit P2.3 is an input and represents the condition of anoven. If it goes high, it means that the oven is hot. Monitor the bitcontinuously. Whenever it goes high, send a high-to-low pulse to portP1.5 to turn on a buzzer.Solution:HERE: JNB P2.3,HERE ;keep monitoring for highSETB P1.5 ;set bit P1.5=1CLR P1.5 ;make high-to-lowSJMP HERE ;keep repeating
  • 149. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 22HANELI/O BITMANIPULATIONPROGRAMMINGChecking anInput Bit(cont’)Example 4-5A switch is connected to pin P1.7. Write a program to check the statusof SW and perform the following:(a) If SW=0, send letter ‘N’ to P2(b) If SW=1, send letter ‘Y’ to P2Solution:SETB P1.7 ;make P1.7 an inputAGAIN: JB P1.2,OVER ;jump if P1.7=1MOV P2,#’N’ ;SW=0, issue ‘N’ to P2SJMP AGAIN ;keep monitoringOVER: MOV P2,#’Y’ ;SW=1, issue ‘Y’ to P2SJMP AGAIN ;keep monitoring
  • 150. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 23HANELI/O BITMANIPULATIONPROGRAMMINGReading SingleBit into CarryFlagExample 4-6A switch is connected to pin P1.7. Write a program to check the statusof SW and perform the following:(a) If SW=0, send letter ‘N’ to P2(b) If SW=1, send letter ‘Y’ to P2Use the carry flag to check the switch status.Solution:SETB P1.7 ;make P1.7 an inputAGAIN: MOV C,P1.2 ;read SW status into CFJC OVER ;jump if SW=1MOV P2,#’N’ ;SW=0, issue ‘N’ to P2SJMP AGAIN ;keep monitoringOVER: MOV P2,#’Y’ ;SW=1, issue ‘Y’ to P2SJMP AGAIN ;keep monitoring
  • 151. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 24HANELI/O BITMANIPULATIONPROGRAMMINGReading SingleBit into CarryFlag(cont’)Example 4-7A switch is connected to pin P1.0 and an LED to pin P2.7. Write aprogram to get the status of the switch and send it to the LEDSolution:SETB P1.7 ;make P1.7 an inputAGAIN: MOV C,P1.0 ;read SW status into CFMOV P2.7,C ;send SW status to LEDSJMP AGAIN ;keep repeatingThe instruction‘MOVP2.7,P1.0’ iswrong , since suchan instruction doesnot existHowever ‘MOVP2,P1’ is a validinstruction
  • 152. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 25HANELI/O BITMANIPULATIONPROGRAMMINGReading InputPins vs. PortLatchIn reading a portSome instructions read the status of portpinsOthers read the status of an internal portlatchTherefore, when reading ports thereare two possibilities:Read the status of the input pinRead the internal latch of the output portConfusion between them is a majorsource of errors in 8051 programmingEspecially where external hardware isconcerned
  • 153. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 26HANELREADINGINPUT PINS VS.PORT LATCHReading Latchfor Output PortSome instructions read the contents ofan internal port latch instead ofreading the status of an external pinFor example, look at the ANL P1,Ainstruction and the sequence of actions isexecuted as follow1. It reads the internal latch of the port andbrings that data into the CPU2. This data is ANDed with the contents ofregister A3. The result is rewritten back to the port latch4. The port pin data is changed and now has thesame value as port latch
  • 154. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 27HANELREADINGINPUT PINS VS.PORT LATCHReading Latchfor Output Port(cont’)Read-Modify-WriteThe instructions read the port latchnormally read a value, perform anoperation then rewrite it back to the portlatchMnemonics ExampleANL PX ANL P1,AORL PX ORL P2,AXRL PX XRL P0,AJBC PX.Y,TARGET JBC P1.1,TARGETCPL PX.Y CPL P1.2INC PX INC P1DEC PX DEC P2DJNZ PX.Y,TARGET DJNZ P1,TARGETMOV PX.Y,C MOV P1.2,CCLR PX.Y CLR P2.3SETB PX.Y SETB P2.3Instructions Reading a latch (Read-Modify-Write)Note: x is 0, 1, 2,or 3 for P0 – P3
  • 155. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 28HANELI/O BITMANIPULATIONPROGRAMMINGRead-modify-write FeatureThe ports in 8051 can be accessed bythe Read-modify-write techniqueThis feature saves many lines of code bycombining in a single instruction all threeactions1. Reading the port2. Modifying it3. Writing to the portMOV P1,#55H ;P1=01010101AGAIN: XRL P1,#0FFH ;EX-OR P1 with 1111 1111ACALL DELAYSJMP BACK
  • 156. Home Automation, Networking, and Entertainment LabDept. of Computer Science and Information EngineeringNational Cheng Kung University, TAIWANChung-Ping Young楊中平ADDRESSING MODESThe 8051 Microcontroller and EmbeddedSystems: Using Assembly and CMazidi, Mazidi and McKinlay
  • 157. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 2HANELADDRESSINGMODESThe CPU can access data in variousways, which are called addressingmodesImmediateRegisterDirectRegister indirectIndexedAccessingmemories
  • 158. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 3HANELIMMEDIATEADDRESSINGMODEThe source operand is a constantThe immediate data must be preceded bythe pound sign, “#”Can load information into any registers,including 16-bit DPTR registerDPTR can also be accessed as two 8-bitregisters, the high byte DPH and low byte DPLMOV A,#25H ;load 25H into AMOV R4,#62 ;load 62 into R4MOV B,#40H ;load 40H into BMOV DPTR,#4521H ;DPTR=4512HMOV DPL,#21H ;This is the sameMOV DPH,#45H ;as above;illegal!! Value > 65535 (FFFFH)MOV DPTR,#68975
  • 159. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 4HANELIMMEDIATEADDRESSINGMODE(cont’)We can use EQU directive to accessimmediate dataWe can also use immediate addressingmode to send data to 8051 portsCount EQU 30... ...MOV R4,#COUNT ;R4=1EHMOV DPTR,#MYDATA ;DPTR=200HORG 200HMYDATA: DB “America”MOV P1,#55H
  • 160. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 5HANELREGISTERADDRESSINGMODEUse registers to hold the data to bemanipulatedThe source and destination registersmust match in sizeMOV DPTR,A will give an errorThe movement of data between Rnregisters is not allowedMOV R4,R7 is invalidMOV A,R0 ;copy contents of R0 into AMOV R2,A ;copy contents of A into R2ADD A,R5 ;add contents of R5 to AADD A,R7 ;add contents of R7 to AMOV R6,A ;save accumulator in R6MOV DPTR,#25F5HMOV R7,DPLMOV R6,DPH
  • 161. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 6HANELACCESSINGMEMORYDirectAddressingModeIt is most often used the directaddressing mode to access RAMlocations 30 – 7FHThe entire 128 bytes of RAM can beaccessedThe register bank locations are accessedby the register namesContrast this with immediateaddressing modeThere is no “#” sign in the operandMOV R0,40H ;save content of 40H in R0MOV 56H,A ;save content of A in 56HMOV A,4 ;is same asMOV A,R4 ;which means copy R4 into ARegister addressing modeDirect addressing mode
  • 162. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 7HANELACCESSINGMEMORYSFR Registersand TheirAddressesThe SFR (Special Function Register)can be accessed by their names or bytheir addressesThe SFR registers have addressesbetween 80H and FFHNot all the address space of 80 to FF isused by SFRThe unused locations 80H to FFH arereserved and must not be used by the8051 programmerMOV 0E0H,#55H ;is the same asMOV A,#55h ;load 55H into AMOV 0F0H,R0 ;is the same asMOV B,R0 ;copy R0 into B
  • 163. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 8HANELACCESSINGMEMORYSFR Registersand TheirAddresses(cont’)0A8HInterrupt enable controlIE*………0B8HInterrupt priority controlIP*0B0HPort 3P3*0A0HPort 2P2*90HPort 1P1*80HPort 0P0*83HHigh byteDPH82HLow byteDPLData pointer 2 bytesDPTR81HStack pointerSP0D0HProgram status wordPSW*0F0HB registerB*0E0HAccumulatorACC*AddressNameSymbolSpecial Function Register (SFR) Addresses
  • 164. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 9HANELACCESSINGMEMORYSFR Registersand TheirAddresses(cont’)89HTimer/counter mode controlTMOD88HTimer/counter controlTCON*0C8HTimer/counter 2 controlT2CON*87HPower ontrolPCON* Bit addressable99HSerial data bufferSBUF98HSerial controlSCON*0CAHT/C 2 capture register low byteRCAP2L0CBHT/C 2 capture register high byteRCAP2H0CCHTimer/counter 2 low byteTL20CDHTimer/counter 2 high byteTH28BHTimer/counter 1 low byteTL18DHTimer/counter 1 high byteTH18AHTimer/counter 0 low byteTL08CHTimer/counter 0 high byteTH0OC9HTimer/counter mode controlT2MODAddressNameSymbolSpecial Function Register (SFR) Addresses
  • 165. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 10HANELACCESSINGMEMORYSFR Registersand TheirAddresses(cont’)Example 5-1Write code to send 55H to ports P1 and P2, using(a) their names (b) their addressesSolution :(a) MOV A,#55H ;A=55HMOV P1,A ;P1=55HMOV P2,A ;P2=55H(b) From Table 5-1, P1 address=80H; P2 address=A0HMOV A,#55H ;A=55HMOV 80H,A ;P1=55HMOV 0A0H,A ;P2=55H
  • 166. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 11HANELACCESSINGMEMORYStack andDirectAddressingModeOnly direct addressing mode is allowedfor pushing or popping the stackPUSH A is invalidPushing the accumulator onto the stackmust be coded as PUSH 0E0HExample 5-2Show the code to push R5 and A onto the stack and then pop themback them into R2 and B, where B = A and R2 = R5Solution:PUSH 05 ;push R5 onto stackPUSH 0E0H ;push register A onto stackPOP 0F0H ;pop top of stack into B;now register B = register APOP 02 ;pop top of stack into R2;now R2=R6
  • 167. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 12HANELACCESSINGMEMORYRegisterIndirectAddressingModeA register is used as a pointer to thedataOnly register R0 and R1 are used for thispurposeR2 – R7 cannot be used to hold theaddress of an operand located in RAMWhen R0 and R1 hold the addresses ofRAM locations, they must be precededby the “@” signMOV A,@R0 ;move contents of RAM whose;address is held by R0 into AMOV @R1,B ;move contents of B into RAM;whose address is held by R1
  • 168. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 13HANELACCESSINGMEMORYRegisterIndirectAddressingMode(cont’)Example 5-3Write a program to copy the value 55H into RAM memory locations40H to 41H using(a) direct addressing mode, (b) register indirect addressing modewithout a loop, and (c) with a loopSolution:(a)MOV A,#55H ;load A with value 55HMOV 40H,A ;copy A to RAM location 40HMOV 41H.A ;copy A to RAM location 41H(b)MOV A,#55H ;load A with value 55HMOV R0,#40H ;load the pointer. R0=40HMOV @R0,A ;copy A to RAM R0 points toINC R0 ;increment pointer. Now R0=41hMOV @R0,A ;copy A to RAM R0 points to(c)MOV A,#55H ;A=55HMOV R0,#40H ;load pointer.R0=40H,MOV R2,#02 ;load counter, R2=3AGAIN: MOV @R0,A ;copy 55 to RAM R0 points toINC R0 ;increment R0 pointerDJNZ R2,AGAIN ;loop until counter = zero
  • 169. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 14HANELACCESSINGMEMORYRegisterIndirectAddressingMode(cont’)The advantage is that it makesaccessing data dynamic rather thanstatic as in direct addressing modeLooping is not possible in directaddressing modeExample 5-4Write a program to clear 16 RAM locations starting at RAM address60HSolution:CLR A ;A=0MOV R1,#60H ;load pointer. R1=60HMOV R7,#16 ;load counter, R7=16AGAIN: MOV @R1,A ;clear RAM R1 points toINC R1 ;increment R1 pointerDJNZ R7,AGAIN ;loop until counter=zero
  • 170. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 15HANELACCESSINGMEMORYRegisterIndirectAddressingMode(cont’)Example 5-5Write a program to copy a block of 10 bytes of data from 35H to 60HSolution:MOV R0,#35H ;source pointerMOV R1,#60H ;destination pointerMOV R3,#10 ;counterBACK: MOV A,@R0 ;get a byte from sourceMOV @R1,A ;copy it to destinationINC R0 ;increment source pointerINC R1 ;increment destination pointerDJNZ R3,BACK ;keep doing for ten bytes
  • 171. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 16HANELACCESSINGMEMORYRegisterIndirectAddressingMode(cont’)R0 and R1 are the only registers thatcan be used for pointers in registerindirect addressing modeSince R0 and R1 are 8 bits wide, theiruse is limited to access anyinformation in the internal RAMWhether accessing externallyconnected RAM or on-chip ROM, weneed 16-bit pointerIn such case, the DPTR register is used
  • 172. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 17HANELACCESSINGMEMORYIndexedAddressingMode andOn-chip ROMAccessIndexed addressing mode is widelyused in accessing data elements oflook-up table entries located in theprogram ROMThe instruction used for this purpose isMOVC A,@A+DPTRUse instruction MOVC, “C” means codeThe contents of A are added to the 16-bitregister DPTR to form the 16-bit addressof the needed data
  • 173. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 18HANELACCESSINGMEMORYIndexedAddressingMode and On-chip ROMAccess(cont’)Example 5-6In this program, assume that the word “USA” is burned into ROMlocations starting at 200H. And that the program is burned into ROMlocations starting at 0. Analyze how the program works and statewhere “USA” is stored after this program is run.Solution:ORG 0000H ;burn into ROM starting at 0MOV DPTR,#200H ;DPTR=200H look-up table addrCLR A ;clear A(A=0)MOVC A,@A+DPTR ;get the char from code spaceMOV R0,A ;save it in R0INC DPTR ;DPTR=201 point to next charCLR A ;clear A(A=0)MOVC A,@A+DPTR ;get the next charMOV R1,A ;save it in R1INC DPTR ;DPTR=202 point to next charCLR A ;clear A(A=0)MOVC A,@A+DPTR ;get the next charMOV R2,A ;save it in R2Here: SJMP HERE ;stay here;Data is burned into code space starting at 200HORG 200HMYDATA:DB “USA”END ;end of programDPTR=200H, A=0U200S201A202DPTR=200H, A=55HDPTR=201H, A=55HDPTR=201H, A=0DPTR=201H, A=53HDPTR=202H, A=53HR0=55HR1=53HR2=41H
  • 174. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 19HANELACCESSINGMEMORYLook-up Table(cont’)The look-up table allows access toelements of a frequently used tablewith minimum operationsExample 5-8Write a program to get the x value from P1 and send x2to P2,continuouslySolution:ORG 0MOV DPTR,#300H ;LOAD TABLE ADDRESSMOV A,#0FFH ;A=FFMOV P1,A ;CONFIGURE P1 INPUT PORTBACK:MOV A,P1 ;GET XMOV A,@A+DPTR ;GET X SQAURE FROM TABLEMOV P2,A ;ISSUE IT TO P2SJMP BACK ;KEEP DOING ITORG 300HXSQR_TABLE:DB 0,1,4,9,16,25,36,49,64,81END
  • 175. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 20HANELACCESSINGMEMORYIndexedAddressingMode andMOVXIn many applications, the size ofprogram code does not leave anyroom to share the 64K-byte codespace with dataThe 8051 has another 64K bytes ofmemory space set aside exclusively fordata storageThis data memory space is referred to asexternal memory and it is accessed only by theMOVX instructionThe 8051 has a total of 128K bytes ofmemory space64K bytes of code and 64K bytes of dataThe data space cannot be shared betweencode and data
  • 176. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 21HANELACCESSINGMEMORYRAM Locations30 – 7FH asScratch PadIn many applications we use RAMlocations 30 – 7FH as scratch padWe use R0 – R7 of bank 0Leave addresses 8 – 1FH for stack usageIf we need more registers, we simply useRAM locations 30 – 7FHExample 5-10Write a program to toggle P1 a total of 200 times. Use RAMlocation 32H to hold your counter value instead of registers R0 –R7Solution:MOV P1,#55H ;P1=55HMOV 32H,#200 ;load counter value;into RAM loc 32HLOP1: CPL P1 ;toggle P1ACALL DELAYDJNZ 32H,LOP1 ;repeat 200 times
  • 177. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 22HANELBITADDRESSESMany microprocessors allow programto access registers and I/O ports inbyte size onlyHowever, in many applications we need tocheck a single bitOne unique and powerful feature ofthe 8051 is single-bit operationSingle-bit instructions allow theprogrammer to set, clear, move, andcomplement individual bits of a port,memory, or registerIt is registers, RAM, and I/O ports thatneed to be bit-addressableROM, holding program code for execution, isnot bit-addressable
  • 178. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 23HANELBITADDRESSESBit-AddressableRAMThe bit-addressable RAM location are20H to 2FHThese 16 bytes provide 128 bits of RAMbit-addressability, since 16 × 8 = 1280 to 127 (in decimal) or 00 to 7FHThe first byte of internal RAM location 20Hhas bit address 0 to 7HThe last byte of 2FH has bit address 78Hto 7FHInternal RAM locations 20-2FH areboth byte-addressable and bit-addressableBit address 00-7FH belong to RAM byteaddresses 20-2FHBit address 80-F7H belong to SFR P0,P1, …
  • 179. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 24HANELBITADDRESSESBit-AddressableRAM(cont’)Default register bank for R0-R70700Bank 10F08Bank 21710Bank 31F1800010203040506072008090A0B0C0D0E0F2110111213141516172218191A1B1C1D1E1F2320212223242526272428292A2B2C2D2E2F2530313233343536372638393A3B3C3D3E3F2740414243444546472848494A4B4C4D4E4F2950515253545556572A58595A5B5C5D5E5F2B60616263646566672C68696A6B6C6D6E6F2D70717273747576772E78797A7B7C7D7E7F2FGeneral purpose RAM7F30Byte addressBit-addressablelocations
  • 180. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 25HANELBITADDRESSESBit-AddressableRAM(cont’)Example 5-11Find out to which by each of the following bits belongs. Give theaddress of the RAM byte in hex(a) SETB 42H, (b) CLR 67H, (c) CLR 0FH(d) SETB 28H, (e) CLR 12, (f) SETB 05Solution:(a) D2 of RAM location 28H(b) D7 of RAM location 2CH(c) D7 of RAM location 21H(d) D0 of RAM location 25H(e) D4 of RAM location 21H(f) D5 of RAM location 20HD0D1D2D3D4D5D6D700010203040506072008090A0B0C0D0E0F2110111213141516172218191A1B1C1D1E1F2320212223242526272428292A2B2C2D2E2F2530313233343536372638393A3B3C3D3E3F2740414243444546472848494A4B4C4D4E4F2950515253545556572A58595A5B5C5D5E5F2B60616263646566672C68696A6B6C6D6E6F2D70717273747576772E78797A7B7C7D7E7F2F
  • 181. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 26HANELBITADDRESSESBit-AddressableRAM(cont’)To avoid confusion regarding theaddresses 00 – 7FHThe 128 bytes of RAM have the byteaddresses of 00 – 7FH can be accessed inbyte size using various addressing modesDirect and register-indirectThe 16 bytes of RAM locations 20 – 2FHhave bit address of 00 – 7FHWe can use only the single-bit instructions andthese instructions use only direct addressingmode
  • 182. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 27HANELBITADDRESSESBit-AddressableRAM(cont’)Instructions that are used for signal-bitoperations are as followingJump to target if bit = 1, clear bit(jump if bit, then clear)JBC bit, targetJump to target if bit = 0 (jump if no bit)JNB bit, targetJump to target if bit = 1 (jump if bit)JB bit, targetComplement the bit (bit = NOT bit)CPL bitClear the bit (bit = 0)CLR bitSet the bit (bit = 1)SETB bitFunctionInstructionSingle-Bit Instructions
  • 183. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 28HANELBITADDRESSESI/O PortBit AddressesWhile all of the SFR registers are byte-addressable, some of them are also bit-addressableThe P0 – P3 are bit addressableWe can access either the entire 8 bitsor any single bit of I/O ports P0, P1, P2,and P3 without altering the restWhen accessing a port in a single-bitmanner, we use the syntax SETB X.YX is the port number P0, P1, P2, or P3Y is the desired bit number from 0 to 7 fordata bits D0 to D7ex. SETB P1.5 sets bit 5 of port 1 high
  • 184. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 29HANELBITADDRESSESI/O PortBit Addresses(cont’)Notice that when code such asSETB P1.0 is assembled, it becomesSETB 90HThe bit address for I/O portsP0 are 80H to 87HP1 are 90H to 97HP2 are A0H to A7HP3 are B0H to B7HP2.7 (A7)P2.6P2.5P2.4P2.3P2.2P2.1P2.0 (A0)P2P3.7 (B7)P3.6P3.5P3.4P3.3P3.2P3.1P3.0 (B0)P3P1.7 (97)P1.6P1.5P1.4P1.3P1.2P1.1P1.0 (90)P1P0.7 (87)P0.6P0.5P0.4P0.3P0.2P0.1P0.0 (80)P0D7D6D5D4D3D2D1D0Port BitSingle-Bit Addressability of Ports
  • 185. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 30HANELBITADDRESSESI/O PortBit Addresses(cont’)Special Function RegisterByteaddressSFR RAM Address (Byte and Bit)99A0A8B0B8D0E0F0FFSBUFP2IEP3IPPSWACCBnot bit addressableA7 A6 A5 A4 A3 A2 A1 A0AF AE AD AC AB AA A9 A8B7 B6 B5 B4 B3 B2 B1 B0-- -- -- BC BB BA B9 B8D7 D6 D5 D4 D3 D2 D1 D0E7 E6 E5 E4 E3 E2 E1 E0F7 F6 F5 F4 F3 F2 F1 F0Bit addressDPLnot bit addressable82SPnot bit addressable8180838788898A8B8C8D9098P0DPHPCONTCONTMODTL0TL1TH0TH1P1SCON87 86 85 84 83 82 81 80not bit addressablenot bit addressable8F 8E 8D 8C 8B 8A 89 88not bit addressablenot bit addressablenot bit addressablenot bit addressablenot bit addressable97 96 95 94 93 92 91 909F 9E 9D 9C 9B 9A 99 98Bit addressByteaddressBit addresses 80 – F7Hbelong to SFR of P0,TCON, P1, SCON, P2, etc
  • 186. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 31HANELBITADDRESSESRegistersBit-AddressabilityOnly registers A, B, PSW, IP, IE, ACC,SCON, and TCON are bit-addressableWhile all I/O ports are bit-addressableIn PSW register, two bits are set asidefor the selection of the register banksUpon RESET, bank 0 is selectedWe can select any other banks using thebit-addressability of the PSWP--OVRS0RS1--ACCY18H - 1FH31110H - 17H20108H - 0FH11000H - 07H000AddressRegister BankRS0RS1
  • 187. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 32HANELBITADDRESSESRegistersBit-Addressability(cont’)Example 5-13Write a program to save the accumulator in R7 of bank 2.Solution:CLR PSW.3SETB PSW.4MOV R7,AExample 5-14While there are instructions such as JNC and JC to check the carry flagbit (CY), there are no such instructions for the overflow flag bit (OV).How would you write code to check OV?Solution:JB PSW.2,TARGET ;jump if OV=1P--OVRS0RS1--ACCYExample 5-18While a program to save the status of bit P1.7 on RAM address bit 05.Solution:MOV C,P1.7MOV 05,C
  • 188. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 33HANELBITADDRESSESRegistersBit-Addressability(cont’) Example 5-17The status of bits P1.2 and P1.3 of I/O port P1 must be saved beforethey are changed. Write a program to save the status of P1.2 in bitlocation 06 and the status of P1.3 in bit location 07Solution:CLR 06 ;clear bit addr. 06CLR 07 ;clear bit addr. 07JNB P1.2,OVER ;check P1.2, if 0 then jumpSETB 06 ;if P1.2=1,set bit 06 to 1OVER: JNB P1.3,NEXT ;check P1.3, if 0 then jumpSETB 07 ;if P1.3=1,set bit 07 to 1NEXT: ...Example 5-15Write a program to see if the RAM location 37H contains an evenvalue. If so, send it to P2. If not, make it even and then send it to P2.Solution:MOV A,37H ;load RAM 37H into ACCJNB ACC.0,YES ;if D0 of ACC 0? If so jumpINC A ;it’s odd, make it evenYES: MOV P2,A ;send it to P2
  • 189. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 34HANELBITADDRESSESUsing BITThe BIT directive is a widely useddirective to assign the bit-addressableI/O and RAM locationsAllow a program to assign the I/O or RAMbit at the beginning of the program,making it easier to modify themExample 5-22A switch is connected to pin P1.7 and an LED to pin P2.0. Write aprogram to get the status of the switch and send it to the LED.Solution:LED BIT P1.7 ;assign bitSW BIT P2.0 ;assign bitHERE: MOV C,SW ;get the bit from the portMOV LED,C ;send the bit to the portSJMP HERE ;repeat forever
  • 190. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 35HANELBITADDRESSESUsing BIT(cont’)Example 5-20Assume that bit P2.3 is an input and represents the condition of anoven. If it goes high, it means that the oven is hot. Monitor the bitcontinuously. Whenever it goes high, send a high-to-low pulse to portP1.5 to turn on a buzzer.Solution:OVEN_HOT BIT P2.3BUZZER BIT P1.5HERE: JNB OVEN_HOT,HERE ;keep monitoringACALL DELAYCPL BUZZER ;sound the buzzerACALL DELAYSJMP HERE
  • 191. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 36HANELBITADDRESSESUsing EQUUse the EQU to assign addressesDefined by names, like P1.7 or P2Defined by addresses, like 97H or 0A0HExample 5-24A switch is connected to pin P1.7. Write a program to check the statusof the switch and make the following decision.(a) If SW = 0, send “0” to P2(b) If SW = 1, send “1“ to P2Solution:SW EQU P1.7MYDATA EQU P2HERE: MOV C,SWJC OVERMOV MYDATA,#’0’SJMP HEREOVER: MOV MYDATA,#’1’SJMP HEREENDSW EQU 97HMYDATA EQU 0A0H
  • 192. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 37HANELEXTRA 128BYTE ON-CHIPRAM IN 8052The 8052 has another 128 bytes of on-chip RAM with addresses 80 – FFHIt is often called upper memoryUse indirect addressing mode, which uses R0and R1 registers as pointers with values of 80Hor higher– MOV @R0, A and MOV @R1, AThe same address space assigned to theSFRsUse direct addressing mode– MOV 90H, #55H is the same asMOV P1, #55H
  • 193. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 38HANELEXTRA 128BYTE ON-CHIPRAM IN 8052(cont’)Example 5-27Assume that the on-chip ROM has a message. Write a program tocopy it from code space into the upper memory space starting ataddress 80H. Also, as you place a byte in upper RAM, give a copy toP0.Solution:ORG 0MOV DPTR,#MYDATAMOV R1,#80H ;access the upper memoryB1: CLR AMOVC A,@A+DPTR ;copy from code ROMMOV @R1,A ;store in upper memoryMOV P0,A ;give a copy to P0JZ EXIT ;exit if last byteINC DPTR ;increment DPTRINC R1 ;increment R1SJMP B1 ;repeat until last byteEXIT: SJMP $ ;stay here when finished;---------------ORG 300HMYDATA: DB “The Promise of World Peace”,0END
  • 194. Home Automation, Networking, and Entertainment LabDept. of Computer Science and Information EngineeringNational Cheng Kung University, TAIWANChung-Ping Young楊中平ARITHMETIC & LOGICINSTRUCTIONS ANDPROGRAMSThe 8051 Microcontroller and EmbeddedSystems: Using Assembly and CMazidi, Mazidi and McKinlay
  • 195. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 2HANELARITHMETICINSTRUCTIONSAddition ofUnsignedNumbersADD A,source ;A = A + sourceThe instruction ADD is used to add twooperandsDestination operand is always in register ASource operand can be a register,immediate data, or in memoryMemory-to-memory arithmetic operationsare never allowed in 8051 AssemblylanguageShow how the flag register is affected by the following instruction.MOV A,#0F5H ;A=F5 hexADD A,#0BH ;A=F5+0B=00Solution:F5H 1111 0101+ 0BH + 0000 1011100H 0000 0000CY =1, since there is acarry out from D7PF =1, because the numberof 1s is zero (an evennumber), PF is set to 1.AC =1, since there is acarry from D3 to D4
  • 196. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 3HANELARITHMETICINSTRUCTIONSAddition ofIndividualBytesAssume that RAM locations 40 – 44H have the following values.Write a program to find the sum of the values. At the end of theprogram, register A should contain the low byte and R7 the high byte.40 = (7D)41 = (EB)42 = (C5)43 = (5B)44 = (30)Solution:MOV R0,#40H ;load pointerMOV R2,#5 ;load counterCLR A ;A=0MOV R7,A ;clear R7AGAIN: ADD A,@R0 ;add the byte ptr to by R0JNC NEXT ;if CY=0 don’t add carryINC R7 ;keep track of carryNEXT: INC R0 ;increment pointerDJNZ R2,AGAIN ;repeat until R2 is zero
  • 197. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 4HANELARITHMETICINSTRUCTIONSADDC andAddition of 16-Bit NumbersWhen adding two 16-bit data operands,the propagation of a carry from lowerbyte to higher byte is concernedWrite a program to add two 16-bit numbers. Place the sum in R7 andR6; R6 should have the lower byte.Solution:CLR C ;make CY=0MOV A, #0E7H ;load the low byte now A=E7HADD A, #8DH ;add the low byteMOV R6, A ;save the low byte sum in R6MOV A, #3CH ;load the high byteADDC A, #3BH ;add with the carryMOV R7, A ;save the high byte sumWhen the first byte is added(E7+8D=74, CY=1).The carry is propagated to thehigher byte, which result in 3C+ 3B + 1 =78 (all in hex)13C E7+ 3B 8D78 74
  • 198. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 5HANELARITHMETICINSTRUCTIONSBCD NumberSystemThe binary representation of the digits0 to 9 is called BCD (Binary CodedDecimal) Digit BCD0 00001 00012 00103 00114 01005 01016 01107 01118 10009 1001Unpacked BCDIn unpacked BCD, the lower 4bits of the number represent theBCD number, and the rest of thebits are 0Ex. 00001001 and 00000101 areunpacked BCD for 9 and 5Packed BCDIn packed BCD, a single byte hastwo BCD number in it, one in thelower 4 bits, and one in theupper 4 bitsEx. 0101 1001 is packed BCD for59H
  • 199. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 6HANELARITHMETICINSTRUCTIONSUnpacked andPacked BCDAdding two BCD numbers must give aBCD resultMOV A, #17HADD A, #28HThe result above should have been 17 + 28 = 45 (0100 0101).To correct this problem, the programmer must add 6 (0110) to thelow digit: 3F + 06 = 45H.Adding these twonumbers gives0011 1111B (3FH),Which is not BCD!
  • 200. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 7HANELARITHMETICINSTRUCTIONSDA InstructionDA A ;decimal adjust for additionThe DA instruction is provided tocorrect the aforementioned problemassociated with BCD additionThe DA instruction will add 6 to the lowernibble or higher nibble if needExample:MOV A,#47H ;A=47H first BCD operandMOV B,#25H ;B=25H second BCD operandADD A,B ;hex(binary) addition(A=6CH)DA A ;adjust for BCD addition(A=72H)The “DA” instruction works only on A. In other word, while the sourcecan be an operand of any addressing mode, the destination must be inregister A in order for DA to work.DA works onlyafter an ADD,but not after INC6CH72H
  • 201. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 8HANELARITHMETICINSTRUCTIONSDA Instruction(cont’)Summary of DA instructionAfter an ADD or ADDC instruction1. If the lower nibble (4 bits) is greater than 9, orif AC=1, add 0110 to the lower 4 bits2. If the upper nibble is greater than 9, or ifCY=1, add 0110 to the upper 4 bitsExample:HEX BCD29 0010 1001+ 18 + 0001 100041 0100 0001 AC=1+ 6 + 011047 0100 0111Since AC=1 after theaddition, ”DA A” will add 6 to thelower nibble.The final result is in BCD format.
  • 202. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 9HANELARITHMETICINSTRUCTIONSDA Instruction(cont’)Assume that 5 BCD data items are stored in RAM locations startingat 40H, as shown below. Write a program to find the sum of all thenumbers. The result must be in BCD.40=(71)41=(11)42=(65)43=(59)44=(37)Solution:MOV R0,#40H ;Load pointerMOV R2,#5 ;Load counterCLR A ;A=0MOV R7,A ;Clear R7AGAIN: ADD A,@R0 ;add the byte pointer;to by R0DA A ;adjust for BCDJNC NEXT ;if CY=0 don’t;accumulate carryINC R7 ;keep track of carriesNEXT: INC R0 ;increment pointerDJNZ R2,AGAIN ;repeat until R2 is 0
  • 203. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 10HANELARITHMETICINSTRUCTIONSSubtraction ofUnsignedNumbersIn many microprocessor there are twodifferent instructions for subtraction:SUB and SUBB (subtract with borrow)In the 8051 we have only SUBBThe 8051 uses adder circuitry to performthe subtractionSUBB A,source ;A = A – source – CYTo make SUB out of SUBB, we have tomake CY=0 prior to the execution ofthe instructionNotice that we use the CY flag for theborrow
  • 204. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 11HANELARITHMETICINSTRUCTIONSSubtraction ofUnsignedNumbers(cont’)SUBB when CY = 01. Take the 2’s complement of thesubtrahend (source operand)2. Add it to the minuend (A)3. Invert the carryCLR CMOV A,#4C ;load A with value 4CHSUBB A,#6EH ;subtract 6E from AJNC NEXT ;if CY=0 jump to NEXTCPL A ;if CY=1, take 1’s complementINC A ;and increment to get 2’s compNEXT: MOV R1,A ;save A in R1Solution:4C 0100 1100 0100 1100- 6E 0110 1110 1001 0010-22 01101 1110CY =1+2’scomplementInvert carryCY=0, the result is positive;CY=1, the result is negativeand the destination has the2’s complement of the result
  • 205. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 12HANELARITHMETICINSTRUCTIONSSubtraction ofUnsignedNumbers(cont’)SUBB when CY = 1This instruction is used for multi-bytenumbers and will take care of the borrowof the lower operandCLR CMOV A,#62H ;A=62HSUBB A,#96H ;62H-96H=CCH with CY=1MOV R7,A ;save the resultMOV A,#27H ;A=27HSUBB A,#12H ;27H-12H-1=14HMOV R6,A ;save the resultSolution:We have 2762H - 1296H = 14CCH.A = 62H – 96H – 0 = CCHCY = 1A = 27H - 12H - 1 = 14HCY = 0
  • 206. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 13HANELARITHMETICINSTRUCTIONSUnsignedMultiplicationThe 8051 supports byte by bytemultiplication onlyThe byte are assumed to be unsigned dataMUL AB ;AxB, 16-bit result in B, AMOV A,#25H ;load 25H to reg. AMOV B,#65H ;load 65H to reg. BMUL AB ;25H * 65H = E99 where;B = OEH and A = 99HMultiplication Operand1 Operand2 ResultByte x byte A B B = high byteA = low byteUnsigned Multiplication Summary (MUL AB)
  • 207. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 14HANELARITHMETICINSTRUCTIONSUnsignedDivisionThe 8051 supports byte over bytedivision onlyThe byte are assumed to be unsigned dataDIV AB ;divide A by B, A/BMOV A,#95 ;load 95 to reg. AMOV B,#10 ;load 10 to reg. BMUL AB ;A = 09(quotient) and;B = 05(remainder)Division Numerator Denominator Quotient RemainderByte / byte A B A BUnsigned Division Summary (DIV AB)CY is always 0If B ≠ 0, OV = 0If B = 0, OV = 1 indicates error
  • 208. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 15HANELARITHMETICINSTRUCTIONSApplication forDIV(a) Write a program to get hex data in the range of 00 – FFH fromport 1 and convert it to decimal. Save it in R7, R6 and R5.(b) Assuming that P1 has a value of FDH for data, analyze program.Solution:(a)MOV A,#0FFHMOV P1,A ;make P1 an input portMOV A,P1 ;read data from P1MOV B,#10 ;B=0A hexDIV AB ;divide by 10MOV R7,B ;save lower digitMOV B,#10DIV AB ;divide by 10 once moreMOV R6,B ;save the next digitMOV R5,A ;save the last digit(b) To convert a binary (hex) value to decimal, we divide it by 10repeatedly until the quotient is less than 10. After each division theremainder is saves.Q RFD/0A = 19 3 (low digit)19/0A = 2 5 (middle digit)2 (high digit)Therefore, we have FDH=253.
  • 209. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 16HANELSIGNEDARITHMETICINSTRUCTIONSSigned 8-bitOperandsD7 (MSB) is the sign and D0 to D6 arethe magnitude of the numberIf D7=0, the operand is positive, and ifD7=1, it is negativePositive numbers are 0 to +127Negative number representation (2’scomplement)1. Write the magnitude of the number in 8-bitbinary (no sign)2. Invert each bit3. Add 1 to itSign MagnitudeD7 D6 D5 D4 D3 D2 D1 D0
  • 210. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 17HANELSIGNEDARITHMETICINSTRUCTIONSSigned 8-bitOperands(cont’)Show how the 8051 would represent -34HSolution:1. 0011 0100 34H given in binary2. 1100 1011 invert each bit3. 1100 1100 add 1 (which is CC in hex)Signed number representation of -34 in 2’s complement is CCHDecimal Binary Hex-128 1000 0000 80-127 1000 0001 81-126 1000 0010 82... ... ... ...-2 1111 1110 FE-1 1111 1111 FF0 0000 0000 00+1 0000 0001 01+2 0000 0010 02... ... ... ...+127 0111 1111 7F
  • 211. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 18HANELSIGNEDARITHMETICINSTRUCTIONSOverflowProblemExamine the following code and analyze the result.MOV A,#+96 ;A=0110 0000 (A=60H)MOV R1,#+70 ;R1=0100 0110(R1=46H)ADD A,R1 ;A=1010 0110;A=A6H=-90,INVALIDSolution:+96 0110 0000+ +70 0100 0110+ 166 1010 0110 and OV =1According to the CPU, the result is -90, which is wrong. The CPUsets OV=1 to indicate the overflowIf the result of an operation on signednumbers is too large for the registerAn overflow has occurred and theprogrammer must be noticed
  • 212. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 19HANELSIGNEDARITHMETICINSTRUCTIONSOV FlagIn 8-bit signed number operations,OV is set to 1 if either occurs:1. There is a carry from D6 to D7, but nocarry out of D7 (CY=0)2. There is a carry from D7 out (CY=1), butno carry from D6 to D7MOV A,#-128 ;A=1000 0000(A=80H)MOV R4,#-2 ;R4=1111 1110(R4=FEH)ADD A,R4 ;A=0111 1110(A=7EH=+126,INVALID)-128 1000 0000+ -2 1111 1110-130 0111 1110 and OV=1OV = 1The result +126 is wrong
  • 213. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 20HANELSIGNEDARITHMETICINSTRUCTIONSOV Flag(cont’)MOV A,#-2 ;A=1111 1110(A=FEH)MOV R1,#-5 ;R1=1111 1011(R1=FBH)ADD A,R1 ;A=1111 1001(A=F9H=-7,;Correct, OV=0)-2 1111 1110+ -5 1111 1011-7 1111 1001 and OV=0OV = 0The result -7 is correctMOV A,#+7 ;A=0000 0111(A=07H)MOV R1,#+18 ;R1=0001 0010(R1=12H)ADD A,R1 ;A=0001 1001(A=19H=+25,;Correct,OV=0)7 0000 0111+ 18 0001 001025 0001 1001 and OV=0OV = 0The result +25 is correct
  • 214. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 21HANELSIGNEDARITHMETICINSTRUCTIONSOV Flag(cont’)In unsigned number addition, we mustmonitor the status of CY (carry)Use JNC or JC instructionsIn signed number addition, the OV(overflow) flag must be monitored bythe programmerJB PSW.2 or JNB PSW.2
  • 215. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 22HANELSIGNEDARITHMETICINSTRUCTIONS2sComplementTo make the 2’s complement of anumberCPL A ;1’s complement (invert)ADD A,#1 ;add 1 to make 2’s comp.
  • 216. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 23HANELLOGIC ANDCOMPAREINSTRUCTIONSANDANL destination,source;dest = dest AND sourceThis instruction will perform a logicAND on the two operands and placethe result in the destinationThe destination is normally theaccumulatorThe source operand can be a register, inmemory, or immediateX Y X AND Y0 0 00 1 01 0 01 1 1Show the results of the following.MOV A,#35H ;A = 35HANL A,#0FH ;A = A AND 0FH35H 0 0 1 1 0 1 0 10FH 0 0 0 0 1 1 1 105H 0 0 0 0 0 1 0 1ANL is often used tomask (set to 0) certainbits of an operand
  • 217. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 24HANELLOGIC ANDCOMPAREINSTRUCTIONSORORL destination,source;dest = dest OR sourceThe destination and source operandsare ORed and the result is placed inthe destinationThe destination is normally theaccumulatorThe source operand can be a register, inmemory, or immediateX Y X OR Y0 0 00 1 11 0 11 1 1Show the results of the following.MOV A,#04H ;A = 04ORL A,#68H ;A = 6C04H 0 0 0 0 0 1 0 068H 0 1 1 0 1 0 0 06CH 0 1 1 0 1 1 0 0ORL instruction can beused to set certain bitsof an operand to 1
  • 218. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 25HANELLOGIC ANDCOMPAREINSTRUCTIONSXORXRL destination,source;dest = dest XOR sourceThis instruction will perform XORoperation on the two operands andplace the result in the destinationThe destination is normally theaccumulatorThe source operand can be a register, inmemory, or immediateShow the results of the following.MOV A,#54HXRL A,#78H54H 0 1 0 1 0 1 0 078H 0 1 1 1 1 0 0 02CH 0 0 1 0 1 1 0 0X Y X XOR Y0 0 00 1 11 0 11 1 0XRL instruction can beused to toggle certainbits of an operand
  • 219. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 26HANELLOGIC ANDCOMPAREINSTRUCTIONSXOR(cont’)The XRL instruction can be used to clear the contents of a register byXORing it with itself. Show how XRL A,A clears A, assuming thatAH = 45H.45H 0 1 0 0 0 1 0 145H 0 1 0 0 0 1 0 100H 0 0 0 0 0 0 0 0Read and test P1 to see whether it has the value 45H. If it does, send99H to P2; otherwise, it stays cleared.Solution:MOV P2,#00 ;clear P2MOV P1,#0FFH ;make P1 an input portMOV R3,#45H ;R3=45HMOV A,P1 ;read P1XRL A,R3JNZ EXIT ;jump if A is not 0MOV P2,#99HEXIT: ...XRL can be used tosee if two registershave the same valueIf both registers have the samevalue, 00 is placed in A. JNZand JZ test the contents of theaccumulator.
  • 220. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 27HANELLOGIC ANDCOMPAREINSTRUCTIONSComplementAccumulatorCPL A ;complements the register AThis is called 1’s complementTo get the 2’s complement, all wehave to do is to to add 1 to the 1’scomplementMOV A, #55HCPL A ;now A=AAH;0101 0101(55H);becomes 1010 1010(AAH)
  • 221. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 28HANELLOGIC ANDCOMPAREINSTRUCTIONSCompareInstructionCJNE destination,source,rel. addr.The actions of comparing and jumpingare combined into a single instructioncalled CJNE (compare and jump if notequal)The CJNE instruction compares twooperands, and jumps if they are not equalThe destination operand can be in theaccumulator or in one of the Rn registersThe source operand can be in a register, inmemory, or immediateThe operands themselves remain unchangedIt changes the CY flag to indicate if thedestination operand is larger or smaller
  • 222. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 29HANELLOGIC ANDCOMPAREINSTRUCTIONSCompareInstruction(cont’)Notice in the CJNE instruction that anyRn register can be compared with animmediate valueThere is no need for register A to beinvolvedCJNE R5,#80,NOT_EQUAL ;check R5 for 80... ;R5 = 80NOT_EQUAL:JNC NEXT ;jump if R5 > 80... ;R5 < 80NEXT: ...Compare Carry Flagdestination ≥ source CY = 0destination < source CY = 1CY flag is alwayschecked for casesof greater or lessthan, but only afterit is determined thatthey are not equal
  • 223. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 30HANELLOGIC ANDCOMPAREINSTRUCTIONSCompareInstruction(cont’)The compare instruction is really asubtraction, except that the operandsremain unchangedFlags are changed according to theexecution of the SUBB instructionWrite a program to read the temperature and test it for the value 75.According to the test results, place the temperature value into theregisters indicated by the following.If T = 75 then A = 75If T < 75 then R1 = TIf T > 75 then R2 = TSolution:MOV P1,#0FFH ;make P1 an input portMOV A,P1 ;read P1 portCJNE A,#75,OVER ;jump if A is not 75SJMP EXIT ;A=75, exitOVER: JNC NEXT ;if CY=0 then A>75MOV R1,A ;CY=1, A<75, save in R1SJMP EXIT ; and exitNEXT: MOV R2,A ;A>75, save it in R2EXIT: ...
  • 224. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 31HANELROTATEINSTRUCTIONAND DATASERIALIZATIONRotating Rightand LeftRR A ;rotate right AIn rotate rightThe 8 bits of the accumulator are rotatedright one bit, andBit D0 exits from the LSB and enters intoMSB, D7MSB LSBMOV A,#36H ;A = 0011 0110RR A ;A = 0001 1011RR A ;A = 1000 1101RR A ;A = 1100 0110RR A ;A = 0110 0011
  • 225. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 32HANELROTATEINSTRUCTIONAND DATASERIALIZATIONRotating Rightand Left(cont’)RL A ;rotate left AIn rotate leftThe 8 bits of the accumulator are rotatedleft one bit, andBit D7 exits from the MSB and enters intoLSB, D0MSB LSBMOV A,#72H ;A = 0111 0010RL A ;A = 1110 0100RL A ;A = 1100 1001
  • 226. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 33HANELROTATEINSTRUCTIONAND DATASERIALIZATIONRotatingthrough CarryRRC A ;rotate right through carryIn RRC ABits are rotated from left to rightThey exit the LSB to the carry flag, andthe carry flag enters the MSBMSB LSBCLR C ;make CY = 0MOV A,#26H ;A = 0010 0110RRC A ;A = 0001 0011 CY = 0RRC A ;A = 0000 1001 CY = 1RRC A ;A = 1000 0100 CY = 1CY
  • 227. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 34HANELROTATEINSTRUCTIONAND DATASERIALIZATIONRotatingthrough Carry(cont’)RLC A ;rotate left through carryIn RLC ABits are shifted from right to leftThey exit the MSB and enter the carry flag,and the carry flag enters the LSBMSB LSBCYWrite a program that finds the number of 1s in a given byte.MOV R1,#0MOV R7,#8 ;count=08MOV A,#97HAGAIN: RLC AJNC NEXT ;check for CYINC R1 ;if CY=1 add to countNEXT: DJNZ R7,AGAIN
  • 228. Department of Computer Science and Information EngineeringNational Cheng Kung University, TAIWAN 35HANELROTATEINSTRUCTIONAND DATASERIALIZATIONSerializing DataSerializing data is a way of sending abyte of data one bit at a time througha single pin of microcontrollerUsing the serial port, discussed in Chapter10To transfer data one bit at a time andcontrol the sequence of data and spacesin between them
  • 229.