Arieh Nachum Introduction to Microprocessors and Microcontrollers EB-3191 Arieh Nachum Introduction to Microprocessors and Microcontrollers EB-3191 1_11 © All rights reserved to DEGEM Systems. The material in this book may not be copied, duplicated, printed, translated, re-edited or broadcast without prior agreement in writing from DEGEM Systems. 20a Eliyau Eitan St., Rishon-Lezion P.O.Box 5340, Rishon-Lezion 75151 Israel Tel: 972-3-9535400 Fax: 972-3-9535423 E-mail: info@degem.com Site: www.degem.com I Contents Preface ............................................................................................................ IV Part I ................................................................................................................. 1 Chapter 1 – Microcomputer Principles of Operation ................................. 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 Input ...................................................................................................... 2 Output .................................................................................................... 3 Memory ................................................................................................. 4 Clock ..................................................................................................... 6 The CPU ................................................................................................ 6 Details of various components ............................................................ 10 Principles of the microprocessor's operation ...................................... 13 Summary of used concepts ................................................................. 15 Chapter 2 – Addressing Modes .................................................................... 18 2.1 2.2 2.3 2.4 2.5 2.6 Register addressing mode ................................................................... 21 Immediate addressing mode ............................................................... 21 Variables ............................................................................................. 22 Direct addressing mode....................................................................... 22 Indirect addressing mode .................................................................... 23 Bit manipulation .................................................................................. 24 Chapter 3 – Flags........................................................................................... 26 3.1 3.2 3.3 3.4 3.5 3.6 Carry flag (CY) ................................................................................... 27 Aux Carry flag (AC) ........................................................................... 27 Zero flag (F0) ...................................................................................... 27 OVerflow flag (OV) ............................................................................ 27 Parity flag (P) ...................................................................................... 28 Summary ............................................................................................. 29 Part II ............................................................................................................. 31 Chapter 4 – Machine and Assembly Language with the 8051 .................. 31 4.1 Preface ................................................................................................. 31 Experiment 4.1 – Software Installation and Operation ............................ 34 Experiment 4.2 – The Debugger Functions ................................................ 42 EB-3191 – Introduction to microprocessors and microcontrollers II Experiment 4.3 – Input / Output Units ....................................................... 57 Experiment 4.4 – Assembly Programming ................................................. 68 Chapter 5 – The 8051's Structure, ............................................................... 94 Instructions and Exercises ............................................................................ 94 5.1 5.2 5.3 5.4 5.4.1 5.4.2 5.4.3 5.4.4 5.5 5.6 5.7 5.8 5.9 5.10 5.10.1 5.10.2 5.10.3 5.10.4 5.10.5 5.10.6 5.10.7 Structure of the internal direct RAM .................................................. 95 Interrupts and stack ........................................................................... 104 Effect of instructions on flags ........................................................... 107 Classification of the instructions ....................................................... 108 Code .................................................................................................. 108 Mnemonic instructions ...................................................................... 109 Bytes .................................................................................................. 109 Cycles ................................................................................................ 109 Data transfer instructions .................................................................. 110 Arithmetic operations ........................................................................ 112 Logical operations ............................................................................. 113 Boolean variable manipulation ......................................................... 114 Program branching ............................................................................ 115 Integrated exercises ........................................................................... 117 Input and processing of a data byte................................................... 121 PLC - Programmable Logic Controller ............................................ 123 Look up tables ................................................................................... 125 Subroutines........................................................................................ 128 Interrupts ........................................................................................... 131 How to use the timer/counter ............................................................ 141 Serial communication ....................................................................... 152 Part III .......................................................................................................... 168 Chapter 6 – Addresses Decoding and Memories ..................................... 168 6.1 6.2 6.3 6.4 6.5 Timing diagrams – general ............................................................... 168 The 8051 timing diagrams ................................................................ 171 Memory types ................................................................................... 173 Structure of the memory units........................................................... 177 Separating the multiplexed bus ......................................................... 185 Experiment 6.1 – Selecting a RAM in an address range ......................... 187 EB-3191 – Introduction to microprocessors and microcontrollers III Chapter 7 – Ports......................................................................................... 199 7.1 Addressing to input / output ports ..................................................... 199 Experiment 7.1 – Input and Output Ports ................................................ 200 Chapter 8 – Displays ................................................................................... 208 8.1 8.2 LED's and their connection to an output port ................................... 208 An image of an output port ............................................................... 210 Experiment 8.1 – 7-Segment display ......................................................... 211 The 7-Segment display .................................................................................. 211 Experiment 8.2 – LCD display ................................................................... 219 Chapter 9 – Switches and Keys .................................................................. 229 Experiment 9.1 – Identifying a key being pressed ................................... 229 Experiment 9.2 – Scanning momentary switches..................................... 235 Scanning momentary switches ...................................................................... 235 Experiment 9.3 – Connecting a keyboard in a matrix ............................. 242 Chapter 10 – D/A and A/D Converters ..................................................... 249 Experiment 10.1 – Operating a DAC ........................................................ 249 Experiment 10.2 – Employing the ADC .................................................... 262 Appendix A – 8051 Instruction Set ............................................................ 271 Appendix B – The 8051 Special Function Registers ................................ 277 EB-3191 – Introduction to microprocessors and microcontrollers IV Preface The experiments in this manual are meant to be run on the experiment board EB-3191 with the Universal Training System EB-3000. The EB-3000 includes: 5 voltages power supply (+12V, +5V, –5V, –12V and –12V to +12V variable voltage). 2 voltmeters. Ampere-meter. Frequency counters up to 1MHz. Logic probe (High, Low, Open, Pulse, Memory). Logic analyzer with 8 digital inputs and trigger input. Two channel oscilloscope (with spectrum analysis while connecting to the PC). Function generator (sine, triangle and square wave signals) up to 1MHz. 3.2" color graphic display with touch panel for signal and measurement display. USB wire communication with the PC. 20 key terminal keyboard. 10 relays for switching the plug-in boards or for planting faults. 48 pin industrial very low resistance connector for plug-in boards connection. Transparent sturdy cover covers the upper part of the plug-in boards in order to protect the board's components that should be protected. EB-3191 – Introduction to microprocessors and microcontrollers V The EB-3000 boards are: Electricity and Electronics EB-3121 Ohm and Kirchoff Laws and DC circuits EB-3122 Norton, thevenin and superposition EB-3123 AC circuits, signals and filters EB-3124 Magnetism, electromagnetism, induction and transformers Semiconductor Devices EB-3125 Diodes, Zener, bipolar and FET transistors characteristics and DC circuits EB-3126 Bipolar and FET transistor amplifiers EB-3127 Industrial semiconductors – SCR, Triac, Diac and PUT EB-3128 Optoelectronic semiconductors – LED, phototransistor, LDR, 7-SEG. Linear Electronics EB-3131 Inverter, non-inverter, summing, difference operational amplifiers EB-3132 Comparators, integrator, differentiator, filter operational amplifiers EB-3135 Power amplifiers EB-3136 Power supplies and regulators EB-3137 Oscillators, filters and tuned amplifiers Motors, Generators and Inverters EB-3141 Analog, PWM DC motor speed control, step motor control, generators EB-3142 Motor control – optical, Hall effect, motor closed control EB-3143 AC-DC and DC-AC conversion circuits EB-3144 3 Phase motor control Digital Logic and Programmable Device EB-3151 AND, OR, NOT, NAND, NOR, XOR logic components & Boolean algebra EB-3152 Decoders, multiplexers and adders EB-3153 Flip-flops, registers, and counters sequential logic circuits EB-3154 555, ADC, DAC circuits EB-3155 Logic families Microprocessor/Microcontroller Technology EB-3191 Introduction to microprocessors and microcontrollers EB-3191 – Introduction to microprocessors and microcontrollers VI The EB-3191 is connected to the EB-3000 via a 48 pin industrial connector. It has a built-in microcontroller that identifies (for the EB-3000 system) the experiment board when it is being plugged into the system, and starts a selfdiagnostic automatically. The following figure describes the EB-3191 experiment board. INT INT0 Reset 8051 Control Address Bus INT T0 T1 P1.7 P1.6 P1.5 P1.4 P1.3 P1.2 P1.1 P1.0 1 Clock EA Decoder DAC Sync CS A15 EEPROM VP DAC Serial CLK Data Bus Serial DI Output Serial CLK Serial DI Input D0 D1 D2 D3 D4 D5 I0………..……..I7 ADC Serial DO S10 S10 S10 S10 ADC CS S10 S10 S10 S10 +5V Potentiometer S10 S10 S10 S10 LCD S10 S10 S10 S10 EN EB-3191 Panel Layout EB-3191 – Introduction to microprocessors and microcontrollers RS D6 D7 VII The experiment method: The system uses an external switching power supply for safety reasons. The power supply low voltage output is converted to the 5 voltages by linear regulators for noise reduction. Two potentiometers on the panel are used to setup the variable voltage and the function generator amplitude. The system cut-off the voltages in overload and displays a massage about that. The plug-in cards are connected directly to system without any flat cable for noise and resistance reduction. The 10 relays are change over relays that can switch active and passive components. Every selecting of a relay configuration is saved in a non-volatile memory located on the connected plug-in card. The components are located on the board with silk screen print of the analytical circuit and component symbols. The central part of the experimenting board includes all the circuit block drawings and all the hands on components, test points and banana sockets. The protected components are located on the circuit board upper side, clearly visible to the student and protected by a sturdy transparent cover. On plugging the experiment board, it sends a message to the EB-3000 which includes the board's number and which of its block are faulty. If there is a faulty module (B1-B8), it will be displayed on the screen. The experiment board checks itself while it is being plugged. This is why, during the plug-in, any banana wire should not be connected on the experiment board. 5 LEDs should turn ON on the top right. EB-3191 – Introduction to microprocessors and microcontrollers VIII The system includes 5 power supply outputs. The system checks these voltages and turns ON the LEDs accordingly. +12V +5V –5V –12V – – – – Red LED Orange LED Yellow LED Green LED The fifth voltage is a variable voltage (Vvar) controlled by a slider potentiometer. The LED of the Vvar is both green and red: when the Vvar voltage is positive – the color is red and when it is negative – the color is green. There are no outlets for the power supply voltages on the The voltages are supplied only to the 48 pin connector. TSP-3100 panel. The experiment boards take these voltages from the 48 pin connector. EB-3000 Screens The system has 3 operating screens: DVM, Oscilloscope and Faults. Moving from one screen to another is done by the Options/Graph key. The keyboard is always at Num Lock position. The keys can also be used as function keys. In order to do so, we have to press once on the Num Lock key and then on the required key. The keyboard returns automatically to Num Lock mode. On scope screen, pressing the Num Lock key and then the Digital key will change the screen to Digital signal screen display. Pressing the Num Lock key and then the Analog key will change the screen to Analog signal screen display. EB-3191 – Introduction to microprocessors and microcontrollers IX DVM Screen DVM V1 [V] 0.00 V2–V1 [V] 0.00 Fout [KHz] 5.00 V2 [V] 0.00 I [mA] 0.0 Cin [Hz] 5.00 I (+5V) [mA] I (+12V) [mA] 0 0 I (–5V) [mA] I (–12V) [mA] 0 0 Num Lock V1 is the voltage measured between V1 inlet and GND. V2 is the voltage measured between V2 inlet and GND. V2–V1 is the voltage measured between V1 and V2. It enables us to measure floating voltage. I is the current measured between A+ and A– inlets. Cin displays the frequency is measured in the Cin inlet. The EB-3000 includes a function generator. The frequency of the function generator is displayed in the Fout field and can be set by the arrow keys or by typing the required values. The square wave outlet is marked with the sign . Near the analog signal outlet there is a sine/triangle switch marked with the signs / . EB-3191 – Introduction to microprocessors and microcontrollers X Scope Screen CH1 3.0VCH2 3.0V t 50s CH1 1.0V Num Lock Analog Run The scope and the display parameters (CH1 Volt/div, CH2 Volt/div, time base Sec/div, Trigger Channel, Trigger rise/fall, Trigger Level) appear on the bottom of the screen. The Up and Down arrow keys highlight one of the fields below. The required field can be selected by touching it and can be changed by the Up and Down arrows. The function generator amplitude is changed by the amplitude potentiometer. The sampling and display can be stopped by pressing the Num Lock key and then pressing the Stop (8) key. Performing a single sampling is done by pressing the Num Lock key and then pressing the Single (9) key. Running again the sampling is done by pressing the Num Lock key and then pressing the Run (7) key. EB-3191 – Introduction to microprocessors and microcontrollers XI Digital Screen Pressing the Num Lock key and then the Digital key on scope screen displays the Digital screen. D0 D1 D2 D3 D4 D5 D6 D7 D0 D1 D2 D3 D4 D5 D6 D7 t 50s TRIG Num Lock Digital Run Check that. The logic analyzer includes 8 digital inlets and one trigger signal inlet. The controller waits for trigger and when it encounters a trigger pulse it samples the 8 digital inputs. If a trigger pulse is not found the sampling will be according to the time base. The sampling and display can be stopped by pressing the Num Lock key and then pressing the Stop (8) key. Performing a single sampling is done by pressing the Num Lock key and then pressing the Single (9) key. Running again the sampling is done by pressing the Num Lock key and then pressing the Run (7) key. EB-3191 – Introduction to microprocessors and microcontrollers XII Logic Probe The EB-3000 Logic Probe includes 5 LEDs indicating the Logic Probe (LP) input state – High, Low, Open (unconnected), Pulses and Memory (registering single pulse). The Logic Probe also has a TTL/CMOS switch that determines which logic level is selected. When the LP is connected to a point with a voltage blow 0.8V (for TTL) or 1.3V (for CMOS), the L green LED should turn ON. When the LP is connected to a point with a voltage above 2.0V (for TTL) or 3.7V (for CMOS), the H red LED should turn ON. The voltage between these levels turns ON the OP orange LED. Fault Screen The EB-3000 includes 10 relays for fault insertion or for switching external components. The fault screen is selected by the Options/Graph key. FAULTS Please choose Fault No.: 0–9 Activated fault Number: 0 Num Lock Typing a fault number and pressing ENTER operates the required relay for the required fault. Fault No. 0 means No Fault. Which relay creates the required fault is registered in the plug-in experiment board controller. EB-3191 – Introduction to microprocessors and microcontrollers XIII On entering a fault number, the system addresses the experiment board controller and asks for the relay number. After that, it executes the required fault. The experiment board controller saves the last registered fault number in its memory. This memory is non-volatile. This is why the system does not allow us to enter a fault number when no experiment board is plugged. When an experiment board that a certain fault (other than zero) is registered in its memory is plugged into the system, a warning message appears on the system's screen. This feature enables the teacher to supply the students various experiment boards with planted faults for troubleshooting. Note: It is recommended (unless it is otherwise required), to return the experiment board fault number to zero before unplugging it. EB-3191 – Introduction to microprocessors and microcontrollers XIV About this book: This book is divided to three parts. The first part is a theory part that describes the structure of a microcomputer and its principles of operation. This part describes also a microcomputer based on the 8051 microcontroller. This kind of microcomputer is called embedded microcontroller system. This part can be studied and exercised by a CBT program. The second part is a programming experiments part. The third part is hardware experiments part. Most of the experiments in these two parts require communication with the PC, writing and running programs. The writing and the running of the programs are done with the software SES51C. This software includes Editor, Assembler and Debugger. Part of the experiments is how to use these features. The last chapter of this book is troubleshooting. Troubleshooting in embedded microcontroller system is based on writing a routine that addresses the hardware and analyzing the received data. It is very difficult to exercise the software while reading instructions on CBT screens. This is the reason why these two parts are not included in the CBT courseware. The exercises are mostly programming exercises accompanied with challenge exercises. On the other hand, the CBT software includes questions related to part II, part III and the troubleshooting. These questions should be answered after studying and exercising part II and III. EB-3191 – Introduction to microprocessors and microcontrollers 1 Part I Chapter 1 – Microcomputer Principles of Operation This chapter deals with the basic structure of the microcomputer and its parts, as well as the principles guiding its mode of operation. The microcomputer is composed of various units, and its basic structure is described in figure 1-1: Timing Clock Input Data Input Central Processing Unit - CPU Output Processed Data Memory Figure 1-1 Basic structure of a microcomputer The heart of the computer is the microprocessor - otherwise known as the Central Processing Unit - in short the CPU. The CPU operates on binary numbers only, which explains why this type of computer is called a digital computer (in contrast with analog computers which operate on a totally different principle). The CPU receives numbers from the input units and by means of numbers stored in its memory, processes these numbers according to a previously defined program. The results of this process are either restored in the memory or are transferred to the output units. The defined program executed by the CPU is also a collection of binary numbers stored in the memory. EB-3191 – Introduction to microprocessors and microcontrollers 2 1.1 Input The means by which data is entered into the input units is by the pressing of keys, the application of different voltages, temperature, etc., and not by feeding in of numbers. For example, a microcomputer system has a keyboard. Each key is given a specific numerical value, and upon pressing of any key its value is transferred by the input unit to the central processing unit. The central processing unit receives the number value, processes it, and transfers the processed value to either the memory, the output unit, or even uses the processed value in order to calculate another number. The processing and transfer of the result is done according to a previously defined program stored in the memory, which defines what is to be done with incoming data from the input units. A further example. Let's assume that we require the microcomputer to control the temperature resulting from the operation of an air-conditioning system. A temperature sensor component is included in the system. Its function is to translate the temperature level to an electrical voltage. This electrical voltage, which changes as the temperature does, is now fed into the microcomputer. In this case, it is the input unit's function to convert the voltage to a binary number, which is then transferred to the processor which gives the output unit an instruction to operate a cooling system (if the incoming binary number is greater than a specific value), or a heating system (if the incoming binary number is smaller than a specific value). The specific values do not necessarily have to be equal. EB-3191 – Introduction to microprocessors and microcontrollers 3 1.2 Output The output unit's function is to translate the numbers received by it from the CPU into a required form. The required form may be characters (letters, figures etc.) on a screen, lights lighting up, or even the manipulation of a system depending on the value of the number received. For example, a value of 10 will operate a heating system whereas a value of 20 would operate a cooling system. From the above, it is clearly seen that the input and output units of different microcomputer systems, differ from one to another according to the functions required to be performed by the different systems. However, there are numerous Input and Output standard units available that perform given functions. Since many microcomputers are operated by means of a keyboard, there are input units available which translate the pressing of a key into a number. Since the translation of a voltage into a number value has become a common requirement, there are standard units available which perform this function. Similarly, units that translate numerical values to the switching of various appliances, machines, systems etc. are readily available. EB-3191 – Introduction to microprocessors and microcontrollers 4 1.3 Memory The next unit, used constantly by the CPU, is the memory unit. The memory unit is composed of an array of cells, each cell storing in it a specific number. Address . 843 843 853 853 853 858 854 855 853 Figure 1-2 Memory cells The signs ( ) at top and bottom of the sketch show that the chain of cells continues in both directions and only a section of the memory is being shown in figure 1-2. The number stored in each cell is called data. The size of the data is limited, depending on the microprocessor being used, and the limit is defined by the size of the cell and type of CPU. The 8051 is an 8 bit microcontroller and microprocessor, i.e. the binary numbers processed and decoded by the CPU are binary numbers have 8 bits (and are able to contain combinations in the range 0-255). A number having 8 bits is called a BYTE. EB-3191 – Introduction to microprocessors and microcontrollers 5 Each cell has a number, which is its serial number. This number is called an address. The address allows us to address each cell in order to examine the number it contains or to insert a new number into the cell. The address is a number having 16 bits, allowing for 65536 different combinations. A binary number having 16 bits is called a WORD. The CPU has access to the memory and to the other units by means of three routes called BUSSES. The first is called the ADDRESS BUS, the second the DATA BUS and the third - the CONTROL BUS. When the CPU requires data from a specific cell, say, cell 354, the number 354 is "registered" on the address bus. The control bus instructs the memory to provide the required data and the number stored in cell 354 is then transferred to the CPU by means of the data bus. Although the information regarding the contents of a memory cell has been transferred to the CPU, the data is not removed from the memory location and remains there until it is changed. When the CPU requires data to be stored in a memory cell, for example, in cell 356, the number 356 is "registered" on the address bus. The CPU gives instructions through the control bus to receive the data, and the required data is transferred by means of the data bus. This data will now be stored in cell 356, replacing any previous data in this cell. Data stored in the memory does not consist solely of numbers, which need to be processed. A significant part of such data is a collection of instructions, which comprises the microcomputer work-program. The CPU translates the data into an instruction, which needs to be carried out and carries out the corresponding instruction. EB-3191 – Introduction to microprocessors and microcontrollers 6 1.4 Clock The operations carried out by the microprocessor are done step-by-step. The CPU addresses a memory cell, which contains a number representing an instruction. It then retrieves, decodes and carries out the instruction. This procedure is repeated, again and again. The timing of each of these steps is crucial and is controlled by an external CLOCK, which regulates the speed at which the operations are carried out. It is very important that the sequence or speed of the microcomputers steps is synchronized to the access times of the components to be controlled or accessed. 1.5 The CPU The CPU is composed of a number of internal parts. In order to understand the principles guiding the microprocessor's operation, an understanding of these internal parts and their functions is required. The parts of the CPU are: a) b) c) The control unit. Arithmetic Logic Unit (ALU). Registers. The above can be found in every CPU. However, the 8051 has a number of additional components, three of which we will mention: a) b) c) A read/write memory having 128 bytes, which is used for variables. This memory is called RAM (Random Access Memory). A read only memory, used for the operating program of the CPU and for fixed data. We are not able to change the contents of this memory, and its cell contents are preserved even when the power supply is turned off. This memory is called ROM (Read Only Memory). Internal input/output units called ports. We will expand the discussion on these units, as well as others, in coming chapters. EB-3191 – Introduction to microprocessors and microcontrollers 7 Let's make some order in the terms: The CPU is the Central Processing Unit, which is the heart of every computer and microcomputer. The MICROPROCESSOR is a CPU built on a monolithic chip. A microcomputer is a computer based on a microprocessor. Every microcomputer has at least 5 parts: CPU, RAM, ROM, INPUT and OUTPUT. The difference between the microcomputers is in the size of each part and their functions. The MICROCONTROLLER is a single chip microcomputer. It has all the above 5 parts in its chip. There are many types of microcontrollers with many different internal components. We select the microcontroller according to out applications. The 8051 is not one microcontroller. It is a big family of microcontrollers for a huge number of various applications. The 8051 is the core part of all this family. After we know it, we will understand how it can easily be changed to many variants. EB-3191 – Introduction to microprocessors and microcontrollers 8 The parts of the 8051 CPU can thus be described as in figure 1-3: I/O Ports Registers Address 4K bytes ROM 128 bytes RAM BUS ALU Arithmetic Logic Unit Clock Control Unit Data BUS Control BUS Figure 1-3 Block diagram of the 8051 The register is a memory unit, which is able to contain only one number. This number can represent either an address or data, depending on the register's function. The register's size is determined accordingly (8 or 16 bits). Some of the registers, called R0-R7, are simply cells in the lower 128 bytes of the read/write memory. Other registers, which are called SPECIAL FUNCTION REGISTERS, are found in another range of the 128 bytes of read/write memory in the CPU. Each of these special registers has a name and a specific function. The most active register in the CPU is the ACCUMULATOR, marked "ACC". A large amount of data in the CPU flows through this register. Another active register is the PC (Program Counter). This 16 bit register shows the address of the instruction about to be carried out. Upon transfer of a byte of instruction to the CPU, the PC automatically increases by one and shows the next byte. EB-3191 – Introduction to microprocessors and microcontrollers 9 If the lower internal read/write memory, having 128 bytes, is not sufficient, another read/write memory may be added to the 8051 externally and it is called External RAM. In order to address a cell in this area of the memory, the help of another register having 16 bits is needed. This register is called the DATA POINTER (DPTR). A required cell's address is entered into the DPTR in order to reach the cell. There are other special registers, which will be dealt with further on. The ALU (Arithmetic Logic Unit) is the unit, which performs the arithmetic and logic functions within the CPU according to the instructions it receives. It receives two items of data either from registers or from a register and a memory cell. Its output, which is the result of the instructed operation, flows to a register. The most complex unit in the CPU is the Control Unit. This unit receives the binary number signifying the instruction about to be carried out, decodes the instruction and carries it out according to the steps required. The number of instructions and their possibilities is enormous. EB-3191 – Introduction to microprocessors and microcontrollers 10 1.6 Details of various components As mentioned previously, the CPU is connected to its units by three BUSSES. The structure of the microcomputer can thus be described as in figure 1-4: Magnetic Memory Unit Read Only Memory Unit Read/Write Memory Unit Interface Unit Address BUS Clock CPU Data BUS Control BUS Input Units Output Units Figure 1-4 Microcomputer structure Figure 1-1 depicted the CPU at the center of the microcomputer. It is at the system's center, but rather as shown in figure 1-4. EB-3191 – Introduction to microprocessors and microcontrollers 11 The BUSSES are a collection of "lines" leading from one unit to another. Each line can have a status of either '0' or '1'. A collection of lines will thus form a binary number. For example, the address bus has 16 lines. On these lines we are able to generate binary numbers from 0000H (where H represents a hexadecimal number) to FFFFH, all in all a total of 65,536 different addresses, called 64K for short. The address bus allows the CPU to address 64K different cells. In a microcomputer system no two cells have the identical address. The DATA BUS is a collection of 8 lines through which the binary numbers flow between the CPU and the other units. In the 8051, the DATA BUS has 8 bits. When a 16-bit data number is required, it will be found in two different memory cells. The CPU will thus address these two cells and transfer the data in two stages. The CONTROL BUS is composed of lines, each of which has its own function. The three main control lines are the RD' line (READ), WR' line (WRITE), and the PSEN' line (PROGRAM SET ENABLE). When the CPU is required to read or retrieve data from one of the units to which it is attached, the cell address is signified on the address lines, and the RD' line is brought to '0'. The data from the specified address will then be brought to the CPU by the data lines. The apostrophe after RD, WR and PSEN signifies operation mode in negative logic, i.e. the line operates when at logic '0'. When the CPU wishes to write data in one of the attached units, it specifies the cell address on the address lines, puts the data on the data lines and drops the WR' line to '0'. The data will then be implanted into the given address. The RD' and WR' will never be found in '0' mode simultaneously. The RD' and WR' lines are activated when the CPU turns to the external RAM. When the CPU turns to the external ROM - which holds the operating program, the PSEN' line is reduced to '0'. The PSEN' line operates similarly to the RD' line, but actually, the ROM is addressed. As we are unable to write on the ROM, there is no line that enables writing on it. The PSEN' line enables us to expand the program memory beyond the internal ROM. EB-3191 – Introduction to microprocessors and microcontrollers 12 Each unit connected to the CPU has a logic circuit which decodes the addresses appearing on the ADDRESS BUS and the RD', WR' or PSEN' lines. When the memory unit identifies an address on the address lines as one belonging to a cell of its own, and the WR' line is in mode '0', the information on the data lines will be written into the signified cell. If, however, the RD' line is in '0' mode, the contents of the cell would be read or "spilled out" onto the data lines. The MEMORIES may be divided into three main categories: a) b) c) Read/write memories called RAM (Random Access Memory). Read only memories, called ROM. Magnetic memories. The RAM memory allows data storage by the CPU, as well as their retrieval during different stages of the program. The user is able to write various programs on this memory, and is also able to alter programs with ease. When the power supply to the system is turned off, all of the data stored in this memory is wiped out. Consequently, we are unable to store fixed programs in this memory. The RAM has random numbers in it when the power supply is turned on. The ROM solves the RAM's problem of volatility. The ROM is a memory whose stored data and instructions are written by an external system and only thereafter is the ROM inserted into the microcomputer. The CPU can only receive data from this memory, not store any data in it. The advantage of this memory is in the fact that a power cut off will not wipe out its contents. It is therefore used for storage of fixed programs, easily accessible when needed, saving the rewriting of the program over and over again. These programs are called MONITOR PROGRAMS - the microcomputer operating system programs. The Magnetic Memories are not part of the microprocessor system, and are linked to the various busses by means of INTERFACE units. These memories are both read and write memories. They are usually in the form of disks, diskettes (floppy disks), tapes etc. These magnetic memories allow for storage of programs and data in a manner that allows them to be preserved or even rewritten. The capacity of these memories is very high, however they have the drawback of being physically large and need extra racks and interface units in order to be used. Additionally, their stored data is accessed more slowly than the data stored in the ROM and RAM. EB-3191 – Introduction to microprocessors and microcontrollers 13 The 8051 has two types of Input/Output units. One type consists of input and output ports. Addressing of these ports is done in the same way a cell of internal RAM is addressed. "Write" will deliver data to the external world whereas "read" will take in data from an external source. The 8051 has four such ports. The second type of Input/Output units is external DATA memory cells. The CPU addresses these units exactly in the same manner as it addresses external RAM memory cells. 1.7 Principles of the microprocessor's operation There are three characteristics of the microcomputer system: a) b) c) All of the units connected to the CPU are connected in parallel by means of the three BUSSES previously mentioned. Any unit not addressed by the CPU is disconnected from the DATA BUS, thereby allowing free flow of data on this BUS. Also, no two units can possibly have a common address. The microcomputer system is synchronized i.e. the pace of work is constantly under the timing-control of the clock. Each operation is carried out in stages (steps). The CPU operates according to a work-program, found in the memory in a group of adjacent cells. This program is in fact a collection of binary numbers representing instructions and data. The 8051 CPU is designed so that upon initial operation of the microcomputer, it turns to a specific address, called 0000H, which is to be found in the system's ROM. This address is loaded onto the PC (Program Counter). The CPU then turns to the address shown by the PC, and recalls from the address the binary number located there. The CPU will expect this binary number to be an instruction it must to carry out (the programmer is required to see to this), consequently it will forward this number on to the control unit. The control unit then decodes and carries out the instruction. This operation is called INSTRUCTION FETCH. After retrieving the instruction, the PC is automatically incremented by 1, and points to the next cell. In general, the address 0000H contains an instruction referring the CPU to the address at the beginning of the main program. This program is called the MONITOR program. EB-3191 – Introduction to microprocessors and microcontrollers 14 The control unit requires additional data in order to execute a large part of its instructions. Some instructions even comprise 2 or 3 binary numbers, listed one after another. In these cases, the CPU retrieves the numbers required to complete the execution of the instruction. The control unit is able to discern how many numbers comprise the instruction, and what operation it is required to execute. Upon retrieval of each number by the control unit, the PC increases automatically by one and points to the next cell. When the instruction has been executed, the PC is pointing to the following cell. The control unit would expect that the binary number in this cell is a new instruction. The control unit, after retrieving the instruction, executes it. Each instruction is actually composed of two steps - FETCH (retrieval) and EXECUTE. Following are a few examples of typical instructions received by the CPU: a) b) c) Transfer of a number or contents of a register to a memory cell. In this case, the operation will include an additional reference to the memory and the designated address. Instructions that pass data between the various registers. These instructions are executed within the CPU. Instructions that include arithmetic or logic functions. The control unit is assisted by the ALU in order to carry out these instructions. EB-3191 – Introduction to microprocessors and microcontrollers 15 1.8 Summary of used concepts Input: The units that receive the various signals (keys, electric voltages, etc.) fed into the microcomputer system by the user. Input units may also translate the signals into binary numbers. Output: The units which receive binary numbers from the CPU, and which translate the binary numbers into the required form for the user (characters on a screen, lighting up of lights, putting a system into operation, etc.). Clock: A clock which defines the speed at which the CPU operates and thereby the operating speed of the system. The CPU's speed has to be regulated in accordance with the reaction time of various components. It is part of the timing system. Memory: A formation of cells, which has a number in each cell called a BYTE, and which is limited in size depending on the type of microprocessor. Each cell has a serial number called its ADDRESS. The types of memory are: RAM - read/write memory. ROM - read only memory. MAGNETIC MEMORIES - discs, diskettes, floppy disks, magnetic tapes. CPU: The Central Processing Unit. It passes on data between the microcomputer's various units and processes them in accordance with the work-program stored in the memory. It is usually called MICROPROCESSOR. Registers: Memory units within the CPU, which are each able to hold only one number. They are used for temporary storage of data needed to be processed and used immediately. EB-3191 – Introduction to microprocessors and microcontrollers 16 Accumulator: The most active register in the CPU. A large amount of data in the CPU flows through this register. ALU: Arithmetic Logic Unit. It performs the processing of the various numbers that reach the CPU. Microcomputer: A unit including all of the above elements (CPU, ROM, RAM, Input, Output and clock). Microcontroller: One chip microcomputer. All the microcomputer elements (CPU, ROM, RAM, INPUT, OUTPUT and CLOCK) are built in one chip and are in one package. EB-3191 – Introduction to microprocessors and microcontrollers 17 Summary questions: 1. Which lines transfer the memory cell contents to the CPU? (a) (b) (c) (d) 2. Which lines indicate the memory cell number to read from or to write to? (a) (b) (c) (d) 3. The address bus. The data bus. The control bus. The clock lines. The address bus. The data bus. The control bus. The clock lines. Which lines signal the timing of the reading and the writing? (a) (b) (c) (d) The address bus. The data bus. The control bus. The clock lines. EB-3191 – Introduction to microprocessors and microcontrollers 18 Chapter 2 – Addressing Modes A computer program is a collection of numbers situated in consecutive cells. The CPU fetches a number, decodes it and executes the instruction. The CPU has an internal 8-bit register, called the ACCUMULATOR. In order to transfer data from cell X to cell Y, for example, the CPU is instructed to transfer the data from cell X to the ACCUMULATOR, and then another instruction transfers it from the ACCUMULATOR to cell Y. A substantial part of the CPU's instructions relate to this accumulator. In some cases, the CPU needs an additional byte, or sometimes even two bytes of data, in order to be able to execute an instruction. The accumulator symbol is A. Example a: Let's assume we want the CPU to load the accumulator with the number 66. The number 74 will represent the instruction code to do this, after which the number 66 must be entered. Upon collecting the instruction code 74, the CPU shall understand that another number is to be fetched and this second number should enter the accumulator. This second number is not a code representing an instruction, but rather a data. The CPU knows too that after receipt of this data it should expect another instruction code. Note that if the CPU had begun with the number 66, it would have interpreted it as a coded instruction. Before proceeding, we will briefly explain a concept called "Mnemonic Instruction". INTEL, the developer of this microprocessor has given every instruction of the CPU an instruction mnemonic. For example, the instruction, which transfers data from its source to its destination is termed MOV (MOVe). This mnemonic may take on a number of forms. EB-3191 – Introduction to microprocessors and microcontrollers 19 The instruction to load the accumulator (A) with the number 66 would be written as follows: MOV A,#66 The number has been recorded in hexadecimal code. The # sign signifies immediate addressing, meaning that the number 66 is to be found in the computer program, immediately after the instruction code which was 74. It also signifies that 66 is a number and not a cell address. The instruction mnemonic is composed of two parts: the operation and the operands. The operation in this example is the instruction MOV. The operands are A and the number 66. The first operand will always be the destination (where to transfer) and the second operand will be the source (what or from where to transfer). In this example, the number 66 is to be transferred to A. Example b: Assume we wish to store the accumulator's contents in cell 0115. To gain access to a memory cell for purposes of storage or retrieval of data, the CPU is assisted by an additional register, called DPTR (Data PoinTeR). We need to make sure that the address of the cell being accessed is recorded in this register. From this, we know that the register has 16 bits, actually being two bytes of 8-bits each: the first byte, which contains the higher digits called DPH, and the second byte which contains the lower digits, called DPL. The number 90 represents the instruction code to load a number into the DPTR. The required address - 0115 should be placed after the instruction code. When the CPU collects the instruction code 90, it understands that it is required to fetch a further two numbers, which will serve as an address for the DPTR to point to. These numbers will be recorded by the CPU in the DPTR register. The two numbers are data, and not an instruction code. Only after receipt of these two numbers, will a new instruction code be anticipated. EB-3191 – Introduction to microprocessors and microcontrollers 20 The instruction to load the address 0115 into the DPTR would be as follows: 90 01 15 The mnemonic instruction to load the DPTR with the number 0115 would be as follows: MOV DPTR,#0115 Example c: The instruction to store the accumulator's contents in the cell indicated by the DPTR is a 1 byte instruction. Its code is F0. Upon receipt and decoding of this coded message, the CPU will register the Accumulator contents in the external memory address found in the DPTR. The mnemonic instruction to store the accumulator's contents in the external RAM cell indicated by the DPTR would be as follows: MOVX @DPTR,A Where X signifies dealing with the external RAM, and @ is a conventional term for the word AT. In other words, the instruction means: store the contents of A in the external RAM cell indicated by the DPTR. The CPU requires data in order to carry out instructions. Different methods exist to show data or its location, and these are called ADDRESSING MODES. The addressing mode is hidden in the instruction code received by the CPU, which treats the data in accordance with the relevant addressing mode and code. EB-3191 – Introduction to microprocessors and microcontrollers 21 2.1 Register addressing mode In an instruction such as this, only the registers are addressed, not the memories. The instruction code indicates also the specific register or registers under question. For example, the instructions: Move contents of R0 to A Increase A by 1 E8 MOV A,R0 R0 A 04 INC A A+1 A The instructions in REGISTER ADDRESSING MODE instructions occupy only one memory cell. 2.2 Immediate addressing mode In this addressing mode, the data is found following the instruction code, within the program. For example: Load A with the number 55 74 MOV A,#55 (55) A 55 This instruction fills 2 memory cells. In the mnemonic, the character # is joined to the data to signal immediate addressing mode. In cases where the data is a 16-bit number the instruction will fill 3 memory cells. For example: Load DPTR with the 90 MOV DPTR,#4010 4010 DPTR number 4010 40 10 EB-3191 – Introduction to microprocessors and microcontrollers 22 2.3 Variables The greatness of the computer is in its ability to manipulate variables, allowing the writing of a general program with variables whose values are defined during the course of the program or whose values change from time to time during the program. The principle behind the operation of this kind of program, is in not defining data in the instructions, but rather the address at which it is located or to which it is transferred. The data (cell contents) can change, but this will make no difference to the program. When writing a program like this, part of the memory must be assigned beforehand to cells, which will contain variable data, the cells being of RAM type. The group of cells before the program, or the group after it, may be assigned, but not a group in the middle of the program. Instructions, which manipulate variables require numbers indicating the address at which the variable's value is stored, in order for the instruction to be executed. 2.4 Direct addressing mode In direct addressing, the address of the cell containing the data must be indicated, where after the instruction will be executed using the data in the cell. In the 8051 this mode of address is used with internal RAM only, that is, the indicated cell's address is a one-byte number. Direct addressing mode instructions fill two bytes. For example: Load A with contents of direct cell 55 E5 MOV A,55 (55) A 55 The contents of the cell 55 will be found in A after execution of the instruction has been completed. We should bear in mind that some of the direct addressing mode cells are special registers or other special components such as ports or timers, which will be dealt with later on. EB-3191 – Introduction to microprocessors and microcontrollers 23 Addressing of external RAM cells or cells in the area of the program cannot be done by direct addressing, but is done by means of the INDIRECT ADDRESSING MODE. 2.5 Indirect addressing mode In this form of addressing neither the data nor its address are indicated, as an indicating register is used. DPTR is the indicating register in the 8051. Before using it, it is primed with the address to which we require it to point. In the instruction, which uses it, the required data is found at the address indicated by this register. For example: Load A with contents E0 MOVX A,@DPTR (DPTR) A indicated by DPTR In the above instruction, the address is found in external RAM. There is also a similar instruction, which loads A from the PROGRAM area (the CODES area). For example: Load A from the cell 93 MOVC A,@A+DPTR (A+DPTR) A address DPTR+A in the PROGRAM area The character @ represents the word AT. When working with blocks of consecutive memory cells (strings or arrays for example), it is essential to use the indirect addressing mode. Here, the cell indicated by the pointing register is operated on, thereafter the pointing register moves forward by one, and the operation is then done on the next cell. This procedure is repeated by means of a loop, so that long strings can be dealt with, without need to indicate the addresses of all the cells in the block. EB-3191 – Introduction to microprocessors and microcontrollers 24 The 8051 allows addressing of a cell related to the address indicated by the program counter. This command has an interesting application in look up tables. An example and an explanation of look up tables appears in chapter 6. Load A from the cell address 83 MOVC A,@A+PC (A+PC) A A+PC to be found in PROGRAM area In the direct areas of the 8051, one is also able to use indirect addressing. Since this is a 256-byte area, only an 8-bit register is required. Registers R0 and R1 may be used as indicating registers. For example: Load A from cell in the E6 E6 MOV A,@R0 (R0) A direct area indicated by R0 2.6 Bit manipulation In the direct RAM area, the 8051 has areas having an address for each bit. Addressing of these bits is done by means of special instructions called BOOLEAN VARIABLE MANIPULATION, described in chapter 6. These direct bits can be used as flags. For example: Zero the bit whose address is indicated Raise direct bit to '1' Jump if direct bit is '1' CLR BIT SETB BIT JB BIT,REL EB-3191 – Introduction to microprocessors and microcontrollers 25 Summary questions: 1. Why the following instruction is called immediate addressing mode? 74 MOV A,#55 55 (a) Because the address is included in the command. (b) Because the data is part of the instruction and comes immediately after the command 74. (c) Because this instruction comes immediate with the address. (d) There is no reason for this name. 2. How we use variables in order to use the instructions in general? (a) We indicate memory cells in the instruction instead of numbers and the data in the cells can change. (b) The program changes the number in the instruction. (c) We use letters instead of numbers. (d) We cannot use variables in microprocessor program. 3. What is bit manipulation instruction? (a) (b) (c) (d) An instruction that deals with 8 bit binary numbers. An instruction that deals with 16 bit binary numbers. An instruction that manipulates a certain bit in a register. All the instructions are bit manipulation. EB-3191 – Introduction to microprocessors and microcontrollers 26 Chapter 3 – Flags Flags are one-bit cells in the CPU, found in a register termed PSW (PROGRAM STATUS WORD REGISTER). Each cell has its own name and operates independently. The flags' purpose is to enable conditional branching instructions to be executed. Branching instructions that react upon certain conditions and relate to these cells only. From a point of view of electronics, it is difficult to build an electronic circuit, which would carry out an operation such as: IF A > B GOTO ... So this has been split up into two stages: The flags change, depending on the result of comparing B to A received from the ALU (Arithmetic Logic Unit), and the branching instruction relates to the flags. The 8051 has the following flags: CARRY flag. AUX CARRY flag. ZERO flag. OVERFLOW flag. PARITY flag. EB-3191 – Introduction to microprocessors and microcontrollers 27 3.1 Carry flag (CY) This flag rises to 1 when a ninth bit is formed as a result of an operation carried out in the ALU. For example, in the following operation: 10110011 + 01110010 [1] 00100101 After the above operation, 1 will appear on the CARRY flag. 3.2 Aux Carry flag (AC) If at the time of execution there would be a CARRY from bit 3 (the fourth bit) to bit 4 (the fifth bit), this flag would be raised. This flag is needed when instructions involve foursomes of bits or the B.C.D. code. The CPU is assisted by this flag in these instructions. 3.3 Zero flag (F0) Although this flag is called ZERO flag, it is not raised or cleared automatically, but by program instructions. It can be used by the programmer as a general purpose flag. 3.4 OVerflow flag (OV) This flag indicates when an incorrect result has been obtained, in cases where integers are used. For instance, the numbers 5F and 4C are positive numbers, which if added together lead to a negative number: +5F +4C -55 01011111 + 01001100 10101011 Here, the overflow flag will rise to 1 because the addition of two positive numbers led to a negative number. EB-3191 – Introduction to microprocessors and microcontrollers 28 It should be noted that it is the program writer's prerogative to decide whether to work with integers. For example, we could show the previous example to be an addition of two 8bit numbers as follows: 5F 4C AB 01011111 + 01001100 10101011 The overflow flag will rise to 1, and it is at the program writer's discretion whether to take notice of it or not, as is the case with any other flag. Another example of an incorrect result: -7B -4D +38 10000101 + 10110011 [1] 00111000 Checking of whether an obtained result is correct or not is done by the checking of the carry attained from the two most significant bits (bit 6 and bit 7). If either both of them or neither of them lead to a carry, the result will be correct. If from only one of them, the result obtained will be incorrect. 3.5 Parity flag (P) When this flag is raised (status '1'), this indicates that there is an even number of 1's in the outcome of the operation. This is important for communication between computers. EB-3191 – Introduction to microprocessors and microcontrollers 29 3.6 Summary The bits of the status register are organized as in figure 3-1: MSB CY LSB AC F0 RS1 RS0 OV - P Figure 3-1 Status Register Organization Bits RS0 and RS1 do not act as flags. Their purpose will be elaborated on in section 6.1 of chapter 6. Not all of the flags have special instructions, which operate on them. On the other hand, the 8051 has various instructions enabling single bits within the direct RAM, including the status register, to be dealt with. These instructions enable us to change these bits or to react in different ways to their status. As previously pointed out, the flags automatically react to the outcome of operations of the ALU. Additionally there are various instructions, which enable the changing of the flags' status - to raise them to 1 or to clear them. EB-3191 – Introduction to microprocessors and microcontrollers 30 Summary questions: 1. The carry flag is '1': (a) (b) (c) (d) 2. The zero flag is '1': (a) (b) (c) (d) 3. After an instruction that creates a ninth bit. After moving data from register to register. Before adding two bytes. Only by a certain command that turns it to 1. After an instruction that creates a ninth bit. After moving data from register to register. Before adding two bytes. Only by a certain command that turns it to 1. Which part of the CPU affects the carry, the aux carry and the overflow flags? (a) (b) (c) (d) The accumulator. The ALU. The ports. The internal ROM. EB-3191 – Introduction to microprocessors and microcontrollers 31 Part II Chapter 4 – Machine and Assembly Language with the 8051 4.1 Preface This chapter is intended to familiarize the reader with the principles underlying the structure of the computer and the manner in which it operates as well as the fundamentals of programming in machine language and Assembly language. Some of the following description was already described in the previous chapter, but this revise is important. Read the preface at your own pace and continue to the experiments that follow. The exercises will make the background material simpler to absorb. The CPU - the heart of the system - works according to a program. Its work "schedule" is composed of instructions coded in 8-bit binary numbers. These numbers are to be found in the memory cells, and are sequential. The CPU fetches a binary number from a cell, decodes it and executes the instruction represented by the specific number. Each memory cell has a unique address, which is a 16-bit binary number. The CPU is connected to the memory cells by means of three BUSSES: an ADDRESS BUS, a DATA BUS and a CONTROL BUS. Each bus is a collection of lines, which carry binary numbers. All of the memory cells are connected to the busses. When a number is required to be retrieved from a memory cell by the CPU, The CPU does the following, step by step: a) b) c) Registers the required cell's address on the address bus (a 16-bit number). The CPU declares that it is in a READ mode, and selects the type of memory concerned by means of the control bus. Reads the number, which appears on the data bus (an 8-bit number). EB-3191 – Introduction to microprocessors and microcontrollers 32 The memory cell, which identifies the address on the address bus as being its own, as well as its own memory-type being identical to that on the control bus, will deliver its contents to the data bus at stages b and c. The contents of the memory cell are not erased. These are the steps taken when the CPU wishes to write data into a memory cell: a) b) c) The required cell's address is registered by the CPU on the address bus. Writes the data on the data bus. The CPU declares that it is in a WRITE mode, and selects the type of memory concerned by means of the control bus. The memory cell, which identifies the address on the address bus as being its own, as well as its own memory-type being identical to that on the control bus, will now collect the data. The new data will replace the previous contents of the memory cell. As can be seen, a microcomputer is a synchronized system. Every microcomputer has a clock, which defines the speed of the system, and the microcomputer's components are synchronized with it. A computer program is a collection of binary numbers, consecutively found in memory cells. The order of the numbers defines what the program does and the resulting operations of the CPU. Each program has a starting address, which is the address of the cell containing the program's first instruction. To get the CPU to execute a program, it has to be referred to the address of the first cell of the program. From here on it will carry on under its own steam. Some of the microcomputer's cells are cells, which may be read and written on. These cells are called RAM cells (READ/WRITE memories). The contents of these cells are wiped out when the power supply is cut off. When the power supply to the system is renewed, random contents will be found in these cells. Other cells are of a type whose contents are preserved even when the power supply is cut off. These cells cannot be written on, and are called ROM (Read Only Memory). These cells contain the system's permanent programs and fixed data. EB-3191 – Introduction to microprocessors and microcontrollers 33 The 8051 microcontroller has three different memory areas – PROGRAM area, internal RAM area and the DATA area. The computer's program is stored in the PROGRAM area, which is usually a ROM-type area. This area covers all the addresses 0000-FFFF, i.e. 64K bytes. The 8051 contains a ROM of 4K bytes. The software on this ROM must be manufactured into the microcontroller chip during the production process. Another microcontroller, called the 8031, is identical to the 8051 with the exception of not having an internal ROM, but works with an external ROM. The CPU requires a RAM area, whenever executing a program, for purposes of storage of variable data. The developers of the 8051 placed a 256-byte RAM in the chip, of which 128 bytes serve as an area for data storage. This area is also termed DIRECT MEMORY. The first 32 bytes of this area make up 4 blocks, each of eight 8-bit registers, called R0-R7. This area of direct memory is not addressed through the microprocessor's external busses. It is accessed internally. The remaining 128 bytes of internal RAM serve as SPECIAL FUNCTION REGISTERS. Occasionally, a microcomputer system needs a RAM area larger than 128 bytes. This would typically be the case when the microcomputer is used for processing large amounts of data. When this is the case, external RAM units can be added to the 8051. These units are connected in parallel to the address, data and control busses. These units can also occupy the area 0000-FFFF, the 8051's DATA area. Among the CPU's control lines, there are lines used by the CPU to signal whether the program area or data area is being addressed. Each memory unit has a circuit, which decodes the lines and responds accordingly. Activation of the system or pressing the <RST> key will refer the CPU to the address 0000 found in the PROGRAM area. This address is to be found in the ROM of the system. This address contains an instruction referring the CPU to a program called the MONITOR PROGRAM. The CPU has special instructions enabling it to address either the external DATA area or the DIRECT area. The CPU's control unit decodes the instruction and executes it accordingly. EB-3191 – Introduction to microprocessors and microcontrollers 34 Experiment 4.1 – Software Installation and Operation Objectives: Introduction to SES51C Installing the software Running the SES51C Equipment required: EB-3000 EB-3191 Discussion: This experiment describes the way to operate the EB-3000 with EB-3191 with a computer and the software package SES51C. SES51C is a Full Screen Editor, Assembler, C Compiler, Debugger software. The setup installs the software and the included compilers. EB-3191 – Introduction to microprocessors and microcontrollers 35 Procedure: Installing the SES51C software Step 1: Turn ON the PC. Step 2: Run the SES51CSetup.exe, which is in the SES51C directory in the CD. This program will install the SES51C in your hard disk. A shortcut to the SES51C program will be located on the desktop. After installing the SES51C, the program will install the SDCC C compiler. Step 3: During the installation of the SDCC you will be asked whether to add the SDCC to the PATH. Answer with 'Yes'. The program installs also a USB to COM driver. The following steps describe how to identify which com port is used by the USB driver. EB-3191 – Introduction to microprocessors and microcontrollers 36 Identifying the USB serial COM: Step 4: Open the "Device Manager". Step 5: Right click on "My Computer" and choose "Properties". Step 6: Choose the "Hardware" tab. Step 7: Choose the "Device Manager". Step 8: Extract the "Ports (COM & LPT)". Step 9: Look for the "Silicon Labs CP210x USB to UART bridge". Step 10: Check which COM is written. EB-3191 – Introduction to microprocessors and microcontrollers 37 Operating the trainer with the PC Step 1: Connect the EB-3000 to the power supply. Step 2: Connect the power supply to the Mains. Step 3: Turn ON the trainer. The DVM screen should appear on the display. Step 4: Plug the EB-3191 into the EB-3000. Step 5: Observe the display and check that the experiment board name appear and no fault is detected. Step 6: The serial communication cable is a USB cable type A and type B connectors. Connect the type A connector to the USB inlet of the PC and the type B connector to the trainer USB inlet. EB-3191 – Introduction to microprocessors and microcontrollers 38 Step 7: Run the SES51C software by double clicking on SES51C icon on the desktop. An introductory screen will appear on the screen: Step 8: Use the mouse or press [Alt + F] and look at the sub-functions of the FILE function. Move right and left with the arrows or with the mouse and observe the other functions and their sub-functions. To leave any window, key <ESC>. Step 9: Select the OPTIONS function. Select the sub-functions is DEBUG OPTIONS. EB-3191 – Introduction to microprocessors and microcontrollers 39 You can define the PC COM port, the baud rate and the trainer you are using in the DEBUGGER OPTIONS window that is opened. Moving from one field to another is done by the <TAB> or <Shift TAB> keys or by clicking with the mouse on the desired field. Movement in the field is done with the arrow keys. EB-3191 is working at 19,200 baud. Select "EB-3191". "Start Address" should be 2100. Select the COM port and press <ENTER> or click <OK> with the mouse. EB-3191 – Introduction to microprocessors and microcontrollers 40 Step 10: Select again the OPTIONS function. Select now the COMPILER OPTIONS. Step 11: Check that the Assembler Compiler is selected. This assembler is part of the SES51C. Step 12: Select the OPTIONS function again. Now choose the SAVE CONFIGURATION sub-function. From now on, the definitions you chose are stored in the configuration file and will be the system’s default. EB-3191 – Introduction to microprocessors and microcontrollers 41 Calling the terminal window Step 1: Select the DISPLAY function. Step 2: Select the Display Terminal sub-function. This function will open a terminal window on the screen. You can magnify this window and place it anywhere on the screen. Operating SAVE CONFIGURATION will also save the location and size. Step 3: Press RST on EB-3191. EB-3191 will send an opening message to the computer ended by '*'. This message should appear on the terminal window. The terminal window allows us to observe the communication between EB-3191 and the PC. In this way, we can identify if EB3191 and the PC react to each other. EB-3191 – Introduction to microprocessors and microcontrollers 42 Experiment 4.2 – The Debugger Functions Objectives: The debugger fields Examining and changing memory contents Filling memory range Copying blocks Programming in machine language and disassembly Equipment required: EB-3000 EB-3191 Discussion: The DEBUGGER is a software intended for running a program on the trainer we want to check and locating errors (bugs debugging) in it. The DEBUGGER software includes windows, which present different parameters of the tested trainer. When the DEBUGGER software is activated, it starts working interactively with the trainer, which is connected to the PC in serial communication. EB-3191 – Introduction to microprocessors and microcontrollers 43 Procedure: Step 1: Connect the EB-3000 to the power supply. Step 2: Connect the power supply to the Mains. Step 3: Turn ON the trainer. The DVM screen should appear on the display. Step 4: Plug the EB-3191 into the EB-3000. Step 5: Observe the display and check that the experiment board name appear and no fault is detected. Step 6: Connect the EB-3000 to the PC with the USB cable. Step 7: Run the SES51C software by double clicking on SES51C icon on the desktop. Step 8: Check that the VP/EA switch is at VP position. Step 9: Press <RST> on the EB-3191. Step 10: Click over the DISPLAY function and the following screen will appear. The list below 'Display All - On' is the list of the debugger fields. The mark indicates that all the fields that are marked with will be opened automatically when we click on Display All - On. EB-3191 – Introduction to microprocessors and microcontrollers 44 Click on the DISPLAY and REGISTER functions. If it was marked with , it will not be opened. Instead, the mark will disappear. Do it again and the register window will appear. Drag it to the most upper right corner of the screen. After opening all the windows, click OPTIONS and then SAVE CONFIGURATION. Step 11: Repeat this step and open all other windows and organize them as describe below. The data in each window comes from the trainer through the communication line. In order to close all the windows, you have to select the DISPLAY and DISPLAY ALL functions. If it was not marked, you have to do it twice. Note: In order to make the software friendlier, you can also use the mouse right button. Clicking on the right button when the cursor is above a window, opens options that can be operated. At the moment, continue with the options as described in this chapter and not with the shorter way. EB-3191 – Introduction to microprocessors and microcontrollers 45 Step 12: If the announcement "Trainer does not answer" appears, press <RST> on the trainer. Step 13: If it does not help, press <ENTER>. Check the connections to the PC and the trainer’s configurations you have defined. The DEBUGGER screen includes 6 fields: Direct Memory field. Disassembly List field. Registers field. Program Memory field. External memory field. Terminal field. The terminal screen presents all the communication data from the computer to the trainer (the commands that are sent) and from the trainer to the computer. We can use it for giving direct commands. You don’t have to open all the windows in order to use the DEBUGGER software. It is enough to open only the required windows. It will enhance the speed of updating the screen. Step 14: The F9 key (DISPLAY ALL) opens simultaneously all the windows, which were checked with a mark. Keying F9 again closes all the open windows. EB-3191 – Introduction to microprocessors and microcontrollers 46 Examining and changing memory contents Step 1: Select the MEMORY main function and the UPDATE PROGRAM sub-function. Step 2: Write the number 3000 in the opened window and press <ENTER>. The Program Memory window now shows the contents of the addresses range 3000-303F. From now on, 3000 will be the default address for showing the addresses range in this field. Step 3: Click over the Program Memory window. This window shows the contents of the cells in the range: 3000-303F Step 4: Move the cursor to the first byte at address 3000. EB-3191 – Introduction to microprocessors and microcontrollers 47 Step 5: Press the Space key. A window with a field with two characters for receiving data opens. Write the number 40 and click over <OK>. The number 40 will be send to the trainer and will change the contents of cell 3000. On the right side of the line the '@' character appears. This character is an ASCII character and its code is 40H. The ASCII code is an international standard code in which each character had a certain binary value. The binary numbers 00-1F indicate in the ASCII code special control characters. The debugger cannot indicate these control characters, thus instead it indicates a period at the right part of the display. Step 6: Move the cursor to address 3001. Enter the number 41 to address 3001. Step 7: Continue to enter the numbers 42-4F to addresses 3002-300F accordingly. The ASCII code of the numbers 40-4F is: "@ABCDEFGHIJKLMNO" The area 3000-3FFF in the DSM-2095 is mapped as a program area, and despite this, the system allows writing to it because the ROM component is EEPROM. Step 8: You can move up and down using the arrows. If you are at the top line and trying to move upwards, all the block is updated with a line (for example, the block will start at address 2FF0). The same happens when moving downward. EB-3191 – Introduction to microprocessors and microcontrollers 48 Step 9: To move in block spacing inside the memory, you can also use the PgUp and PgDn keys. Remember, each screen update is based on the communication between the computer and the trainer and data transfer, thus this process requires time. Step 10: Select the MEMORY main function and the UPDATE PROGRAM sub-function and bring back the program field display, so that the top line will show the cells starting at address 2100. EB-3191 – Introduction to microprocessors and microcontrollers 49 Filling memory contents Sometimes we need to fill a certain range in the RAM memory with a certain data. Step 1: Select the MEMORY main function and the FILL EXTERNAL sub-function. A window with 3 fields for receiving data opens: Block Start Address Block Last Address Destination Byte Value Movement from field to field is done using the mouse or the <TAB> key. Press the <ENTER> key or click over <OK> only after filling all the fields. Step 2: Enter the following parameters into the fields: Start Address .................... 2100 Last Address ..................... 2115 Destination Value ............. 55 Press the <ENTER> key. The range 2100-2115 in the external memory will be filled with the number 55(its ASCII character is 'U'). EB-3191 – Introduction to microprocessors and microcontrollers 50 Copying blocks Step 1: Select the MEMORY main function and the COPY PROGRAM MEMORY sub-function. A window with 3 fields for receiving data opens: Block Start Address Block Last Address Block Destination Address The start address and the last address define the source block and relate to the program area. The destination address defines the start of the destination block (similar in length to the soruce block) and relates to the external area. Press the <ENTER> key or click over <OK> only after filling all the fields. Step 2: Enter the following parameters into the fields: Start Address .................... 2100 Last Address ..................... 2112 Destination Value ............. 2120 Press the <ENTER> key. The range 2100-2112 from the program area will be copied into the block starting at address 2120 in the external area. There is an additional function called COPY EXTERNAL MEMORY, which copies a block from external to external. We will not exercise this function because the DSM-2095 card does not have an external memory to read from. EB-3191 – Introduction to microprocessors and microcontrollers 51 Programming in machine language and disassembly A computer program is a collection of numbers located in cells one after the other. The CPU collects a number, decodes it and executes it. The CPU has an 8 bits internal register called accumulator. When, for example, we want the CPU to transfer data from cell A to cell B, we instruct the CPU to transfer the data from cell A to the accumulator, and another instruction to transfer the data from the accumulator to cell B. You can also use another register. A large part of the CPU's instructions are connected to this accumulator. In some of the instructions, the CPU needs additional parameters for execution. Example A: Let's assume that we want the CPU to load the number 66 to the accumulator. The instruction to load a number to the accumulator is the code 74. After this code, you need to write the number 66. When the CPU collects the code 74, it knows that it needs to collect another number and to load it to the accumulator. This number is not an instruction code for the CPU, but data. The CPU also knows that after this data, it needs to wait for a new instruction code to perform. Note that if the CPU would have started with the number 66, it would have tried to decode it as an instruction code. Who knows what it would have performed? Before we go on, let's explain another concept called "Mnemonic". Intel company, which developed this microprocessor gave a mnemonic to each instruction of the CPU. For example, the instruction to move data from source to destination got the mnemonic MOV (MOVe). This mnemonic has a number of forms. We will address some of them now. EB-3191 – Introduction to microprocessors and microcontrollers 52 The mnemonic for loading the number 66 to accumulator A is written as follows: MOV A,#66 The character # indicates numerical value. This character symbolizes here that 66 is a number (and not a cell address), and that it is part of the instruction and comes right after the mnemonic. The mnemonic is composed of two parts: operation and operand. The operation in this case is the instruction MOV. The operands are A and the number 66. The first operand is always the destination (where to transfer) and the second operand is the source (what or from where to transfer). In this case, the number 66 should be transferred to A. Example B: Let's assume that we want to store the accumulator contents in address FF00. In order to address a memory cell (for reading data or storing data), we use a special register which point to this memory cell. This register is called DPRT (Data PoinTeR). We load this register with the address of the cell we wish to address. The instruction to load a number to the DPTR is the number 90. After this code we write the desired value – FF00. When the CPU collects the code 90, it knows that it needs to collect two additional numbers to load into the DPTR. For the CPU, these two numbers are data and not an instruction code. Only after loading these two numbers, it will wait for a new instruction code. In other words, the instruction to load the number FF00 to the DPTR is written as follows: 90 FF 00 EB-3191 – Introduction to microprocessors and microcontrollers 53 The mnemonic of the above instruction is: MOV DPTR,#FF00 The 8 LEDs in the DSM-2095 card occupy this address, so the data written to this address will be seen on the LEDs. Example C: The instruction to store the accumulator contents in the cell the DPTR points to is a one byte instruction and its code is F0. When the CPU reads this code it goes to the cell the DPTR points to and writes there the accumulator contents. The mnemonic is: MOVX @DPTR,A The letter X indicates addressing an external RAM (as mentioned, the CPU also has an internal RAM). The character @ is used as a shorten symbol for the word AT. In other words, the instruction is to store A in the external RAM at the address the DPTR points to. Example D: For the end of program instruction we will give the CPU an instruction which returns it to the monitor program. The instruction has 3 bytes and its codes are: 12 01 03 The mnemonic is: LCALL 0103 This instruction turns the CPU back to the monitor program. EB-3191 – Introduction to microprocessors and microcontrollers 54 Let's write a program combined from the above 4 examples. Step 1: Move the cursor to address 0100 in the PROGRAM MEMORY field. Enter the numbers: 74 to address 2100 66 to address 2101 In the disassembly field the following mnemonic appears: MOV A,#66 Which means, load the number 66 to the accumulator. The disassembly field displays the mnemonics of the codes in its addresses range. The conversion from codes to mnemonics is called a disassembly operation. Step 2: Enter the following numbers: 90 to address 2102 FF to address 2103 00 to address 2104 In the disassembly field the following mnemonic appears: MOV DPTR,#FF00 Which means, load the number FF00 to the address the DPTR points to. EB-3191 – Introduction to microprocessors and microcontrollers 55 Step 3: Enter the number F0 to address 2105. In the disassembly field the following mnemonic appears: MOV @DPTR,A Which means, store the accumulator in the cell at the external RAM the DPTR points to. Step 4: Enter the following numbers: 12 to address 2106 01 to address 2107 03 to address 2108 In the disassembly field the following mnemonic appears: LCALL 0103 This instruction returns the CPU to the debugger program. Step 5: In order to run the program, select the DEBUG main function and the RUN sub-function. A window is opened asking for the start address and suggest the address located in a special area called PC (Program Counter) as default. If this value is 2100, click over <OK> to confirm. If not, write 2100 and confirm. The CPU performs the program. It start at address 2100 and stops at address 2109. Step 6: Check if the number 66 appears on the LEDs. EB-3191 – Introduction to microprocessors and microcontrollers 56 Challenge exercise Step 7: Change the program so that the system's controller will move the number BB to cell FF00 while running the updated program. Step 8: Select the DEBUG main function and the PROGRAM RESET subfunction in order to run the program from the beginning. Step 9: Run the program and check if the changes were executed. EB-3191 – Introduction to microprocessors and microcontrollers 57 Experiment 4.3 – Input / Output Units Objectives: Input and output unit of EB-3191 Direct ports of the 8051 Offset branching Equipment required: EB-3000 EB-3191 Discussion: Every computer had Input / Output (I/O) units. The I/O units are connected to the CPU and are called ports. The input port receives data from the external world and transfers it to the CPU as binary numbers. The output port receives a binary number from the CPU and transfers it to the external world. The EB-3191 has one input unit and one output unit. 8 switches are connected to the input unit. This unit is located at address FF00H. 8 red LEDs are connected to the output unit, and this unit is also located at address FF00H. Before performing a number of exercises related to the I/O units, we will expand a little about mnemonic instructions. The instruction to load the number 55 to the accumulator is written as follows: MOV A#,55 The mnemonic is composed of an operation and operands. The operation in this case is the instruction MOV and its codes are: 74 55 EB-3191 – Introduction to microprocessors and microcontrollers 58 The operands are A and the number 55. The first operand is always the destination (where to transfer) and the second operand is the source (what or from where to transfer). In this case, the number 55 should be transferred to A. The LEDs unit is located at address FF00, thus the number FF00 is loaded to the DPTR. Addressing an input or output unit is similar to addressing a memory cell. The mnemonic is: MOV DPTR,#FF00 The instruction codes are: 90 FF 00 Moving contents A to an output port is done using the instruction: MOVX @DPTR,A Which means: move contents A to the output port that its address is written in the DPTR. This is a one byte instruction and its code is: F0 This instruction is in fact an instruction for storing contents in a memory cell (because the output port is built as a memory cell). The instruction which returns the program to the monitor program is: LCALL 0103 and its codes are: 12 01 03 The program will be: 2100 74 55 MOV A,#55 2102 90 FF 00 MOV DPTR,#FF00 2105 F0 MOVX @DPTR,A 2106 12 01 03 LCALL 0103 ;Load the number 55 to A ;Load the number FF00 to DPTR ;Store A in the port indicated by DPTR ;Call the monitor's return routine EB-3191 – Introduction to microprocessors and microcontrollers 59 Direct ports Let's take a closer look at the direct port in the controller. The 8051 has four direct ports. Each direct port has additional functions on top of being an I/O unit, except port 1. Port 1 is designated to act only as an I/O unit. It is located at address 90 and it is addressed by direct addressing. The data to port 1 can be sent as 8 bit byte like in the following commands: 74 55 F5 90 MOV A,#55 MOV P1,A 90 is the address of P1. Each of the bits of port 1 in EB-3191 has a special function. Their function will be discussed later (in part III of the book). These bits can addressed separately by special bit commands as explained in chapter 2. You can see that the difference between the switches/LEDs unit and the LEDs connected to port 1 is their addressing system. In the first type, addressing is done via the DPTR, thus it is called an INDIRECT ADDRESSING mode. In the second type, addressing is done directly, thus this method is called a DIRECT ADDRESSING mode. In the instruction to the direct port we write its address, and that is the reason why the addressing mode is called DIRECT ADDRESSING. The instruction includes the port address without the help of any index register. The direct port epitomizes the 8051 philosophy. The 8051 is not a single kind of micro-controller, but it is the kernel of an entire family of micro-controllers. These controllers are all identical in their instruction set, and in their basic structure. They differ only in one aspect – a set of special registers called Special Function Registers (SFR). These registers serve for those functions of the 8051, which are outside the bounds of the ordinary functions of a microprocessor. The 8051's four direct ports, for example, are four SFR's of the 8051. EB-3191 – Introduction to microprocessors and microcontrollers 60 When the 8051 was originally developed, a 128 byte SFR space was allocated. The basic 8051 actually contains 23 SFR's. The rest of the space was left free for future applications. As these registers are accessed directly by addressing them, there is no need to change the processor's instruction set, and so the variations in development tools for 8051 embedded systems are minor. Today the 8051 has become the biggest family of micro-controllers in the world. This family grows all the time and includes additional components and ports such as: ADC components, communication components, timers, counters and much more. The 8051 has become a leading components in the robotics, automation, equipment, control, autotronics, avionics fields etc. EB-3191 – Introduction to microprocessors and microcontrollers 61 Procedure: Step 1: Connect the EB-3000 to the power supply. Step 2: Connect the power supply to the Mains. Step 3: Turn ON the trainer. The DVM screen should appear on the display. Step 4: Plug the EB-3191 into the EB-3000. Step 5: Observe the display and check that the experiment board name appear and no fault is detected. Step 6: Connect the EB-3000 to the PC with the USB cable. Step 7: Run the SES51C software by double clicking on SES51C icon on the desktop. Step 8: Check that the VP/EA switch is at VP position. Step 9: Press <RST> on the EB-3191. Step 10: Write the following program according to the written addresses. Address Code 2100 2101 2202 47 55 00 2201 2207 2205 2201 2204 2201 FF 00 F0 22 01 01 Mnemonic Remarks MOV A,#55 MOV DPTR,#FF00 Load the number FF00 to DPTR (the port's address). MOVX @DPTR,A LCALL 0103 Load the number 55 to A. Store A in the port indicated by DPTR. Call the monitor's return routine. Step 11: Run the program. Step 12: The red LEDs should light up alternately since the number 55 is identical to the binary number 01010101. EB-3191 – Introduction to microprocessors and microcontrollers 62 Step 13: Change the program as follows: Turns ON only the right LED. Turns ON the forth LED from the right. Turns ON the 4 left LEDs. Turns ON the LEDs alternately, but not with the number 55. Turns OFF all the LEDs. Turns On all the LEDs. Step 14: Let's write a program that transfers the input switches' contents to the output LEDs. Write the following program according to the units you have. Address Code 2100 90 2101 2202 2201 2207 2205 2201 2204 FF 00 E0 F0 22 01 01 Mnemonic Remarks MOV DPTR,#FF00 Load the LEDs and switches port address to DPTR. MOVX MOVX LCALL A,@DPTR Read the status of the switches to A. @DPTR,A Store A in the LEDs. 0103 Call the monitor's return routine. Note the instruction: E0 MOVX A,@DPTR It means: "transfer the cell's contents indicated by DPTR to accumulator A". In our case, it means reading the input unit and transferring the status of the switches to A. Step 15: Run the program. The status of the switches should appear on the LEDs. Step 16: Change the status of the switches and run the program again. The LEDs should change accordingly. EB-3191 – Introduction to microprocessors and microcontrollers 63 Step 17: Change the last instruction, so instead to returning to the monitor, the program will run in an infinite loop. Use the instruction LJMP (Long JuMP). Its code is 02. Change the cells contents according to trainers you use. 0105 02 LJMP 2100 0106 21 0107 00 Step 18: Run the program. Step 19: Change the status of the switches (the LEDs should react accordingly). The following message appears on the screen: 'Trainer Running' The above message appears because the trainer's CPU runs the program in an infinite loop and does not react to the PC. Step 20: In order to stop the program's running, you should press the <RST> key on the card. Do that. EB-3191 – Introduction to microprocessors and microcontrollers 64 Offset branching The instruction LJMP, meaning Long JuMP, has been used in previous exercises. In this instruction, the full address of the instruction (to which the CPU should jump) is given. This is called a branching instruction. The 8051 has additional branching instructions. One of these is SJMP (Short JuMP). In this instruction, the number of steps to be jumped from the address shown by the PC (Program Counter) is to be given. This number, called OFFSET, is a one-byte number, which means that this instruction takes up only 2 bytes. The offset may be a positive number (representing jumping forwards) or a negative number (representing jumping backwards); consequently the most that can be jumped is 127 steps forwards (7FH) or 128 steps backwards (80H), which is why this is called a short jump. When this instruction is executed, the program's counter will show the address of the next instruction, therefore the number of bytes we wish to jump should be counted from there. We'll now write down the program we executed in section 2.8, the program which transfers the status of the switches to the LEDs in an infinite loop. Address Code 2100 2101 2202 2201 2207 2205 2201 00 FF 00 E0 F0 10 F9 Mnemonic Remarks MOV DPTR,#FF00 Load the number FF00 (the switches & LEDs address) onto DPTR. MOVX MOVX SJMP A,@DPTR @DPTR,A 2100 Load A from cell indicated by DPTR. Store A in the cell indicated by DPTR. Make a short jump to 0100. The offset. Note that we did show what the offset should be in cell 0106. The offset calculation should be: the address of the destination minus the branching address (the instruction address after the branchings instructions – the cell after the offset). Thus: 2100 – 2107 = -7 = F9 F9 is the 2's complement representation of – 7. EB-3191 – Introduction to microprocessors and microcontrollers 65 Step 1: Run the program starting at address 2100. Step 2: Change the switches and watch the LEDs change accordingly. This program runs in an infinite loop and can only be stopped by pressing the <RST> key. Step 3: Press <RST>. The program is not erased from the memory. Step 4: In order to update the debugger screen, Select the DEBUG main function and the PROGRAM RESET sub-function. Step 5: We will demonstrate one of the advantages of offset branching. Let's start by copying the program to a different addresses ragne. Select the MEMORY main function and the COPY PROGRAM MEMORY sub-function. A data entry window will be opened with 3 data fields: Block start address. Block last address. Block destination address. The start address and the last address define the source block in the program area. The destination address defines the first address in the destination block (the same length as the source block) in the external RAM area. Moving from one data field to another is done by the <Tab> key. Press <ENTER> only after checking or updating all the data fields. Step 6: Enter the following values into the data fields: Start address ..................... 2100 Last address ...................... 2110 Destination address .......... 2300 Press <ENTER>. EB-3191 – Introduction to microprocessors and microcontrollers 66 The addresses range 2100-2110 from the program area will be copied into memory starting at address 2300. Step 7: Update the Disassembly List field to display the range starting at address 2300. Select the MEMORY main function and UPDATE PROGRAM LIST sub-function. Watch the program on the screen and especially the branching address. Even though the program codes have not been changed, the branching instruction has been changed according to the program's location and is addressing the correct address. This is quite obvious, as we have defined the number of steps to branch, rather than the absolute target address. In this way, a program that includes offset branching may be allocated anywhere in the memory space and can still be run properly. Check this. Step 8: To change the system's default to the program's start address, Select the OPTIONS main function and the DEBUG OPTIONS subfunction. The number 2100 will appear in the Start Address field on the opened window. Enter the number 2300 and confirm. Step 9: Select the DEBUG main function and the PROGRAM RESET subfunction to update the screen data accordingly. Step 10: Run the program starting at address 2300 and check that the system behaves correctly. Step 11: Press <RST>. EB-3191 – Introduction to microprocessors and microcontrollers 67 Step 12: Return the Start Address to 2100 (in the DEBUG OPTIONS window). Step 13: Activate the PROGRAM RESET function. EB-3191 – Introduction to microprocessors and microcontrollers 68 Experiment 4.4 – Assembly Programming Objectives: Registers and conditional branching Writing programs in assembly language Subroutines Embedded microcontroller system Equipment required: EB-3000 EB-3191 Discussion: Registers and conditional branching The accumulator by itself is not large enough to process data. It acts mainly as a transit point. Additional registers are frequently needed. There are 8 registers (R0-R7) in the 8051, made up of 8 cells in its internal RAM. The CPU has special instructions relating to these registers. Following are some of these instructions: MOV MOV MOV MOV MOV XCH A,Rn Rn,A Rn,DIRECT DIRECT,Rn Rn,#DATA A,Rn Move register n's contents to accumulator A. Move A's contents to the register Rn. Move cell's contents to Rn by direct addressing. Move contents of register to cell by direct addressing. Move the recorded data to the register. Exchange A's contents with that of the register. EB-3191 – Introduction to microprocessors and microcontrollers 69 The instruction's codes are: E8 MOV A,R0 E9 MOV A,R1 EA MOV A,R2 EB MOV A,R3 EC MOV A,R4 ED MOV A,R5 EE MOV A,R6 EF MOV A,R7 F8 MOV R0,A F9 MOV R1,A FA MOV R2,A FB MOV R3,A FC MOV R4,A FD MOV R5,A FE MOV R6,A FF MOV R7,A A8 A9 AA AB AC AD AE AF MOV R0,DIRECT MOV R1,DIRECT MOV R2,DIRECT MOV R3,DIRECT MOV R4,DIRECT MOV R5,DIRECT MOV R6,DIRECT MOV R7,DIRECT 78 MOV R0,#DATA 79 MOV R1,#DATA 7A MOV R2,#DATA 7B MOV R3,#DATA 7C MOV R4,#DATA 7D MOV R5,#DATA 88 MOV DIRECT,R0 89 MOV DIRECT,R1 8A MOV DIRECT,R2 8B MOV DIRECT,R3 8C MOV DIRECT,R4 8D MOV DIRECT,R5 C8 C9 CA CB CC CD XCH XCH XCH XCH XCH XCH A,R0 A,R1 A,R2 A,R3 A,R4 A,R5 The following are interesting instructions, usually used to create loops: CJNE Rn,#data,rel: Compare the register's contents with the data listed in the instruction, and if the numbers are not equal, offset-branch with offset listed as rel. If the numbers are equal, move on to the next instruction. This instruction is composed of 3 bytes. DJNZ Rn,rel: Subtract one from the value of the register's contents (Decrement) and if the result differs from zero, branch off by listed offset. This instruction has 2 bytes and is used for counting loops. EB-3191 – Introduction to microprocessors and microcontrollers 70 The instructions codes are: B8 CJNE R0,#DATA,rel B9 CJNE R1,#DATA,rel BA CJNE R2,#DATA,rel BB CJNE R3,#DATA,rel BC CJNE R4,#DATA,rel BD CJNE R5,#DATA,rel BE CJNE R6,#DATA,rel BF CJNE R7,#DATA,rel D8 DJNZ R0,rel D9 DJNZ R1,rel DA DJNZ R2,rel DB DJNZ R3,rel DC DJNZ R4,rel DD DJNZ R5,rel DE DJNZ R6,rel DF DJNZ R7,rel We will use the instruction DJNZ in order to create a delay. We will write a program that will flash the LEDs. Between turning the lights ON and OFF, a delay loop must be inserted. In this delay loop, the CPU is made to count down from a specific number to zero. This counting process inhibits the CPU from executing the rest of the program, thereby causing the required delay. Writing in assembly When we write short routines for practicing or various testing, we may write them with the help of the debugger. When we are interested in writing a program which we wish to store in an orderly fashion and which we may wish to update easily, we need to do it in a different way. The software should be written in the microprocessor's assembly language (it may be written also in a high level language, but we will not discuss it in this book). The assembly language contains, in addition to the mnemonic instructions, the use of labels, symbols, directives and remarks. The labels are used as names for the lines; the symbols are used as names for variables; the directives are special instructions which appear as part of the program and are used by the program that translates it to machine language. The directives enable to perform changes in the program easily and turn the program into a general program. The remarks are used by the programmer and the person reading the program for understanding the program. This makes the program written in assembly language quite flexible and easy to read and understand. EB-3191 – Introduction to microprocessors and microcontrollers 71 An assembly program is written as a text using a screen editor. This text is called a Source program. After the source program is written and stored in the CD, we operate an assembler program on it. The assembler program reads the source program, line after line, and translates it into machine language. The process of translating usually requires a two pass assembler. In the first pass, the assembler's software forms a table with values for all labels, symbols and variables. In the second pass, it forms the program in machine language, containing the values of the table. The labels are used as names for the lines to which the program is branching and the symbols are used as names for different variables and parameters. The assembler calculates the addresses and plants them at the right places. The following program is a source program in assembly that transfers the switches to the LEDs in an infinite loop. IOPORT EQU ORG SWLD: MOV SWLD1: MOVX MOVX SJMP END 0FF00H 2100H DPTR,#IOPORT A,@DPTR @DPTR,A SWLD1 The rule of distinction between a number and a symbol is: Every number will start with a digit and every label or symbol will start with a letter. To a number, which starts with a letter, we add 0 at the beginning. The letter H at the end of the number indicates that it is a hexadecimal number. In the above program we used three assembler directives: EQU, ORG and END. Directives are also called pseudo operations. They appear in the source program similar to the microprocessor instructions, but do not belong to the microprocessor's instructions set. They guide the assembler in decoding the source program and translating it to machine language. EB-3191 – Introduction to microprocessors and microcontrollers 72 EQU (EQUal) – Defining a symbol for a numeric value: This directive assigns a fixed numeric value to the symbol. It enables the use of symbols in the program instead of fixed numeric values. For example: PORTA EQU 3401H In the program, we will use only the symbol (in our example PORTA) and not the numeric value. If we wish to change the value of PORTA, we need only to change the directive and the assembler will make the change wherever the symbol PORTA appears. The following phrase can also be used: PORTB EQU PORT1+1 ORG – ORiGin directive: This directive is accompanied by an address. It indicates to the assembler at which start address to locate the program section which follows. The translated bytes will be placed at consecutive addresses from this address. A number of origin instructions may appear in one program. For example: ORG 0100H . Program section 1 . . ORG 300H . Program section 2 . . The assembler knows the position of each instruction in relation to the relevant ORG directive, and calculates its address accordingly. In this fashion, it knows the address of every label, and knows how to calculate offset branching. EB-3191 – Introduction to microprocessors and microcontrollers 73 The assembler creates one program from two program’s sections. The assembler builds the destination program in a special format called HEX format. This format enables the file to be transmitted via communication from one compute to another. The receiving computer knows where to place the different sections of the program. DB – Define Byte: This directive defines a value for a byte in the destination program. When the assembler goes over the program, it advances a counter which points to the address in the program. When it reaches this directive, it places the bytes written in the directive in the address at the counter (or in the addresses which comes after this address). The labels attached to the directives or the mnemonic automatically receive the counter's value. Examples: a) Place 50H at address: b) Place the ASCII codes of: DB 50H TITLE: DB 'ABC' The labels are written in addresses starting from the counter's address. DW – Define Word: This directive is accompanied with a two numbers byte (a word). In other words, it places the two bytes word at the address indicated by the program's counter and the one following it. Examples: a) b) STRADR: DW 5F00H LSTADR: DW 5F02H FROM: DW STRADR EB-3191 – Introduction to microprocessors and microcontrollers 74 DS – Data Storage: This directive enables allocating cells for variables or strings. This directive is used for the RAM areas. The label attached to this directive gets the address of the first cell. For examples: ORG START: DS LAST: DS VALUE: DS DEST: 2 3000H 2 2 1 The number written in the directive indicates the number of allocated cells. The labels in the example will receive the following values: START: LAST: VALUE: DEST: 3000H 3002H 3004H 3005H END – End of program directive: This directive indicates the assembler that this is the end of the source program. This directive is vital for the assembler, which performs two passes over the source program. When the END directive is reached, the second pass begins. A program, which was created in machine language, is called an Object Program. Different assemblers form object programs in slightly different forms, according to their loading programs. We must remember that the object program is destined to be loaded into the system's memory, where it should run. We shall refer to the SES51C software package. EB-3191 – Introduction to microprocessors and microcontrollers 75 When we write a source program using the SES51C software, it is mandatory that the source program name will have the extension .A51. For example: SWLD.A51 When we operate the assembler (included in this software), it translates it and forms an object program, which receives the name of the source program with the extension .HEX. For example, for the SWLD.A51 file we will get a SWLD.HEX file. Besides the object program, the assembler also forms a symbol file with the extension .SYM. For example: SWLD.SYM The assembler also forms another file called a LIST file, which is comprised from the source program and the object program. This file gets the extension .LST. For example: SWLD.LST If there are errors in the program, the assembler will put them in a special file with the extension .ERR. For example: SWLD.ERR In the following steps, we will exercise all the complete stages of software developing in assembly. EB-3191 – Introduction to microprocessors and microcontrollers 76 Procedure: Step 1: Connect the EB-3000 to the power supply. Step 2: Connect the power supply to the Mains. Step 3: Turn ON the trainer. The DVM screen should appear on the display. Step 4: Plug the EB-3191 into the EB-3000. Step 5: Observe the display and check that the experiment board name appear and no fault is detected. Step 6: Connect the EB-3000 to the PC with the USB cable. Step 7: Run the SES51C software by double clicking on SES51C icon on the desktop. Step 8: Check that the VP/EA switch is at VP position. Step 9: Press <RST> on the EB-3191. Writing in assembly Step 10: Select the FILE main function and the NEW sub-function. An UNTITLED window will be opened under full screen editor. The screen editor is our word processor for writing our source program. Step 11: Type the following program: WARM EQU IOPORT EQU ORG SWLD: MOV SWLD1: MOVX MOVX LCALL END 0103H 0FF00H 2100H DPTR,#IOPORT A,@DPTR @DPTR,A WARM Use the <Tab> key to move from one column to another. EB-3191 – Introduction to microprocessors and microcontrollers 77 Do not forget the END directive at the end of the program. After the END directive press <ENTER>. Note: Every label should be located at the beginning of the line (without any space before it). Every instruction should be written after one space character. Step 12: After typing all the program play a little with the editor's functions in order to get acquainted with them. First observe the sub-function of the EDIT and SEARCH main functions. Step 13: EDIT functions: The screen editor has an invisible area in the background called clipboard. We can cut or copy a section of the program into the clipboard. To mark a section before cutting or copying it, bring the cursor to the first character of the desired section. Press the <Shift> key and hold it pressed down, while you move the cursor (with the arrows keys, End, PgUp, PgDn or Home) to the end of the section. The section will be highlighted. To copy the highlighted section from the screen editor window to the clipboard, select the COPY sub-function or press <Ctrl + C>. For cutting the highlighted section from the screen editor window to the clipboard, select the CUT sub-function or press <Ctrl + X>. The highlighted section will disappear from the screen and will be saved in the background. When a section was copied to the clipboard, we can paste it anywhere in the text in the editor window. EB-3191 – Introduction to microprocessors and microcontrollers 78 Move the cursor to the place were you want to add the copied section and select the PASTE sub-function or press <Ctrl + V>. The contents of the clipboard will be copied and added to the text. The contents of the clipboard will not change. Copying or cutting another section to the clipboard will replace the old section in it. In order to delete an error, we use the UNDO sub-function or <Ctrl + Z>. Step 14: SEARCH functions: To find a string in the text we use the SEARCH main function and the FIND sub-function. Select this functions and a data entry window is opened asking for a string to search. Enter any string appearing in the program (usually we type a label, a symbol or a directive) and press <ENTER>. The editor will search for the string from the cursor position and downward. If the string is found it will be highlighted and the editor will put the cursor at the end of the string. To search the same string once again, you can select the SEARCH AGAIN sub-function or press F3. To replace a string with another one, we use the REPLACE subfunction. This function opens a window with two data entry fields. The first one asks for a string to find and the second one asks for the replacement string. Moving from one field to another is done by the <Tab> or <Shift Tab> keys. Before replacing, the editor highlights the string to be replaced and asks for confirmation. To perform another replacing you can also Select the SEARCH AGAIN sub-function or press F3. EB-3191 – Introduction to microprocessors and microcontrollers 79 Step 15: Check that after all the playing you did with the various functions, the program text is still the same as in step 2. Step 16: In order to translate the program to machine language, and create an object program, we operate a translation program called assembler on the file. The assembler can work only on a CD file, so we have to first save the file on a CD. Select the FILE main function and the SAVE AS sub-function. Write the name: SWLD.A51 The text on the screen will be saved in a CD under this name. Step 17: Select the OPTIONS main function and the COMPILER OPTIONS sub-function. Check that the Assembler Compiler is marked. The SAVE CONFIGURATION sub-function also saves these definitions. Step 18: Select the COMPILE main function and the COMPILE subfunction. The assembler will compile (translate) the SWLD.A51 file and will create a HEX file. It will also create a SYM file and a LST file. The assembler indicates errors if it finds them. Step 19: If errors are found, they will be saved in a file called SWLD.ERR. Select the VIEW main function and the ERROR MESSAGES subfunction. A new window will display the error messages file SWLD.ERR. EB-3191 – Introduction to microprocessors and microcontrollers 80 Close the error messages window by keying the X on the top corner of the window. Note: The assembler works only on the file stored in the CD. A command for saving the file is given before performing the compilation. Step 20: In order to download a program to the trainer, it should be in ASCII code. The created HEX file is an ASCII file (see section 3.2). Check that the EB-3000 is connected to the PC COM (communication) port. Press <RST> on the EB-3191. Step 21: Select the COMPILE main function and the DOWNLOAD AND PROGRAM sub-function. The file will be sent to the trainer and it will be placed according to its ORG. Step 22: Check that the debugger windows are opened and select the DEBUG main function and the PROGRAM RESET sub-function. After updating the windows, the program you have written will be found in the disassembly window (written in machine language). Step 23: The source program in the editor can be compared with the program's disassembly in the trainer. Step 24: Set a certain number in the switches. Step 25: Select the DEBUG main function and the RUN sub-function and run the program starting at address 2100H. Step 26: Check and compare the switches with the LEDs. EB-3191 – Introduction to microprocessors and microcontrollers 81 Breakpoints and single step Very often the program we have written does not work straight away. We need to be able to monitor the program as it runs in order to locate errors. To do this we run the program up to a certain point and check the registers' status. This stopping point is called a breakpoint. From this point, we may continue the program execution to a further breakpoint, or we might choose to continue execution step-by-step. Step 1: Select the FILE main function and the OPEN sub-function. A window will be opened with all the .A51 files. Click over the SWLD.A51 file and click over <OK>. An editor window will be opened with the source file SWLD.A51 in it. Step 2: Change the program (add the highlighted line) to the following program: WARM EQU IOPORT EQU ORG SWLD: MOV SWLD1: MOVX ADD MOVX LCALL END Step 3: 0103H 0FF00H 2100H DPTR,#IOPORT A,@DPTR A,#5 @DPTR,A WARM Select the COMPILE main function and the COMPILE sub-function or press <Alt + F9>. If errors are found, correct them in the source file, save the file and compile it again. EB-3191 – Introduction to microprocessors and microcontrollers 82 Step 4: Select the COMPILE main function and the DOWNLOAD AND PROGRAM sub-function or press <Alt + F7> to download the program to EB-3191. Step 5: Make sure that the Debugger, the Registers, the Disassembly and the Program windows are open. Step 6: Select the DEBUG main function and the PROGRAM RESET subfunction. The debugger screen will be updated and will display the downloaded program in the disassembly field. Compare this program with the source program. Step 7: Set the number 0F on the switches. Step 8: Check if the PC (Program Counter) register contains the number 2100. If not, perform PROGRAM RESET. Step 9: Select the DEBUG main function and the TRACE INTO subfunction. This function performs a single step. The CPU performs the instruction written at address 2100 and stops at address 2103. The DPTR gets the value FF00. The PC points to address 2103. Step 10: Select again the TRACE INTO sub-function or press <F7>. The PC advances to address 2104 and the accumulator A receives the value 0F. Step 11: Press <F7< again. The PC advances to address 2106 and the accumulator A receives the value 14 (0F + 5). EB-3191 – Introduction to microprocessors and microcontrollers 83 Step 12: Press <F7< again. The PC advances to address 2107. The number 14 appears on the LEDs. Step 13: Select the DEBUG main function and the PROGRAM RESET subfunction. Step 14: We can plant a breakpoint in the program. In the disassembly field move the cursor to line 2107. Step 15: Select the DEBUG main function and the TOGGLE BREAKPOINT sub-function or press <Ctrl + F8>. The '*' character appears on the left side of the line. Step 16: Set the number 04 on the switches. Step 17: Run the program using the DEBUG main function and the RUN sub-function or press <Ctrl + F9>. Write the start address 2100 in the opened window and press <OK>. The CPU runs the program starting at address 2100 and stops at address 2107 (the breakpoint). Step 18: The breakpoint can be removed and the PC can be returned to the initial state using the DEBUG main function and the PROGRAM RESET sub-function or <Ctrl + F2>. This instruction also updates the disassembly field according to the PC. EB-3191 – Introduction to microprocessors and microcontrollers 84 Step 19: In the disassembly field, move the cursor again to address 2107. Select the DEBUG main function and the GOTO CURSOR subfunction or press <F4>. The CPU runs starting at the PC address (2100) and stops at the address the cursor points to (2107). Step 20: The running start address can be changed and a different starting address can be defined to be used as default. Select the OPTIONS main function and the VIEW DEBUG START ADDRESS sub-function. Write another address in the opened window. Press <Ctrl + F2> to perform PROGRAM RESET and observe the received screen. Step 21: There is another single step instruction called STEP OVER. The STEP OVER (<F8>) instruction is useful when the program stops at a calling for a subroutine instruction. <F8> plants a breakpoint after the subroutine call, thus the program will perform the subroutine and stops afterwards. The TRACE INTO (<F7>) instruction brings us into the subroutine and stops there. EB-3191 – Introduction to microprocessors and microcontrollers 85 Subroutine We will write a program that causes the LEDs to flash in an infinite loop. After the LEDs have been switched OFF, we will need to put an additional delay loop into effect, and then jump to the beginning of the program in order to again turn ON the LEDs. In order to avoid writing the delay loop again, this part of the program can be written as a separate program. This program is called a SUBROUTINE, and it end with the instruction RET (RETurn). When you wish to perform a dealy in the main program, a subroutine is called, using the instruction LCALL. This instruction is similar to the instruction LJMP, with one main difference: the CPU remembers from which address it branched off. Upon meeting the instruction RET at the end of the subroutine, the CPU returns to this address, continues the main program from the address immediately after that from which it branched off. Since you've had some practice by now, we'll write the instructions in a slightly different, shortened and accepted form. Step 1: Select the FILE main function and the NEW sub-function. Step 2: Write the following program. Use the <Tab> key to move from one column to another. EB-3191 – Introduction to microprocessors and microcontrollers 86 Take care that every label starts at the beginning of the line. PLED EQU ORG BLINK: MOV BLINK1: MOV MOVX LCALL MOV MOVX LCALL SJMP ; DEALY: MOV LOOP1: MOV LOOP2: DJNZ DJNZ RET END 0FF00H 2100H DPTR,#PLED A,#0FFH @DPTR,A DEALY A,#0 @DPTR,A DELAY BLINK1 R2,#0FFH R1,#0FFH R1,LOOP2 R2,LOOP1 Step 3: Use the FILE main function and the SAVE AS sub-function to save the program under the name BLINK.A51. Step 4: Press <Alt + F9> to compile (translate) the program. Note that the compilation operation is done only on a file saved on a diskette (or CD). The assembler creates an object file in the HEX format, a SYM file and a LST file. Step 5: If the assemble detects errors, view them using the VIEW function. Correct the errors according to the source program. Save the corrected program and operate the compiler again. Step 6: Download the program to DSM-2095 using <Alt + F10>. Step 7: Press <Ctrl + F2> for PROGRAM RESET. EB-3191 – Introduction to microprocessors and microcontrollers 87 Step 8: Run the program by pressing <Ctrl + F9>. The LEDs should flash at a rate of about half a second between flashes. Step 9: Press <RST>. Step 10: Press <Ctrl + F2> for PROGRAM RESET. Move the cursor to the line, which calls the delay subroutine (the instruction LCALL) in the disassembly field (2106). Step 11: Press <F4> in order to carry out the GOTO CURSOR function. The CPU will execute the program, will stop at the line’s address and will update the registers accordingly. Step 12: If we press <F7> for performing the TRACE INTO function, the CPU will execute one instruction and will stop at the first command of the delay subroutine. If we press <F8> for performing the STEP OVER function, the CPU plants a breakpoint at the following address of the instruction which comes after the instruction that calls the subroutine. The CPU will executes the program, carries out the subroutine and stops at the breakpoint. Press <F8> and observe the system's reaction. Step 13: Press <Ctrl + F2> for PROGRAM RESET. Step 14: Change the program so that the LEDs flash at a higher frequency. Step 15: Change the program so that the LEDs will blink (once the four right LEDs and once the four left LEDs). EB-3191 – Introduction to microprocessors and microcontrollers 88 Embedded micro-controller system The idea behind developing an embedded micro-controller is to achieve a micro-computer card that operates independently, and does not need a PC and monitor software. The software is burned in its ROM and does not erase when the card's power is turned OFF. Connecting the card to a voltage activates the CPU according to the program burned in its ROM. The EB-3191 card includes a ROM component called EEPROM. The meaning of this name is: Electrical Erasable programmable Read Only Memory (a ROM which can be programmed and erased electrically). When the 8051 is activated or the RST pushbutton is pressed, the 8051 turns to address 0000 and starts to perform the instruction it finds from this address and forwards. An addressing instruction to the main program is usually written in this address. The card includes a VP/EA switch. When the switch is in the VP position, the card's monitor program starts at address 0000 and the memory for the user's programs starts at address 2000H. Pressing the RST causes the processor to turn to the monitor program and it uses this program to respond to the instructions coming from the computer. When the switch is in the EA position, the processor does not refer to the monitor program and it finds the user's program at addresses 0000 and 2000H. Activating the card or after pressing RST, the processor turns to address 0000. At this address, it finds the cell's contents 2000 (when the VP/EA switch is at the EA position). At this address it finds the jump to the main program instruction. EB-3191 – Introduction to microprocessors and microcontrollers 89 Step 1: Change the blinking program (BLINK.A51) to the following program: PORTA EQU ORG LJMP ORG BLINK: MOV MOV MOVX LCALL MOV MOVX LCALL SJMP DELAY: MOV DELAY2: MOV DELAY3: DJNZ DJNZ RET END 0FF00H 2000H BLINK 2100H DPTR,#PORTA A,#0FFH @DPTR,A DELAY A,#00 @DPTR,A DELAY BLINK R7,#0FFH R6,#0FFH R6,DELAY3 R7,DELAY2 Step 2: Use the COMPILE instruction to translate the program to machine language. Step 3: use the DOWNLOAD AND PROGRAM instruction to download the program. Step 4: Run the program starting at address 2000. The LEDs should blink. Step 5: Press <RST>. The LEDs should stop blinking. Step 6: Set the VP/EV switch to EA position. It means that the CPU ignores the program of its internal ROM and will turn to an external memory. Step 7: Press <RST>. The LEDs should blink. EB-3191 – Introduction to microprocessors and microcontrollers 90 Step 8: Disconnect the card from the voltage. Step 9: Connect the card to the voltage. Step 10: The LEDs should blink. If not, press <RST>. The program is not erased upon disconnecting the card from the voltage. EB-3191 – Introduction to microprocessors and microcontrollers 91 Summary In this chapter, our practice has covered the subjects: a) Studying all the debugger functions. This tool is used for dealing with memory cells, writing programs, downloading programs to the memory and executing them with or without breakpoints or single step. b) Studying the SES51C software functions for developing in assembly language, which include a screen editor, assembler and a full screen debugger. We have learned to write a source program, translate it to machine language, download it to the trainer and run it while using the debugger functions. c) Studying some of the 8051's basic instructions and functions to understand terms such as: machine language, source program, object program, assembly language, disassembly, registers, I/O units, subroutines, branching and more. All the 8051 instruction set appears at appendix A. You can find a more detailed description of the 8051 in the text book: "Principles of Microcontrollers with the 8051". EB-3191 – Introduction to microprocessors and microcontrollers 92 The exercise programs location The EB-3191 card, which operates independently, includes monitor software burned inside its 8051 component. This software occupies the 0000-1FFF addresses range. The EB-3191 has an EEPROM (A Read Only Memory (ROM) which can be programmed and erased electrically), which occupies the 0000-1FFF and also the 2000-3FFF addresses range. Thanks to the double mapping (a memory area that occupies a number of addresses ranges), we can write our program starting at address 2000H and also run them from address 2000H as well as address 0000 when the VP/EA switch is at the EA position. Ending a program In order to run a program we use a mapping program called debugger. The 8051 does not have any stopping instruction. In order to enable the running of a program and to return the system to the debugger software, a special routine called WARM has been written in the card's monitor. This stopping operation is called "warm stopping" because it keeps the registers' status as opposed to the RESET instruction that does not keep anything and zeroes (resets) some of the registers. To end the program running, we use the LCALL WARM instruction. This routine returns the CPU to the debugger while saving the registers' status. If you use the EB-319, the WARM routine address is 0103. EB-3191 – Introduction to microprocessors and microcontrollers 93 Summary questions: 1. What does the following program execute? 2100 74 66 MOV A,#66 2102 90 FF 00 MOV DPTR,#FF00 2103 F0 MOVX @DPTR,A (a) (b) (c) (d) 2. Writes the number 74 in cell FF00. Writes the number 66 in cell FF00. Reads the number 66 from cell FF00. Reads a number from cell FF00. What does the following program execute? PLED EQU ORG BLINK: MOV BLINK1: MOV MOVX LCALL MOV MOVX LCALL SJMP ; DEALY: MOV LOOP1: MOV LOOP2: DJNZ DJNZ RET END (a) (b) (c) (d) 0FF00H 2100H DPTR,#PLED A,#0FFH @DPTR,A DEALY A,#0 @DPTR,A DELAY BLINK1 R2,#0FFH R1,#0FFH R1,LOOP2 R2,LOOP1 Writes the contents of the input port in the output port. Writes the number FF in the output port. Turns the LEDs On and OFF without delay. Turns the LEDs On and OFF with delay. EB-3191 – Introduction to microprocessors and microcontrollers 94 Chapter 5 – The 8051's Structure, Instructions and Exercises In order to take full advantage of the 8051's instruction set we must better acquainted with certain internal parts of the 8051. Section 6.1 will cover the internal direct RAM and the Special function Registers. Section 6.2 will cover interrupts and other functions. More details about the interrupts, the Timer/Counter and the Serial communication with the UART (Universal Asynchronous Receiver Transmitter) can be found in the relevant exercises 5.10.5, 5.10.8 and 5.10.7. EB-3191 – Introduction to microprocessors and microcontrollers 95 5.1 Structure of the internal direct RAM As pointed out in chapter 1, the internal RAM has 256 bytes, divided into two parts. One part, called the INTERNAL DATA RAM includes bytes 00 to 7F. The second part is called SPECIAL FUNCTION REGISTERS. We will expand on these parts. The internal data RAM area is composed of six parts as in figure 5-1: RAM (MSB) Region 6 – for storage of data in a usual manner Region 5 - for bit addressing Region 4 - BANK3 of R0-R7 30H 2FH 2EH 2DH 2CH 2BH 2AH 29H 28H 27H 26H 25H 24H 23H 22H 21H 20H 1FH 127 7F 77 6F 67 5F 57 4F 47 3F 37 2F 27 1F 17 0F 07 7E 76 6E 66 5E 56 4E 46 3E 36 2E 26 1E 16 0E 06 7D 75 6D 65 5D 55 4D 45 3D 35 2D 25 1D 15 0D 05 7C 74 6C 64 5C 54 4C 44 3C 34 2C 24 1C 14 0C 04 7B 73 6B 63 5B 53 4B 43 3B 33 2B 23 1B 13 0B 03 7A 72 6A 62 5A 52 4A 42 3A 32 2A 22 1A 12 0A 02 79 71 69 61 59 51 49 41 39 31 29 21 19 11 09 01 78 70 68 60 58 50 48 40 38 30 28 20 18 10 08 00 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 Bank 3 18H 17H 24 23 Bank 2 Region 3 - BANK2 of R0-R7 Region 2 - BANK1 of R0-R7 (LSB) 7FH 10H 0FH 16 15 Bank 1 08H 07H Region 1 - BANK0 of R0-R7 8 7 Bank 0 00H Figure 5-1 Layout of the internal RAM EB-3191 – Introduction to microprocessors and microcontrollers 6 96 Regions 1 to 4 each have 8 bytes. They enable us to use various bytes as registers R0-R7. The choice regarding which BANK of R0-R7 is in use is made by means of the Program Status Word (one of the special registers), which was outlined in chapter 4. Choice of the register bank is made by defining the contents of bits RS0 and RS1 in the PSW register. This interesting division enables branching off to a subroutine without disturbing the contents of the registers. In the subroutine we will continue using the R0-R7 commands but the contents of these registers will be in another bank of bytes. For instance, there is no need to store the registers or to be assisted by the subroutine in order to leave the registers' contents untouched. All that needs to be done on entering a subroutine is to change RS0 and RS1 so that they will point to another BANK. Then all of the registers R0 to R7 are used. Before returning from the subroutine, RS0 and RS1 of the status register are returned to their previous status. 0,0 in RS0,RS1 allocates the registers to BANK0 (bytes 00H-07H). 0,1 in RS0,RS1 allocates the registers to BANK1 (bytes 08H-0FH). 1,0 in RS0,RS1 allocates the registers to BANK2 (bytes 10H-17H). 1,1 in RS0,RS1 allocates the registers to BANK3 (bytes 18H-1FH). Region 5: The bits in this RAM area can be dealt with in one of two ways: a) By direct addressing to bytes 20H to 2FH. b) By means of instructions in bit-addressing. In this special type of instruction, each bit is addressed directly, where each bit has its own 8bit address as described in figure 6-1. The CPU knows if the instruction refers to a byte or to a bit. For example, the instruction: D2 0F SETB 0F Will raise the MSB of the cell at address 21H to '1'. All in all, region 5 has 128 bits that can be controlled in this manner. EB-3191 – Introduction to microprocessors and microcontrollers 97 Region 6: Is an ordinary direct RAM region of 80 bytes, running from 30H to 7FH. The second part of the internal direct RAM (SPECIAL FUNCTION REGISTERS area) has bytes that are actually special registers. The accumulator and the DPTR are among these registers and they have special instructions that deal directly with them. To the other registers we refer by direct addressing, as with the DATA RAM in the first part of the RAM. The fact that each of these registers has its own function, makes them distinctive. The registers are fixed in a slightly unusual order; therefore they have been described according to their functions as opposed to their addresses. Full Name Accumulator B register Program status word (status register) Stack pointer Data pointer high byte Data pointer low byte Port 0 Port 1 Port 2 Port 3 Interrupt priority control Interrupt enable control Timer/counter mode control Timer/counter control Timer/counter 0 high byte Timer/counter 0 low byte Timer/counter 1 high byte Timer/counter 1 low byte Serial control Serial data buffer Power control Mnemonic *ACC *B *PSW SP DPH DPL *PO *P1 *P2 *P3 *IP *IE TMOD TCON TH0 TL0 TH1 TL1 *SCON SBUF PCON Address E0H F0H D0H 81H 83H 82H 80H 90H A0H B0H B8H A8H 89H C8H 8CH BAH 8DH 8BH 98H 99H 97H There are two additional bytes, PCH and PCL (the Program Counter bytes) but we cannot address them. As you can see in this table, not all 128 bytes of this RAM (only 23 bytes) are used. The user does not have access to unused bytes. They are reserved by INTEL for future development of the 8051. This explains the philosophy behind the 8051 component. EB-3191 – Introduction to microprocessors and microcontrollers 98 The 8051 is not a single kind of microcontroller, but it forms the kernel of an entire family of microcontrollers. These controllers are all identical in their instruction set, and in their basic structure. They differ only in one aspect - the set of the Special Function Registers (SFR). These registers serve for those functions of the 8051, which are outside the bounds of the ordinary functions of a microprocessor. The 8051's four direct ports, for example, are four SFR's of the 8051. When the 8051 was originally developed, a 128 byte SFR space was allocated. The basic 8051 actually contains 23 SFR's (including the program counter PC). The rest of the space was left free for future applications. As these registers are accessed directly by addressing them, there is no need to change the processor's instruction set, and so the variations in development tools for 8051 embedded systems are minor. Today the 8051 is the largest family of controllers in the world and is constantly growing, including components with additional ports: ADC's, communications ports, additional timers and counters, and many more variations. In all of these variations the basic 8051 structure is still maintained. In appendix A you can find a section from the Phillips data book, which describes some of the 8051 family microcontrollers manufactured by Phillips. These components are intended for machines, instrumentation, avionics, automation, autotronics and many other applications. The 8051 chip has a larger number of sub-manufacturers than any other microprocessor or microcontroller. EB-3191 – Introduction to microprocessors and microcontrollers 99 All of the registers marked with an asterisk in the previous list have bits, which can be addressed by means of bit-addressing, as shown in figure 5-2. Direct Byte Address (LSB) Hardware Register Symbol Bit Address (MSB) 240 F7 F6 F5 F4 F3 F2 F1 F0 B 224 E7 E6 E5 E4 E3 E2 E1 E0 ACC 208 CY D7 AC D6 F0 D5 RS1 D4 RS0 D3 0V D2 D1 P D0 PSW 200 TF2 CF EXF2 CE RCLK CD TCLK CC EXEN2 CB TR2 CA CT/ T 2 C9 CP/ RL 2 C8 184 - - PT2 BD PS BC PT1 BB PX1 BA PT0 B9 PX0 B8 IP 176 B7 B6 B5 B4 B3 B2 B1 B0 P3 168 EA AF - ET2 AD ES AC ET1 AB EX1 AA ET0 A9 EX0 A8 IE 160 A7 A6 A5 A4 A3 A2 A1 A0 P2 152 SM0 9F SM1 9E SM2 9D REN 9C TB8 9B RB8 9A TI 99 RI 98 SCON 144 97 96 95 94 93 92 91 90 P1 136 TF1 8F TR1 8E TF0 8D TR0 8C IE1 8B IT1 8A IE0 89 IT0 88 TCON 128 87 86 85 84 83 82 81 80 P0 Figure 5-2 Special Function Registers EB-3191 – Introduction to microprocessors and microcontrollers T2CON 100 We'll briefly describe the various registers: ACC: The ACCumulator. This is the most active register in the microprocessor. B: B register. Mainly used for multiplication and division. PSW: Program Status Word. Described in detail in chapter 4. Its bits serve as flags and for switching of the various banks of registers R0-R7. SP: Stack Pointer. We shall explain its function when we talk about instructions relating to subroutines. DPTR: Data PoinTeR. Used for indirect addressing to 16-bit addresses. Composed of two bytes: DPH and DPL. P0-03: Ports. Joined to 32 lines leaving the CPU. Each bit's contents pass through a buffer (driver) to the outgoing line. EB-3191 – Introduction to microprocessors and microcontrollers 101 Each port is composed of 8 bit latch and 8 bit buffer constructed as the following: Data to the port CPU pins Latch Data from the port Figure 5-3 Writing of a number on a port (by either direct or bit-addressing) results in a number appearing on the output line. Note: The electrical signal representing logic '0' dominates a signal representing logic '1' if both appear simultaneously on the same line. For this reason, if logic '0' has been written on one of the bits of one of these ports, it will not be possible for the port to accurately read incoming information. Bearing this in mind it is clear that if we intend to use a port or part of it as an input port, we must ensure that '1' has been written on all the lines of the port's output buffer prior to reading incoming data through this port. EB-3191 – Introduction to microprocessors and microcontrollers 102 A glance at the initialization value table printed will show you that the initial value given this port is FF, in order to enable them to be used as input ports without further initialization by the programmer. The lines of ports 0, 2 and 3 serve also as lines of the address, data and control BUSSES when external memories are connected to the 8051. There is a special line which signals to the CPU whether it is connected to external memories or not. As mentioned previously the 8051 has an internal ROM, so if no RAM is required in addition to the internal RAM, a microcomputer having only one component can be built, in which case the link with the external environment is made by means of the ports. IP,IE: Interrupt Priority control, Interrupt Enable control. We will elaborate on these when we discuss INTERRUPTS and their uses in section 6.2 and 6.10.14. TMOD/TCON: The control over the timers and the mode in which they are used. The 8051 has two timers that can be used also as counters. Each timer is composed of two bytes TH and TL. Exercises later on in the chapter will clarify the timer/counter's functions and its mode of use. TH0/TL0 - TH1/TL1: These are the timer/counter's bytes. SCON: Control of serial communications. The 8051 has two lines which allow for reception and transmission, bit by bit. SCON serves as the communication control. The means by which we are able to use serial transmission and reception will be described later in this chapter. SBUF: Serial data buffer. This is used to store data transmitted in series. EB-3191 – Introduction to microprocessors and microcontrollers 103 PCON: Power Control. Some of this register's bits enable switching of the CPU and disconnection of it from the clock system, even to the point of stopping its functioning. This switching is done by means of software. Stopping the CPU is done in order to reduce current consumption, which is important in systems with batteries. When the CPU runs, it consumes large amount of current, even in delay loops. There are two main halt modes WAIT and STOP. At WAIT mode, the CPU remember the registers’ contents and getting out this mode is done by interrupt request. At STOP mode, the CPU is almost completely switched off and the current consumption is almost zero. Getting out this mode is done by RESET request. At that case, the CPU does not keep the registers’ contents. In systems that use these modes of operation, the hardware design should include ‘wake-up’ system. Following are the values attributed to special registers upon initialization of the CPU: Register PC B SP P0-P3 IE TCON TL TL1 SBUF ACC PSW DPTR IP TMOD TH TH1 SCON PCON Contents 0000H 00H 07H FFH 0x000000B 00H 000H 00H undefined 00H 00H 0000H xx000000B 00H 000H 00H 00H 0xxx0000B EB-3191 – Introduction to microprocessors and microcontrollers 104 Initializing the CPU can be done in two ways: a) By connecting it to a power source. b) By means of an input line called RST (RESET). Connection of this line to the VCC initializes the CPU. Note that only ports are given the initial value FF (as explained before). 5.2 Interrupts and stack We have come across registers connected with interrupts among the special registers. An interrupt is a state in which the CPU is requested to leave the program it is presently executing and to move to another program. This program is called an interrupt program. There are a number of ways to request an interrupt. An EXTERNAL INTERRUPT occurs when systems external to the CPU are joined to 2 lines leading out of the CPU. These lines request the CPU to perform an interrupt. A second way is by means of one of the two timers. As soon as they have reached a predetermined number, they request an interrupt. A third way is by means of the serial port within the CPU. This alternative is only relevant when serial communication is in progress. Upon receipt of the request to interrupt, the CPU completes the instruction presently being dealt with. The program counter, which points to the next instructions' address, has its contents stored by the CPU, so that at the end of the interrupt program, execution of the original program can be continued from where it was stopped. After the value in the program counter has been stored, the CPU turns to an area of branch instructions in the monitor program. Each of the various interrupt programs has a fixed address where its branch instructions are located. The CPU loads this address on to the program counter. Continued operation of the CPU refers it to the required interrupt program. This sequence is called an interrupt vector. EB-3191 – Introduction to microprocessors and microcontrollers 105 Following are the locations of the interrupt vectors: External interrupt 0 Timer 0 overflow External interrupt 1 Timer 1 overflow Serial port 0003H 000BH 0013H 001BH 0023H The monitor program writer should make sure that branching instructions directing the CPU to the various interrupt programs are found at these addresses. It should be noted that this area is in the system's ROM. Use of the various interrupts is described in the exercises later on in the chapter. As we have seen, the CPU stores the program counters' contents whenever an interrupt program or subroutine is called. The storing is done in an area of the RAM called STACK, which is located in the internal RAM area. The CPU uses a register called the SP (Stack Pointer) to define the precise location at which to store the program counter's contents. This register, found among the special registers in the internal RAM, indicates the address within the internal RAM at which the contents are to be stored. Before the CPU branches off to a subroutine or interrupt program, it advances the SP by 1. PCL (the low byte of the PC) is then stored at the address indicated by SP. Once again SP is advanced by 1 and this time PCH (the high byte of the PC) gets stored. SP remains pointing to the last data stored in the stack. The reloading of data is done in the opposite order to that of storage, on the basis of Last In First Out. The stack is also used for temporary storage of data, and for this we use the instruction: PUSH direct This instruction pushes the indicated cell's contents into the stack. The stack pointer is advanced by 1 and then the cell's contents are pushed, The SP points to the data last stored in the stack. EB-3191 – Introduction to microprocessors and microcontrollers 106 Retrieval of the data is done by means of: POP direct These instructions are used mainly in subroutines and interrupt routines. Various registers are used in these programs, registers, which may contain information of importance to the main program. Therefore, it should be seen to that they are stored in the stack at the start of a subroutine or interrupt, and that upon completion of the program they can once again be readily restored. Upon initialization of the CPU, SP is given the value 07, which means that data will be pushed into the stack beginning at cell 08. This area is in the BANK1 region of the registers R0-R7. If this is not convenient, SP can be given a different value. Certain interrupt requests can be blocked or masked, or in the case of simultaneous receipt of more than one request, an order of preference can be defined, called interrupt priority. Priority and the blocking (called MASKING) is defined by a number in registers IP and IE. This is explained in detail in exercise 5.10.7. EB-3191 – Introduction to microprocessors and microcontrollers 107 5.3 Effect of instructions on flags Only a small number of instructions affect the flags. The following table shows all of those which do. X means that the flag will be raised or lowered depending on the operation's outcome. 0 means that upon execution of the instruction, the flag will be zeroed. 1 means that the flag will be raised upon execution of the instruction. Instruction CY OV AC ADD x x x ADDC x x x SUBB x x x MUL 0 x DIV 0 x DA x RRC x RLC x SETB C 1 CLR C 0 CPL C x ANL C,BIT x ANL C,/BIT x ORL C,BIT x ORL C,/BIT x MOV C,BIT x CJNE x EB-3191 – Introduction to microprocessors and microcontrollers 108 5.4 Classification of the instructions The 8051 has 255 different instruction codes, almost all the possible combinations of an 8-bit binary number. The instructions may be divided into five groups: a) b) c) d) e) Data transfer instructions. Arithmetic instructions. Logical instructions. Boolean variable manipulation. Program branching. In the listing of each instruction we will relate to the following variables: 5.4.1 Code These are binary numbers expressed in hexadecimal code, which serve as instructions to the CPU. Each instruction relating to registers R0-R7 has eight different codes. These are given the values X8-XF, where X8 goes to R0, X9 to R1 etc. For example: F8-EF MOV A,Rn Means that: E8 = MOV A,R0 E9 = MOV A,R1 And so on... EB-3191 – Introduction to microprocessors and microcontrollers 109 5.4.2 Mnemonic instructions A mnemonic instruction is composed of an operation and an operand. The operation is written as a word of between 2 to 5 letters, usually an abbreviated form of the instruction in normal English. Intel, the developers of the microprocessor, were those who fixed these mnemonics. The operands are separated by a comma. Possible operands are: a) b) c) d) e) f) g) h) i) Rn – registers R0 to R7 in the internal RAM (see section 6.4.1). DIRECT – this operand refers to an 8-bit address in the internal RAM area. It should be kept in mind that part of the internal RAM is a series of special registers described in 6.1. With the exception of the accumulator and DPTR, all of these registers can be reached by direct addressing only. The register's address is stated in the operand. @RO,@R1 – indirect addressing by means of registers R0 and R1. The register contents indicate the required internal address. #DATA – a fixed, 8-bit number found further on in the instruction code. # signifies immediate addressing. #DATA16 – a fixed, 16-bit number, whose 2 bytes are found further on in the instruction code. The higher byte precedes the lower one. # once again signifies immediate addressing. ADDR16 – a 16-bit address, whose 2 bytes are found further on in the instruction code. The higher byte precedes the lower one. ADDR11 – an 11-bit address, explained in the AJMP instruction in the branching instructions group. REL – a signed integer within the range +127 to -128 representing the offset from the present position. BIT – an address within the internal RAM in bit-addressing, in the DATA RAM or special registers area. 5.4.3 Bytes The number of bytes taken up by the instruction, including the operation and the operands. 5.4.4 Cycles The number of machine cycles required to complete the execution of the instruction. Each machine cycle is 12 CPU – clock's cycles long. If the CPU clock's cycle time is known, this data will enable us to calculate the amount of time required to execute any instruction. EB-3191 – Introduction to microprocessors and microcontrollers 110 5.5 Data transfer instructions An indirect byte is a byte in the internal RAM accessed by indirect addressing – a byte indicated by either R0 or R1. Description Code s Mnemonic Byte s Cycle s Move immediate data to A. DATA A. Move direct byte to A. (DIRECT) A. Move indirect byte to A. (R0) A. Move indirect byte to A. (R1) A. Move contents of register to A. Rn A. Move contents of A to register. A Rn. Move immediate data to register. DATA Rn. Move direct byte to register. (DIRECT) Rn. Move contents of A to direct byte. A (DIRECT). Move immediate data to direct byte. DATA (DIRECT). Move direct byte to direct byte. (DIRECT) (DIRECT). Move indirect byte to direct byte. (R0) (DIRECT). Move indirect byte to direct byte. (R1) (DIRECT). Move register's contents to direct byte. Move A's contents to indirect byte. A (R0). Move A's contents to indirect byte. A (R1). Move immediate data to indirect byte. DATA (R0). Move immediate data to indirect byte. DATA (R1). Move direct byte to indirect byte. (DIRECT) (R0). Move direct byte to indirect byte. (DIRECT) (R1). Move immediate 16-bit data to DPTR. DATA16 DPTR. Move byte to A from address DPTR+A in PROGRAM area. (A+DPTR) A. Move byte to A from address PC+A in PROGRAM area. (A+PC) A. Move byte to A from address DPTR in external RAM. (DPTR) A. 74 E5 E6 E7 E8-EF F8-FF 78-7F A8-AF F5 75 MOV MOV MOV MOV MOV MOV MOV MOV MOV MOV A,#DATA A,DIRECT A,@R0 A,@R1 A,Rn Rn,A Rn,#DATA Rn,DIRECT DIRECT,A DIRECT,#DATA 2 2 1 1 1 1 2 2 2 3 1 1 1 1 1 1 1 2 1 2 85 MOV DIRECT,DIRECT 3 2 86 MOV DIRECT,@R0 2 2 87 MOV DIRECT,@R1 2 2 88-8F F6 F7 76 MOV MOV MOV MOV DIRECT,Rn @R0,A @R1,A @R0,#DATA 2 1 1 2 2 1 1 1 77 MOV @R1,#DATA 2 1 A6 MOV @R0,DIRECT 2 2 A7 MOV @R1,DIRECT 2 2 90 MOV DPTR,#DATA16 3 2 93 MOVC A,@A+DPTR 1 2 83 MOVC A,@A+PC 1 2 E0 MOVX A,@DPTR 1 2 EB-3191 – Introduction to microprocessors and microcontrollers 111 Description Move byte to A from address R0 in external RAM 1. (R0) A. Move byte to A from address R1 in external RAM 2. (R1) A. Move A's contents to byte in external RAM2 at address DPTR. A (DPTR). Move A's contents to byte in external RAM2 at address R0. A (R0). Move A's contents to byte in external RAM2 at address R1. A (R1). Exchange contents of A with direct byte. A (DIRECT). Exchange contents of A with indirect byte. A (R0). Exchange contents of A with indirect byte. A (R1). Exchange contents of A with that of register. A R. Exchange 4 bits of LSB in indirect byte with 4 bits of LSB in A. A (R0). Exchange 4 bits of LSB in indirect byte with 4 bits of LSB in A. A (R1). Save direct byte on STACK. SP+1 SP. (DIRECT) (SP). Retrieve a direct byte from STACK. (SP) (DIRECT). SP-1 SP. 1 2 Code s Mnemonic Byte s Cycl es E2 MOVX A,@R0 1 2 E3 MOVX A,@R1 1 2 F0 MOVX @DPTR,A 1 2 F2 MOVX @R0,A 1 2 F3 MOVX @R1,A 1 2 C5 XCH A,DIRECT 1 1 C6 C7 C8-CF D6 XCH XCH XCH XCHD A,@R0 A,@R1 A,Rn A,@R0 1 1 1 1 1 1 1 1 D7 XCHD A,@R1 1 1 C0 PUSH DIRECT 2 2 D0 POP DIRECT 2 2 R0 and R1 are 8-bit registers. In this instruction, an 8-bit address connected with the external RAM is obtained. This instruction is used when the external RAM is small (not more than 256 bytes) in which case the high address lines can be omitted. EB-3191 – Introduction to microprocessors and microcontrollers 112 5.6 Arithmetic operations Description Add immediate data to A. A+DATA A. Add a direct byte to A. A+(DIRECT) A. Add an indirect byte to A. A+(R0) A. Add an indirect byte to A. A+(R1) A. Add register's contents to A. A+Rn A. Add immediate data and CARRY to A. A+DATA+CY A. Add direct byte and CARRY to A. A+(DIRECT)+CY A. Add indirect byte and CARRY to A. A+(R0)+CY A. Add indirect byte and CARRY to A. A+(R1)+CY A. Add registers' contents & CARRY to A. A+Rn+CY A. Subtract immediate data & CARRY from A. A-DATA-CY A. Subtract direct byte & CARRY from A. A-(DIRECT)-CY A. Subtract indirect byte & CARRY from A. A-(R0)-CY A. Subtract indirect byte & CARRY from A. A-(R1)-CY A. Subtract registers' contents & CARRY from A. A-Rn-CY A. Multiply A by B. MSB goes to B and LSB to A. A*B A,B. Divide A by B. The quotient goes to A & the remainder to B. A5B A,B. Increase A by 1. A+1 A. Increase direct byte by 1. (DIRECT)+1 (DIRECT). Increase indirect byte by 1. (R0)+1 (R0). Increase indirect byte by 1. (R1)+1 (R1). Increase register's contents by 1. Rn+1 Rn. Increase DPTR by 1. DPTR+1 DPTR. Decrease A by 1. A-1 A. Decrease direct byte by 1. (DIRECT)-1 (DIRECT). Decrease indirect byte by 1. (R0)-1 (R0). Decrease indirect byte by 1. (R1)-1 (R1). Decrease register's contents by 1. Rn-1 Rn. Convert contents of A to BCD1 code. A BCD. 1 Code s Mnemonic Byte s Cycl es 24 25 26 27 28-2F 34 ADD ADD ADD ADD ADD ADDC A,#DATA A,DIRECT A,@R0 A,@R1 A,Rn A,#DATA 2 2 1 1 1 2 1 1 1 1 1 1 35 ADDC A,DIRECT 2 1 36 ADDC A,@R0 1 1 37 ADDC A,@R1 1 1 38-3F ADDC A,Rn 1 1 94 SUBB A,#DATA 2 1 95 SUBB A,DIRECT 2 1 96 SUBB A,@R0 1 1 97 SUBB A,@R1 1 1 98-9F SUBB A,Rn 1 1 A4 MUL AB 1 4 84 DIV AB 1 4 04 05 INC INC A DIRECT 1 2 1 1 06 07 08-0F A3 14 15 INC INC INC INC DEC DEC @R0 @R1 Rn DPTR A DIRECT 1 1 1 1 1 2 1 1 1 2 1 1 16 17 18-1F D4 DEC DEC DEC DA @R0 @R1 Rn A 1 1 1 1 1 1 1 1 This instruction is effective only if used after the instruction ADD or ADDC. It adjusts the result of the addition of numbers in BCD code. EB-3191 – Introduction to microprocessors and microcontrollers 113 5.7 Logical operations Description Code s Mnemonic Byte Cycle s s AND direct byte with A. (DIRECT) A (DIRECT). AND immediate data with direct byte. (DIRECT) DATA (DIRECT). AND immediate data with A. A DATA A. AND direct byte with A. A (DIRECT) A. AND indirect byte with A. A (R0) A. AND indirect byte with A. A (R1) A. AND register's contents with A. A Rn A. OR A with direct byte. (DIRECT)+A (DIRECT). OR direct byte with immediate data. (DIRECT)+DATA (DIRECT). OR A with immediate data. A+DATA A. OR A with direct byte. A+(DIRECT) A. OR A with indirect byte. A+(R0) A. OR A with indirect byte. A+(R1) A. OR A with register's contents. A+Rn A. XOR A with direct byte. (DIRECT)+A (DIRECT). XOR immediate data with direct byte. (DIRECT)+DATA (DIRECT). XOR immediate data with A. A+DATA A. XOR direct byte with A. A+(DIRECT) A. XOR indirect byte with A. A+(R0) A. XOR indirect byte with A. A+(R1) A. XOR register's contents with A. A+Rn A. Rotate A to the right. 52 ANL DIRECT,A 2 1 53 ANL DIRECT,#DATA 3 2 54 55 56 57 58-5F 42 ANL ANL ANL ANL ANL ORL A,#DATA A,DIRECT A,@R0 A,@R1 A,Rn DIRECT,A 2 2 1 1 1 2 1 1 1 1 2 1 43 ORL DIRECT,#DATA 3 2 44 45 46 47 48-4F 62 ORL ORL ORL ORL ORL XRL A,#DATA A,DIRECT A,@R0 A,@R1 A,Rn DIRECT,A 2 2 1 1 1 2 1 1 1 1 1 1 63 XRL DIRECT,#DATA 3 2 64 65 66 67 68-6F 03 XRL XRL XRL XRL XRL RR A,#DATA A,DIRECT A,@R0 A,@R1 A,Rn A 2 2 1 1 1 1 1 1 1 1 1 1 Rotate A to right through carry. 13 RRC A 1 1 Rotate A to the left. 23 RL A 1 1 Rotate A to left through carry. 33 RLC A 1 1 E4 F4 C4 CLR CPL SWAP A A A 1 1 1 1 1 1 CX CX Zero A. 0 A. Complement A. A' A. Exchange 4 bits of MSB n ACC. with 4 bits of LSB in ACC. (A0-A3) (A4-A7). EB-3191 – Introduction to microprocessors and microcontrollers 114 5.8 Boolean variable manipulation Bit manipulation instructions are instructions that change a bit or react to a specific bit's status. The 8051 has 256 bits which can be addressed directly in this manner. As previously described in section 6.1, each such bit has its own address. These instructions include special instructions that deal with the carry flag bit. Bit manipulation instructions have extraordinary power. In other microprocessors between 2 and 4 instructions are needed in order to fulfill the same function filled by a single bit manipulation instruction performed by the 8051. Description Zero carry flage. 0 C. Zero direct bit. 0 (BIT). Raise carry to 1. 1 C. Raise direct bit to 1. 1 (BIT). Complement the carry flag. C C. Complement the direct bit. (BIT) (BIT). AND direct bit with carry. C * (BIT) C. AND direct bit's complement with carry. C * (BIT) C. OR direct bit with carry. C + (BIT) C. OR direct bit's complement with carry. C + (BIT) C. Move direct bit to carry. (BIT) C. Move carry to direct bit. C (BIT). Jump if direct bit is '1' and zero it. Jump if direct bit is '1' and zero it. Jump if direct bit is '0'. Jump if carry is '1'. Jump if carry is '0'. Code s Mnemonic Byte s Cycle s C3 C2 D3 D2 B3 B2 82 B0 CLR CLR SETB SETB CPL CPL ANL ANL C BIT C BIT C BIT C,BIT C,/BIT 1 2 1 2 1 2 2 2 2 1 1 1 1 1 2 2 72 A0 ORL ORL C,BIT C,/BIT 2 2 2 2 A2 92 10 20 30 40 50 MOV MOV JBC JB JNB JC JNL C,BIT BIT,C BIT,REL BIT,REL BIT,REL REL REL 2 2 3 3 3 2 2 1 2 2 2 2 2 2 EB-3191 – Introduction to microprocessors and microcontrollers 115 5.9 Program branching Two branching instructions have a distinctive characteristic - AJMP and ACALL. In both of these instructions, part of the address to which we wish to branch is hidden in the instruction code. The instruction AJMP (Absolute JuMP) occupies two bytes and is of the following form: OPCODE A10,A9,A8 00001 DATA A7,A3,A5,A4 A3,A2,A1,A0 In execution of the instruction, the PC indicates the next consecutive instruction. The given instruction changes the 11 lowest bits of the PC. This instruction enables a jump within a block of 2K in which the PC is situated, which is limited by the 5 MSB's of the address in the PC. The instruction ACALL (Absolute CALL) also ocupies 2 bytes and is of the following form: OPCODE A10,A9,A8 00001 DATA A7,A3,A5,A4 A3,A2,A1,A0 Here too the PC indicates at the next in line instruction's address at the time it executes the present instruction. This address is pushed into the STACK to enable us to return to the main program. Thereafter, the registered address changes the 11 lowest bits of the PC. EB-3191 – Introduction to microprocessors and microcontrollers 116 Description Call subroutine with absolute address. Call distant subroutine. Return from subroutine. Return from interrupt. Jump with absolute address. Long jump. Short jump by offset. Jump to address A+DPTR. Jump if A=0. Jump if A = 0. Compare A to immediate data and jump if they are not equal. Compare A to direct byte and jump if they are not equal. Compare immediate data to indirect byte and jump if they are not equal. Compare immediate data to indirect byte and jump if they are not equal. Compare immediate data to register and jump if they are not equal. Decrement direct byte and jump if result is different from 0. Decrement register & jump if result is different from 0. No operation1. 1 Code s Mnemonic Byte s Cycl es 2 2 2 2 2 2 2 2 2 2 2 *1 12 22 32 *1 02 80 73 60 70 B4 ACALL LCALL RET RET1 AJMP LJMP SJMP JMP JZ JNZ CJNE ADDR11 ADDR16 ADDR11 ADDR16 REL @A,DPTR REL REL A,#DATA,REL 2 3 1 1 2 3 2 1 2 2 3 B5 CJNE A,DIRECT,REL 3 2 B6 CJNE @R0,#DATA,REL 3 2 B7 CJNE @R1,#DATA,REL 3 2 B8-BF CJNE Rn,#DATA,REL 3 2 D5 DJNZ DIRECT,REL 3 2 D8-DF DJNZ Rn,REL 3 2 00 NOP 1 1 This instruction does nothing other than advance the PC by 1. It is intended for causing short delays. EB-3191 – Introduction to microprocessors and microcontrollers 117 5.10 Integrated exercises The exercises in this paragraph cover a variety of different subjects connected with 8051 and constitute a collection of levels in the development of software. Each subject consists of theoretical background (if necessary), an example exercise and a challenge exercise for the student. Part of the exercises end in returning to the monitor program by calling the WARM routine, which returns the CPU to the debugger. The WARM routine is located at address C003H. We refer to switches and LEDs in the exercises. In the flow charts we do not refer to the 8255 initialization of the DSM-2200 card. The programs do refer to it. The solved exercises are given in assembly language. The user should write the program using an editor, compile it into machine language by using an assembler and download it and debug it by using a debugger. This software development procedure is described in chapter 2, section 2.15. In the exercises special emphasis was put on working with blocks of data. You will also find that the special components of the 8051 such as Interrupts, Timers and Serial Communication are described at length. In experiment 4.4 we described some of the assembler directives. We will review them here and describe some more. Directives are also called pseudo operations. They appear in the assembly program as instructions, but do not belong to the microprocessor's instruction set. They aid us when writing the program, to give it flexibility and a generalized form. EB-3191 – Introduction to microprocessors and microcontrollers 118 EQU - Defining a symbol for a numeric value: This directive assigns a fixed numeric value to the symbol. This enables the use of symbols in the program instead of fixed numeric values. For Example: PORTA EQU 3401H In the program we will write only the symbol (in our example PORTA) and not the numeric value. If we wish to change the value for PORTA we need only to change the directive and the assembler will make the change in the object program wherever the symbol PORTA appears. ORG - ORiGin directive: This directive is accompanied by an address. It indicates to the assembler at which start address to locate the program section which follows. The translated bytes will be placed at consecutive addresses from this address. A number of origin instructions may appear in one program. For example: ORG 0100H . Program section 1 . . ORG 300H . Program section 2 . . The assembler knows the position of each instruction in relation to the relevant ORG directive, and calculates its address accordingly. In this fashion it knows the address of a label, and knows how to calculate branching displacements. EB-3191 – Introduction to microprocessors and microcontrollers 119 END - End of program directive: This directive indicates the end of the source program to the assembler. This directive is vital for the assembler, which performs two passes over the source program. When the END directive is reached the second pass begins. If a program is not limited by an END statement, the assembler will indicate an error and abort translation of the program. DB - Define Byte: This directive determines bytes in the program area as a data and not as program instruction. When the assembler scans the source program, it advances a counter which points to the corresponding address in the object program. When a DB directive is encountered, the assembler plants the bytes determined in the directive at the corresponding addresses. Examples: a) DB 50H Place the value 50H at the address. b) MESSG: DB 50H,51H,52H Place the number 50H,51H,52H starting at the address. c) TITLE: DB 'SES',24H Place the ADCII codes of the characters between the ' ' and 24H after them at consecutive addresses beginning at the address in the counter. The label TITLE assumes the value in the counter. EB-3191 – Introduction to microprocessors and microcontrollers 120 DW - Define Word: This directive is accompanied by a 2-byte (word) number or by a symbol that equal to such a number. The assembler will place the two bytes of the word at the address in the program counter and the following address. Examples: a) STRTADR: DW 1F00H LSTADR: DW 1F02H b) FROM: DW STRTADR DS - Define Storage: This directive determines a group of cells (usually in the RAM), which are used as variables. The symbol that accompanies this directive gets the counter address which point to these cells. The number, which goes with this directive indicated the number of cells connected to the directive. Examples: START: LAST: VALUE: DEST: ORG 100H DS 2 DS DS 2 2 1 The number written in the directive indicates the number of the allocated cells. The lables in the example will receive the following values: START: LAST: VALUE: DEST: 3000H 3002H 3004H 3005H EB-3191 – Introduction to microprocessors and microcontrollers 121 5.10.1 Input and processing of a data byte Purpose: Flow chart: To transfer the condition of the switches to the lights in an endless loop, provided that switch no. 3 (D3) is not lifted. If it is lifted, then the program should turn off the lights and stop. PROCESS Input/Output address DPTR (DPTR) A AB A AND 08 A I/O ≠ 0 Yes No BA A (DPTR) JUMP 0A A (DPTR) END EB-3191 – Introduction to microprocessors and microcontrollers 122 EB-3000 + EB-3191 IOPORT WARM EQU EQU 0FF00H 0103H PROC: PROC1: ORG MOV MOVX 2100H DPTR,#IOPORT A,@DPTR MOV ANL JNZ MOV MOVX SJMP CLR MOVX LCALL END B,A A,#08H PROC2 A,B @DPTR,A PROC1 A @DPTR,A WARM PROC2: ;Load A from switches & store result ;Check S3. Stop if ON ;Restore in A ;Move A to lights ;Turn the lights OFF Run the program from address 2100, change the switches and observe its behavior. Challenge exercise 1: Change the program so that instead of using the ANL instruction, use the Boolean instruction JB or JNB. Challenge exercise 2: Write a program, which inputs a number, adds 50H to it and, if there is no carry, outputs the result. If there is a carry, it should output FFH. EB-3191 – Introduction to microprocessors and microcontrollers 123 5.10.2 PLC - Programmable Logic Controller The 8051 is widely used in PLC systems. With its bit manipulation instructions, it is very easy to implement a logic function. Purpose: A program that reads the switches and outputs the result of the following diagram in an endless loop: SW.2 SW.1 LED.7 SW.0 This program has no loops or branches and will therefore appears without a flow chart. EB-3000 + EB-3191 IOPORT PLC: EQU 0FF53H ORG LJMP ORG MOV MOVX MOV ANL ORL 2000H PLC 2100H DPTR,#IOPORT A,@DPTR C,ACC.2 C,ACC.1 C,/ACC.0 CLR MOV MOVX SJMP END A ACC.7,C @DPTR,A PLC ;SW.2 status to carry flag ;SW.2 AND SW.1 to carry flag ;Carry OR complement of SW.0 to carry ;Clear accumulator ;Result to LEDs Run the program from address 2100, change the switches and observe its behavior. EB-3191 – Introduction to microprocessors and microcontrollers 124 While running, the LED.7 should act according to the following table: SW.2 SW.1 SW.0 LED.7 0 0 0 1 0 0 1 0 0 1 0 1 0 1 1 0 1 0 0 1 1 0 1 0 1 1 0 1 1 1 1 1 Challenge exercise: Write a program that implements the following diagram: SW.3 SW.2 SW.1 SW.0 LED.0 EB-3191 – Introduction to microprocessors and microcontrollers 125 5.10.3 Look up tables A look up table is a table used to convert values from one form to another. For example, numbers are shown in their binary code (0-F) and we wish to translate them into their ASCII values. To do this we write a table, which includes the ASCII values, according to their order. These values will be in hexadecimal code: 30,31,32,33,34,35,36,37,38,39,41,42,43,44,45,46 And they are the values of the characters: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F The ASCII value of the number I will be located at the start address of the table + I. Purpose: A program, which inputs a number from the switches, translates it into ASCII code and outputs the converted value to the lights. The program runs in an infinite loop. The conversion program is based on the instruction: MOVC A,@A+PC EB-3191 – Introduction to microprocessors and microcontrollers 126 Flow chart: Start CONVERT Input/Output address DPTR (DPTR) A Clear 4 MSB’s Conversion table start 3 cells after program counter (see program). A AND 0F A A+3 A (Program Counter +A) A A (DPTR) JUMP EB-3191 – Introduction to microprocessors and microcontrollers 127 EB-3000 + EB-3191 IOPORT EQU 0FF53H CONVRT: ORG LJMP ORG MOV 2000H CONVRT 2100H DPTR,#IOPORT MOVX ANL ADD A,@DPTR A,#0FH A,#3H MOVC MOVX A,@A+PC @DPTR,A SJMP DB DB DB DB END CONVRT 30H,31H,32H,33H,34H 35H,36H,37H,38H,39H 41H,42H,43H,44H,45H 46H TABLE: ;I/O address input from switches ;Clear 4 MS bits ;Table begins 3 bytes after PC ;Read from table ;Output converted byte ;Do it again Run the program from address 2100, change the switches and observe its behavior. Challenge exercise: Change the program so that the placing of the conversion table will not be in sequence with the program. In such a case, we should use DPTR instead of PC. EB-3191 – Introduction to microprocessors and microcontrollers 128 5.10.4 Subroutines When we write a main program, which relies on a subroutine, we first characterize and write the subroutine, then the main program is written. The reason for this is that the main program may be required to prepare data for the subroutine and/or receive data from it. The transfer of data from one program to the other is done through registers. The subroutine sometimes destroys the contents of certain registers and the main program should be aware of this. Purpose: Flow chart: The main program should turn on and off the output lights at a frequency determined by the input switches. The subroutine creates a delay according to the number, which it inputs through the accumulator, multiplied by FF. DELAY A R7 FF R6 R6-1 R6 ≠0 Yes No R7-1 R7 ≠0 Yes No RETURN EB-3191 – Introduction to microprocessors and microcontrollers 129 Flow chart of the main program: LIGHTS I/O address DPTR 0A A (DPTR) (DPTR) A Call DELAY FF A A (DPTR) (DPTR) A Call DELAY JUMP EB-3191 – Introduction to microprocessors and microcontrollers 130 EB-3000 + EB-3191 IOPORT LIGHTS: LIGHT2: EQU 0FF00H ORG LJMP ORG MOV CLR MOVX MOVX LCALL MOV MOVX MOVX LCALL SJMP 2100H LIGHTS 2100H DPTR,#IOPORT A @DPTR,A A,@DPTR DELAY A,#0FFH @DPTR,A A,@DPTR DELAY LIGHT2 ;I/O address ;Turn lights OFF ;Read switches for delay ;Turn lights ON ;Read switches for delay ;Do it again ;******************************************************************** ;NAME: DELAY ;INPUTS: A ;OUTPUTS: None ;CALLS: None ;DESTROYS: A,R7,R6 ;DESCRIPTION: Creates a delay depending on number in ACC multiplies by FF ;******************************************************************** DELAY: DELAY2: DELAY3: MOV MOV DJNZ DJNZ RET END R7,A R6,#0FFH R6,DELAY3 R7,DELAY2 ;Delay length ;Multiply by FF ;First loop ;Second loop Run the program from address 2100, change the switches and observe its behavior. Challenge exercise: Assume that the output lights are traffic lights directing two lanes crossing each other (6 out of the 8 lights). Write a program, which will operate the traffic lights according to the different possible combinations and with different delay times. EB-3191 – Introduction to microprocessors and microcontrollers 131 5.10.5 Interrupts Reread paragraph 5.2 before you continue with this paragraph. As mentioned in paragraph 5.2, there are five possible sources in the 8051 for interrupt requests. Three of the above sources are internal and are devices in the 8051 itself. Those are the two timers and the serial communication unit called "UART". We will briefly describe the above three units: The timer is a counter to which a clock is attached. When all the cells of the counter reach a '0' condition (overflow), it creates an interrupt request. In the 8051, there are two timers, independent of each other. The UART is a unit, which enables serial communication. It receives a character for transmission in parallel form and transmits it in serial form, or receives a character in serial form and the CPU reads it in parallel form. The UART initiates an interrupt request each time it completes the reception or transmission of a character in serial form. Two additional sources for interrupt requests reach the 8051 via two external interrupt lines called "External0" and "External1". The logic level on one of these lines sinks to '0' to indicate an interrupt requested by the source connected to that line. In the 8051 there are two registers connected to this system of interrupts. One register enables the blocking of a specific one or all interrupt requests. This is called a "MASK" and the register is called "Interrupt Enable" (IE). The second register determines the priority level of each one of the interrupts. This register is called "Interrupt Priority" (IP). It enables us to determine, by software, which of two simultaneous interrupt requests will have a higher priority. EB-3191 – Introduction to microprocessors and microcontrollers 132 Interrupt control: As already mentioned, the masking of interrupts is done by writing to the IE register. The address of this register is A8H and we are able to refer to it by direct addressing. We may also access the bits of this register by bit manipulation. Each of the bits of this register has a different function, and they are described in figure 5-4: (MSB) EA SYMBOL POSITION EA IE.7 - IE.6 ET2 IE.5 ES IE.4 ET1 IE.3 EX1 IE.2 ET0 IE.1 EX0 IE.0 X ET2 ES ET1 EX1 ET0 (LSB) EX0 FUNCTION Disables all interrupts. If EA=0, not interrupt will be acknowledged. If EA=1, each interrupt source is individually enabled or disabled by setting or clearing its enable bit. Reserved. Enables or disables the Timer 2 overflow or capture interrupt. If ET2=0, the Timer 2 interrupt is disabled (for 8052 only). Enables or disables the Serial Port interrupt. If ES=0, the Serial Port interrupt is disabled. Enables or disables the Timer 1 overflow interrupt. If ET1=0, the Timer 1 interrupt is disabled. Enables or disables External Interrupt 1. If EX1=0, External Interrupt 1 is disabled. Enables or disables the Timer 0 overflow interupt. If ET0=0, the Timer 0 interrupt is disabled. Enables or disables External Interrupt 0. If EX0=0, External Interrupt 0 is disabled. Figure 5-4 Description of the IE register When a bit in the IE register is '0', it masks the interrupt associated to it. Bit EA masks all interrupts, with no consideration as to the status of the other bits of the register. In order to enable an interrupt, we should raise the bit associated to that interrupt to '1', and also raise the EA bit to '1'. As already mentioned, this may be done either by direct addressing or by bit manipulation. EB-3191 – Introduction to microprocessors and microcontrollers 133 In the 8051 there are two priority levels for interrupts. Each of the interrupt sources may be classified as bearing a higher or a lower priority level. The classification is done by writing in the IP register. The address of this register is B8H and we access it by direct addressing. We may also access the bits of this register by bit manipulation. The functions of the bits of this register are described in figure 5-5: (MSB) X SYMBOL PT2 POSITION IP.7 IP.6 IP.5 PS IP.4 PT1 IP.3 PX1 IP.2 PT0 IP.1 PX0 IP.0 X PT2 PS PT1 PX1 PT0 (LSB) PX0 FUNCTION Reserved. Reserved. Defines the Timer 2 interrupt priority level. PT2=0 programs it to the tighter priority level (for 8052 only). Defines the Serial Port interrupt priority level. PS=1 programs it to the tighter priority level. Defines the Timer 1 interrupt priority level. PT1=1 programs it to the tighter priority level. Defines the External Interrupt 1 priority level. PX1=1 programs it to the tighter priority level. Defines the Timer 0 interrupt priority level. PT0=1 programs it to the tighter priority level. Defines the External Interrupt 0 priority level. PX1=1 programs it to the tighter priority level. Figure 5-5 Description of the IP register Raising an interrupt priority bit to 1 gives the associated interrupt a higher priority level. We may have a number of interrupts with the same priority level (high or low). In this case, the priority between them is determined according to the order of the bits: PX0 with the highest priority and PS with the lowest. EB-3191 – Introduction to microprocessors and microcontrollers 134 In the initialization of the 8051, the IE and IP registers are given "00" values. SP is given "07" value (area BANK1). In case the main program is required to enable interrupts, it should include initialization of the values of these registers. For example: Enable external interrupts only. MOV IE,#85H ;10000101 EXT0 low priority, EXT1 high priority. MOV IP,#04H ;00000100 Stack starting at the address 31H in MOV SP,#30H ; DIRECT. After determining the above, we are able to mask the interrupts by using one instruction: CLR 0AFH - CLR EA Or enable them by using the instruction: SETB 0AFH - SETB EA There is an additional register called TCON (Timer CONtrol) intended to control the timer. But for this purpose we only use the four higher bits of the register. The four lower bits are used to determine the mode of operation of the external interrupt requests - whether they will be activated by edge triggering or by level triggering. In the case of edge triggering, the interrupt request line is connected to an internal Flip-Flop. With the transition of the line from high to low, the interrupt request is registered in the Flip-Flop. The system "remembers" the request even if the interrupt line reverts to '1' before the CPU is free and able to check the line. In level triggering, the interrupt request is not latched, and therefore the interrupt line must be kept at '0' long enough for the CPU to notice it. EB-3191 – Introduction to microprocessors and microcontrollers 135 The TCON register is at address 88H and we may access it either by direct addressing or by bit manipulation. Its four lower bits are described in figure 5-6: TCON IE1 IT1 IE0 IT0 88H TCON. 0 Interrupt 0 type control bit INT TCON. 1 Interrupt 0 edge flag CLK Edge sensitive 1 D Q Interrupt detection Level sensitive TCON. 2 Interrupt 0 type control bit TCON. 3 Interrupt 1 edge flag Figure 5-6 Programming the form of triggering in the TCON register The bits IT0 and IT1 are determined in the software by the user according to the intended MODE. If the bit is '1' - the interrupt will be edge triggered. If it is '0' - the interrupt will be level triggered. The bits IE0 and IE1 are, in effect, the Flip-Flop of the interrupt requests, when using edge triggering. They are raised to '1" when an interrupt request is received and revert to '0' when the CPU has identified the interrupt request. We are able to access the TCON register by software and to check the status of those bits, to raise them to '1' In the initialization of the 8051 TCON is given the value 00H. The advantage of level triggering is the ability to connect a number of external sources to the same interrupt line and enable identification of the source of the request through one of the ports of the 8051. See figure 5-7. EB-3191 – Introduction to microprocessors and microcontrollers 136 +5V 40 VCC 28 A14/P2.6 27 A13/P2.5 26 A12/P2.4 25 A11/P2.3 24 A10/P2.2 23 A9/P2.1 22 A8/P2.0 21 AD7/P0.7 32 AD6/P0.6 33 AD5/P0.5 34 AD4/P0.4 35 AD3/P0.3 36 AD2/P0.2 37 AD1/P0.1 38 AD0/P0.0 39 11 P3.1 (TXD) P1.7 8 12 P3.2 (INT0) P1.6 7 13 P3.3 (INT1) P1.5 6 14 P3.4 (T0) P1.4 5 15 P3.5 (T1) P1.3 4 16 P3.6 (WR’) P1.2 3 17 P3.7 (RD’) P1.1 2 P1.0 1 XTSL. 1 30pF 8051AH 18 XTSL. 2 +5V 10 RST 9 RESET +5V Open Collector Inverters INT. ROM +5V 31 I/O 3 EA 10 P3.0 (RXD) EXT. ROM I/O DEVICE 1 DEVICE AL DEVICE 3 VSS A15/P2.7 19 30pF 20 E 30 P S EN 29 DEVICE 4 Figure 5-7 Joint of number of interrupt sources EB-3191 – Introduction to microprocessors and microcontrollers 137 When the CPU gets the interrupt request, it checks with the P1.0-P1.3 lines who requested the interrupt and responses accordingly. We will use figure 5-7 to explain some points that are not related to interrupts. External memories and clock: Port 0 and port 2 are used as data and address lines for connecting external memory units or external devices to the 8051. Port 0 is used for data and address lines (AD0-AD7) and port 2 is used for address lines (A8-A15). This prevents us from using these ports as I/O (Input/Output) ports. How to connect external memories and other devices to the 8051 is described in the author's book: "Hardware and Peripheral Components". If the system software is in the 8051 internal ROM, the EA' line should be connected to +5V. If the system software is in an external ROM and we want the 8051 to ignore its internal ROM, the EA' line should be connected to GND. The 8051 has an internal clock which is controlled by an external crystal oscillator. Figure 6-7 describes how the oscillator should be connected. The RESET circuit: The 8051 (as all microprocessors) has a RESET line for its initialization. When we supply power to the 8051, the RESET line should be held at the high voltage level for a certain time (depending on the crystal frequency). This delay circuit is also described in figure 6-7. When we want to reduce current consumption we move the CPU into WAIT mode or STOP mode (see page 107). We also connect a ‘wake-up’ circuit to an interrupt request line or to the RESET line accordingly. EB-3191 – Introduction to microprocessors and microcontrollers 138 Watch dog: Sometimes, because of an electromagnetic noise or power failure, the CPU loose data and start working randomly. Pressing RESET initials the CPU. Sometimes, we want to add a system that automatically restarts the CPU when it works randomly. This kind of system is called ‘Watch-Dog’. The watch dog is based on a timer, which resets the system after an interval time, if it hasn’t received a clear pulse during that interval. The normal program should include producing such clear pulse. When the CPU works randomly, it will not clear the timer and the timer will reset the system. There are some 8051 controllers that include internal watch-dog components. On the EB-3191 there is a push button <INT> that can be connected to INT0 or INT1 lines. We shall connect it to INT1. When we push that button, the line sinks to '0', while it's normal state is '1'. The interrupt request (provided it is not masked) refers the CPU to address 0013H. At this address, there is a jump command to address 2013H. At address 2013H, the user can write his interrupt program or write an additional jump instruction to the interrupt program. Exercise: We shall write a main program (starting at address 2100H), which creates a "running light" effect on the output lights and an interrupt program. The interrupt program will be the same "flashing lights" program as in paragraph 5.10.6 and will start at address 2013H. The main program initializes the registers IE, IP, SP and TCON at the beginning. EB-3191 – Introduction to microprocessors and microcontrollers 139 EB-3000 + EB-3191 IOPORT INT1: INT2: MAIN: MAIN2: EQU 0FF00H ORG LJMP ORG LJMP 2000H MAIN 2013H INT1 ORG MOV CLR MOVX MOVX LCALL MOV MOVX MOVX LCALL SJMP 2040H DPTR,#IOPORT A @DPTR,A A,@DPTR DELAY A,#0FFH @DPTR,A A,@DPTR DELAY INT2 ORG MOV MOV MOV MOV MOV MOV MOV MOVX MOVX LCALL MOV RL SJMP END 2100H IE,#84H IP,#04H TCON,#04H SP,#30H DPTR,#IOPORT A,#01H R5,A @DPTR,A A,@DPTR DELAY A,R5 A MAIN2 ;I/O address ;Turn lights OFF ;Read switches for delay ;Turn lights ON ;Read switches for delay ;Do it again ;Enable EXT1 only ;High priority to EXT1 ;Edge triggering for EXT1 ;Stack start at 31H ;I/O address ;Start "run light" at LSB ;Read switches for delay ;Rotate lights left ;Do it again ;****************************************************************** ;NAME: DELAY ;INPUTS: A ;OUTPUTS: None ;CALLS: None ;DESTROYS: A,R7,R6 ;DESCRIPTION: Creates a delay depending on number in ACC multiplies by FF ;****************************************************************** DELAY: MOV R7,A ;Delay length DELAY2: MOV R6,#0FFH ;Multiply by FF DELAY3: DJNZ R6,DELAY3 ;First loop DJNZ R7,DELAY2 ;Second loop RET END EB-3191 – Introduction to microprocessors and microcontrollers 140 Run the program. Push the <INT> button. The system should shift to the interrupt program, which flashes the lights. Exercise 1: Change the interrupt program so that it counts the flashes. After 30 flashes, the CPU will return to the main program. Use the RETI instruction. Exercise 2: Change the main program so that the LSB switch of the input switches determines the direction of rotation, clockwise or counter clockwise. When the lights rotate counter clockwise, the interrupt should be masked with the help of the instruction CLR EA. When the lights rotate clockwise, we are able to request an interrupt. Try this program once using edge triggering at EXT1 and once with level triggering. EB-3191 – Introduction to microprocessors and microcontrollers 141 5.10.6 How to use the timer/counter The timer is a counter, which counts pulses reaching it at equal intervals. So, in effect, it measures the time. The distinction between the names counter and timer is made according to the function. If we connect a signal derived from the CPU clock (i.e. pulses at regular intervals), to the input of the counter, then the device functions as a timer. If we connect the input of the counter to an external source of signals, which creates pulses not necessarily at regular intervals, then the device will function as a counter. The 8051 has two timers/counters which prove to be most helpful tools. They avoid the need of programming precise delay loops for event sampling by examining the counter status, and they release the CPU to perform other duties. The following example will demonstrate the importance of the timer. The emulation of a clock by the CPU may be achieved by delay loops in the program. In this form of emulation, there are two major problems, the first is due to the fact that the CPU is capable of dealing with this program only. (i.e. with the delay loops and with processing the data at the end of each loop). The second problem is that the time required to process the data changes. For example, the time required to update the minutes is shorter than the time required to update the minutes and the hours. By using a timer we receive the interrupt request at regular intervals, the length of which may be programmed by the user. The CPU may simultaneously be occupied with any program. With the reception of an interrupt request from the timer, it turns to the interrupt program and updates the clock accordingly. The intervals in this case will be equal. EB-3191 – Introduction to microprocessors and microcontrollers 142 There are two timers/counters in the 8051, each of them 16 bits long. They are schematically described in figure 5-8: 12 OSC C/ T 0 C/ T 1 TL1 (8 bits) TH1 (8 bits) TF1 INTERRUPT C/ T 1 CONTROL T1 PIN TR1 GATE INT1 PIN Figure 5-8 Description of the timers/counters The timers/counters are called TIMER0 and TIMER1 and we shall hereafter refer to them, for convenience, as "timers" although they are capable of serving as counters as well. The timers consist of four registers in the register system, each of 8 bits. They are called: TL0 (Timer Low 0), TH0, TL1 and TH1. They occupy the addresses in direct addressing: 8AH, 8CH, 8BH and 8DH respectively. The timers are capable of performing a vast variety of different tasks which are determined by the user with the help of two control registers: TCON and TMOD. The signals in the figure 5-8, C/T', TR1 and GATE are outputs of Flip Flops which are part of these registers and are determined n the software by the user. EB-3191 – Introduction to microprocessors and microcontrollers 143 The register TMOD is described in figure 5-9: (MSB) GATE (LSB) C/T` M1 M0 GATE TIMER 1 GATE C/T` Gating control when set. Timer/Counter “x” is enabled only while “INTx” pin is high and “TRx” control pin is set. When cleared Timer “x” is enables whenever “TRx” control bit is set. Timer of Counter Selector Cleared for Timer operation (input from internal system clock). Set for counter operation (input from “Tx” input pin). C/T` M1 M0 TIMER 0 M1 0 M0 0 0 1 1 0 1 1 1 1 Operating Mode MCS-48 timer “TLx” serves as 5 bit prescaler. 16 bit Timer/Counter “THx” and “TLx” are cascaded; there is no prescaler. 8 bit auto-reload timer-counter “THx” holds a value which is to be reloaded into “TLx” each time it overflows. (Timer0) TL0 is an 8 bit timer counter controlled by the standard Timer 0 control bits. TH0 is an 8 bit timer only controlled by timer 1 control bits. (Timer1) Timer-counter 1 stopped. Figure 5-9 Description of the TMOD TMOD is divided into two parts. One part deals with TIMER0 and the other with TIMER1. The bit C/T' determines whether the timer will function as a timer or as a counter. If this bit is '0', then signals, which come from the CPU clock are divided by 12 and then directed to the counters TL and TH. This is for application as a timer. If C/T' is '1', then the input to the counter is taken from the T0 or T1 lines, which are external to the CPU (pins P3.4 and P3.5). Signals received from these lines will operate the counter. This is for application as a counter (see figure 5-9). On their way to the counters, the signals pass via a control switch (a logic GATE). When this gate is switched on, the pulses flow to the counters and the timer is switched on. The switch is controlled by a logic circuit, the inputs of which are TR1, GATE and INT input. EB-3191 – Introduction to microprocessors and microcontrollers 144 TR1 is a Flip-Flop output in the TCON register, which is described in figure 5-10: (MSB) TF1 (LSB) TR1 Sybmol Position Name & Significance TF1 TCON.7 TR1 TCON.6 TF0 TCON.5 TR0 TCON.4 TF0 TR0 IE1 IT1 IE0 IT0 Symbol Position Name & Significance Timer 1 overflow Flag. Set by hardware on time/counter overflow. Cleared by hardware when processor vectors to interrupt routine. Timer 1 Run control bit. Set/cleared by software to turn timer/counter ON/OFF. IE1 TCON.3 IT1 TCON.2 Timer 0 overflow Flag. Set by hardware on time/counter overflow. Cleared by hardware when processor vectors to interrupt routine. Timer 0 Run control bit. Set/cleared by software to turn timer/counter ON/OFF. IE0 TCON.2 IT0 TCON.0 Interrupt 1 Edge flag. Set by hardware when external interrupt edge detected. Cleared when interrupt processed. Interrupt 1 Type control bit. Set/cleared by software to specify falling edge/low level triggered external interrupts. Interrupt 0 Edge flag. Set by hardware when external interrupt edge detected. Cleared when interrupt processed. Interrupt 0 Type control bit. Set/cleared by software to specify falling edge/low level triggered external interrupts. Figure 5-10 A full description of the TCON register IE1, IT1, IE0 and IT0 are used to control the external interrupts. The bits TR0 and TR1 are used by the software to operate the timers. If the bit TR is '1', then the timer is switched on, provided that the switchable GATE bit is '0'. A GATE bit is a bit in the TMOD register. When it is '1' and TR is '1' too, then the line input of the external interrupt is used to control the timer. When the INT input is '0', then the timer starts operating. When it is '1', its operation stops. Check this in figure 5-10. EB-3191 – Introduction to microprocessors and microcontrollers 145 Each pulse which reaches the counters TL and TH advances them by 1. When they are filled with ones, the next pulse will cause the contents of the counters to become zero, causing an overflow condition. This turns on the TF Flip Flop in the TCON register. When a TF is switched ON, it creates an interrupt request accordingly (TIMER0 or TIMER1 interrupt). Usually we want the timer to count a certain number of pulses and then to create an interrupt request. In this case, we load the registers of this timer with the two's complement of the number of pulses to be measured. The timers have four operating modes called MODE0-MODE3. These modes are determined for each timer by the bits M0 and M1 in the TMOD register. In addition to these modes, TIMER1 has the function of supplying a driving signal to the UART in the 8051 in order to set the frequency of the serial communication. MODE0 - M1=0, M0=0: In this MODE, the timer functions as described in figure 5-8, except for the following: the TL register functions as a counter consisting of 5 bits only and it is used as a prescaler by 32 to the TH register. This way we receive a MODE identical to the timer of the 8048 (which is an earlier version of the 8051). MODE1 - M1=0, M0=1: The timer functions exactly as described in drawing 6-8 while the registers function together as a 16 bit counter. EB-3191 – Introduction to microprocessors and microcontrollers 146 MODE2 - M1=1, M0=0: In MODE2 the TL is used as an 8 bit counter and the TH as a LATCH. We prime the TH with a reload value. Each time the count of TL is completed, it is automatically reloaded with the reload value, which is in TH, and starts running again from that value. See figure 5-11. 12 OSC C/ T 0 TL1 (8 bits) C/ T 1 T1 PIN TF1 INTERRUPT CONTROL RELOAD TR1 GATE TH1 (8 bits) INT0 PIN Figure 5-11 Description of MODE2 of the timers EB-3191 – Introduction to microprocessors and microcontrollers 147 MODE3 - M1=1,M0=1: In this MODE the two timers function as three separate systems. 12 OSC 1 f 12 OSC 1 f 12 OSC C/ T 0 TL0 (8 bits) C/ T 1 TF0 INTERRUPT CONTROL T0 PIN TR0 GATE INT0 PIN TH0 (8 bits) 1 f 12 OSC TF1 INTERRUPT CONTROL TR1 Figure 5-12 Description of MODE3 of the timers TIMER1 is used as a timer/counter, but its output is not connected to the interrupt request flag TF1. It is used only to supply pulses for serial communication. TIMER0 is divided into two parts. TL0 functions as a timer/counter, which turns on TF0 and initiates an interrupt request accordingly. TH0 functions as a timer only. At its input, it receives the clock frequency divided by 12 and controlled by TR1. Its output turns on TF1 and initiates an interrupt request accordingly. EB-3191 – Introduction to microprocessors and microcontrollers 148 Note: The flags TF0 and TF1, when raised to '1', create an interrupt request, provided they are not masked by the register IE. By acknowledging the interrupt request, the flags are cleared again. The timers may be used without interrupts by software sampling and checking the status of the flags and by clearing them by software. In order to calculate the number, which needs to be stored in the timer's registers in order to receive a delay of a certain length, we have to know the frequency of the system's clock. In the EB-3191, that frequency is 11.0592MHZ. If we define TD as the delay time, and TP as the cycle time of a pulse, which reaches the timer, then the number of pulses that the timer has to count is equal to TD divided by TP. The number which should be reloaded into the registers will be the two's complement of that number of pulses. The frequency of the pulses which reach the timer equals fosc/12 and therefore TP=12/fosc. (fosc = system clock frequency). For example: If we want a delay of 1mS, then the number which should be loaded into the registers will be the two's complement of X, calculated in the following formula: X TD f osc 1m 11.0592M 021.6 922 12 12 The remainder is ignored. 922 is a decimal number and equal to 039AH. Two's complement of X is EC66H, so ECH will be load to TH and 66H will be load to TL. EB-3191 – Introduction to microprocessors and microcontrollers 149 Summary: In order to operate the timer we have to perform the following stages: a) b) c) To determine a MODE for the timer/counter with the help of the TMOD register. To load an initial value into the TH and the TL of the required timer. To turn on the timer with the help of the TCON register. Timer experiment: We shall demonstrate the use of the timer with the following programs. The main program initializes timer1 and reads the switches into a direct memory cell (40H) in an endless loop. The Timer1 interrupt routine reads this cell, complements its byte and outputs it to the LEDs every 0.5 seconds. The interrupt request of TIMER1 (when it is not masked) refers the CPU to the address 001BH. At this address, there is a jump command to address 201BH. At address 201BH, the user can write his interrupt program or an additional jump instruction to the interrupt program. We will use TIMER1 in MODE1 (timer MODE when the GATE is closed). Operating the timer will be performed with the help of TR0. The main program and the Timer1 interrupt program will be as follows: EB-3191 – Introduction to microprocessors and microcontrollers 150 EB-3000 + EB-3191 BUFF1 BUFF2 CNT IOPORT TIMR1: TIMRET: MAIN: MAIN2: MAIN3: EQU EQU EQU EQU 40H 41H 42H 0FF00H ORG LJMP ORG LJMP 2000H MAIN 201BH TIMR1 ORG CLR PUSH PUSH PUSH PUSH DJNZ MOV MOV CPL MOV MOV X MOV MOV MOV POP POP POP POP SETB RETI 2040H TR1 DPH DPL PSW ACC CNT,TIMRET CNT,#5 A,BUFF1 A DPTR,#IOPORT @DPTR,A ORG MOV MOV MOV MOV MOV SETB MOV MOV X CJNE SJMP MOV MOV SJMP END 2100H TMOD,#10H TL1,#00H TH1,#00H IE,#88H CNT,#5 TR1 DPTR,#IOPORT A,@DPTR BUFF1,A TL1,#00H TH1,#00H ACC PSW DPL DPH TR1 ;Stop TIMER1 ;Save PSW and ACC ;For the main program ;Initiate TIMER1 again ;For maximum delay ;Reload ACC and PSW ;Start TIMER1 ;Return to main program ;MODE1,C/T'=0,GATE=0 for TIMER1 ;For maximum delay ;For maximum delay ;Enable TIMER1 interrupt request ;Start TIMER1 ;Jump to "running lights" program A,BUFF2,MAIN3 MAIN2 BUFF1,A BUFF2,A MAIN2 Run the main program at 2100H, change the switches and observe the LEDs. EB-3191 – Introduction to microprocessors and microcontrollers 151 Challenge exercise: As mentioned in the previous paragraph, the <INT> push button is connected to EXT1. Change the initial instructions of the timer so that the timer will operate when the button <INT> is pushed. I.e., pushing the button will cause the lights to flesh, and its release - to halt. EB-3191 – Introduction to microprocessors and microcontrollers 152 5.10.7 Serial communication 5.10.7.1 Classification of communication methods: In communication between computers, the computers are connected to each other by communication lines. At each stage of the communication, there is a transmitting computer and a receiving computer. The transmitter transmits information through an output port and the receiver receives that information through an input port. It is possible for a transmitting computer to transmit and then switch into receiving condition and vice versa. No computer can "see" what is happening in the other computer. Computers can only read information, which is placed on their input ports. That is the reason why a part of the transferred information consists of signals concerning the status of the transmitting and the receiving computer, signals such as: "ready to receive", "receive a message", "end of message" etc. The various communication methods are classified in three basic groups: a) Synchronous and asynchronous: In synchronous communication, the computers are connected to a mutual line, which supplies synchronization signals to them both. The synchronization signal enables the computers to know when to transmit and when to expect a message through the communication lines. Each computer, before transmitting a message, awaits the appearance of the synchronization signal, and only then starts transmitting. A computer, which is due to receive a message, awaits the appearance of the synchronization signal and only then collects the information from its input port lines. In asynchronous communication, we circumvent the use of a synchronization pulse line and a pulse generator. On the information lines, we transmit a start signal at the beginning of each message. The receiving computer awaits the reception of such a signal. After locating it, the receiving computer collects the message, which follows that signal. This method of communication is the most commonly used. EB-3191 – Introduction to microprocessors and microcontrollers 153 b) Parallel and serial: In parallel communication, we transmit the information in parallel form. A byte of 8 bits is transmitted through a cable of 8 wires. Each bit is transmitted on a separate wire simultaneously. This method requires a cable with a large number of wires. In serial communication, we use a small number of wires. The byte is transmitted through one line, bit by bit. The transmitter and receiver must both be synchronized to the same communications frequency. c) Polling or interrupts: The problem in communication is in recognizing when the dialogue begins. One of the methods to overcome this obstacle is to determine one of the computers as "MASTER" and the others as "SLAVES". The master always initiates the communication. It turns to the slave and asks whether it has any information to transmit. It waits a certain time to receive a message from the slave. If the slave does not answer within that time, then the master returns to its main program. The above procedure is performed at pre-determined regular intervals. When the slave has a message to transmit, it waits for the master to turn to it and when this happens, the slave answers by transmitting an opening message. The master reacts and the dialogue takes place. This method is called "communication by polling". Another method to start a conversation is by interrupts. We use input ports with a strobe line (STB). When one computer wishes to talk to another, it sends a message on its own output port, together with a strobe pulse. An input port collects the message and performs an interrupt request in the receiving computer. The receiver executes the interrupt program, which handles the received message. This method is quick and convenient although it requires the use of adequate ports and interrupt programs. Another expression in communication is "handshake". This means that the transmitter of a message awaits an acknowledgement of it reception by the receiver. Without such acknowledgement, the transmitter does not continue with the program. EB-3191 – Introduction to microprocessors and microcontrollers 154 5.10.7.2 Serial asynchronous communication: This is the most popular method of communication in microcomputer systems. In this method, the communication line is minimal and may consist of two or three wires only. It is possible to transmit and to receive through telephone wires (with the help of an interface unit called a modem) and even through a wireless connection. Serial communication is a method in which a byte of 8 bits is translated into a series of serial pulses, zeros and ones, which are transmitted through the communication line. The receiver knows the length of time of each pulse transmitted by the transmitter. In serial asynchronous communication, there is a problem in identifying the start of each byte. The following procedure was therefore determined: Start bit: The normal status of the line is "high". Before each byte which is transmitted in a serial form, a '0' bit should be transmitted for the same period of time which is required for the transmission of each of the other bits. This is called "start bit". The receiver identifies the beginning of the transmission of a character by identifying the transition from '1' to '0'. Data bits: At the end of the transmission of the start bit, the data bits are transmitted, one after the other (usually 7 data bits). The transmission time of each bit is equal to that of the other bits. Since the receiver knows when the transmission starts, it is able to time the sampling of the data bits in order to overcome the problem of transients. Parity bit: Usually we convert each data byte to ASCII code and transmit it in this code. ASCII is a code of seven bits. We use the eighth bit as a parity bit, which is used by the receiver to check the accuracy of the data received by it. The value of the bit ('0' or '1') is determined according to the number of 1's in the data byte. There are two ways to determine this: "even parity" and "odd parity". In "even parity", the number of 1's, including the parity bit, should be even. For example, if there are three 1's in a byte, then the transmitter determines the parity bit as '1'. If there are four 1's, then the parity bit will be '0'. EB-3191 – Introduction to microprocessors and microcontrollers 155 In "odd parity", the number of 1's, including the parity bit, should be odd. Stop bits: At the end of each byte, bits of logical 1's are transmitted (usually 2). These bits are used to transfer the line to its normal status for a period of time, which enables the receiver to perform primary processing of the information collected by it, and to resynchronize on the beginning of the transmission of the next character. The transmission of a single character (58H) will be as follows: 0 0 0 1 1 0 1 0 Stop bit Start bit LSB MSB Figure 5-13 Transmission of the character 58H in asynchronic serial communication The transmission rate is measured in units of baud, which are bits transmitted in a second. A different transmission is "bits per second", whereby we mean the data bits which are transmitted in one second. For example, if we transmit at a rate of 10 characters per second, the baud rate is 110. Each character requires 11 transmission bits for its transmission (including the start and stop bits). This rate is also equal to 80 bits per second (data bits). EB-3191 – Introduction to microprocessors and microcontrollers 156 To conclude, asynchronous serial communication is as described in following figure: Start bit DATA Stop bit Start bit DATA Stop bit Figure 5-14 Description of the transmission of data in serial communication The most popular transmission rates are: 110, 150, 300, 600, 1200, 1800, 2400, 4800 and 9600 baud. The transmitting computer converts a character from its parallel form (as a binary number) into serial form, and then transmits it. The receiving computer translates it back from serial form into parallel form. It is necessary for the receiver to know the transmission rate and the number of data bits in the transmitted byte (which is not always seven). It also has to know whether the eighth bit indicates even or odd parity or is insignificant, and the number of stop bits. In communication between computers - one computer transmits and the other receives. Usually, both computers have the capability of transmitting as well as of receiving. Each computer has a TXD (Transmit eXternal Data) output and a RXD (Receive eXternal Data) input. EB-3191 – Introduction to microprocessors and microcontrollers 157 In communication, there are two major forms of connection. One is called: "Full duplex Communication". See figure 5-15: TXD TXD TXD TXD RXD RXD RXD RXD HALF DUPLEX FULL DUPLEX Figure 5-15 The forms of connection in communication The second form of connection is called: "Half duplex Communication", and it uses only two connecting wires. In half duplex communication, a computer, which changes from receiving into transmitting status must ensure that the other computer has finished transmitting and that it has cleared the line. Usually, at the input and in the output of a communication line, there are driving components, which enable transmission of the signals over long distances. There are different methods of connection between computers. The most popular are RS232, RS422 and 20 mA current loop. These methods are described in the author's book: "Hardware and Peripheral Components". The process of receiving the serial information and of its conversion into parallel form operates in the following manner: The receiving computer samples the RXD input line and awaits the start bit, i.e. the sinking of the line to '0'. As soon as it notices this transition, it waits for a period equaling half a bit time, and then samples the line again. If the line is still '0', that means that the start bit has been received. Now it samples the line at intervals of one bit, according to the number of data bits. While sampling, the bits are pushed one after the other (LSB is being received first) into a shift register. At the end of the process, the shift register contains the transmitted byte, which is readable in parallel form. EB-3191 – Introduction to microprocessors and microcontrollers 158 This process is performed with the help of a hardware device called a UART Universal Asynchronous Receiver Transmitter, or with the help of software, which conducts the sampling of one bit of an input port and creates a delay. In this chapter, we shall describe the operation of the UART in the 8051. The UART in the 8051: The UART is a programmable device. For its operation it uses two registers: SCON and SBUF. We have to write a control word to SCON (Serial CONtrol) prior to operating the UART. The SBUF register (Serial BUFfer) consists, in effect, of two separate registers, placed at the same address. When writing information in SBUF for transmission, this information reaches a register called TX data. When we read information from SBUF, this information (previously received in serial communication), comes from a register called RX data. In order to operate the UART we need to supply a clock pulse according to the required frequency of communication. At each pulse of the clock, the UART performs a specific action. Therefore, clock frequency should be higher than that of the transmission in order to enable the UART to perform a number of actions between one bit and the next. It is common to have a clock frequency 16 times higher than the communication frequency. The frequency of the signal to the UART is achieved by dividing the CPU clock frequency. This frequency is, in effect, divided by two. The frequency of the UART clock is in accordance with the required baud rate, and will be achieved by the following formula: The frequency of the UART clock = 2 16 baud In order to create that frequency we use TIMER1, the output of which is connected to the UART as a clock generator. We program the timer to work in the position "auto Load" (see chapter relating to timers). We load the timer (TH1 SFR) with an initial value, which will create the required UART clock frequency. EB-3191 – Introduction to microprocessors and microcontrollers 159 The CPU clock signal, prescaled by 12 reaches the timer's input. The value, which should be loaded into the timer (division value) will therefore be according to the following formula: RELOAD VALUE Internal Clock Frequency 12 2 16 baud For example: Assume we wish to transmit and receive at a rate of 4800 baud, and the frequency of the crystal is 11.0592MHZ. The value, which should be loaded into the timer, will be: 11.0592 106 RELOAD VALUE 6 12 2 16 4800 The value should be an integer, which will be converted to two's complement before loading into the timer. The number that should be loaded into TH1 is FAH. After initializing the timer and the UART, the UART begins transmitting and receiving. The clock works all the time. When transmitting, the UART transmits the data bits, each during 16 clock cycles. When receiving, as soon as the UART identifies the transition of the RXD line to '0', it waits 8 clock cycles and conducts an additional sampling for verification purposes. Then it counts 16 additional clock cycles and collects the first data bit. Actually, the data bit is received in the following way: The UART samples the line three times, at the descending edge of the clock on the seventh, the eighth and the ninth cycles of the data bit. The decision regarding the value of the bit is a "Majority Vote". If in two samples, the value is '0', then the '0' is loaded into the shift register and vice versa. This method immensely improves the reliability of the reception. The UART automatically produces, with each character transmitted, one start bit and one stop bit. After transmitting the start bit, it transmits the eight bits, which are in the SBUF. The eighth bit can serve as a data bit, as a parity bit, we can set it to '0' (as required by some peripheral devices), or it can serve as an additional stop bit, when two are necessary. The way we use the eighth bit is determined in the software. EB-3191 – Introduction to microprocessors and microcontrollers 160 Sometimes we may have to work with nine information bits, for example where there are eight data bits and the ninth bit has to serve as parity bit or as an additional stop bit. The 8051's UART is capable of dealing with this situation. In such a case, after the transmission of the eight SBUF bits, the ninth bit is transmitted from the SCON register. Reception is performed similarly. Figure 5-16 describes the SCON register and the functions of its bits. The expression: "Set/Cleared by software" indicates that the content of a certain bit is determined in the software for the initialization of the device. The expression: "Set/Cleared by hardware" indicates that the bit is changed by the device itself. It is possible to call that bit and check its condition with the help of the software. See figure 5-16: (MSB) SM0 (LSB) SM1 SM0 Sybmol Position Name & Significance SN0 TCON.7 SM1 TCON.6 Serial port Mode control bit 0. Set/cleared by software (see note). Serial port Mode control bit 1. Set/cleared by software (see note). SM2 TCON.5 REN TCON.4 TB8 TCON.3 REN Serial port Mode control bit 2. Set software to disable reception of frames for which bit 8 it zero. Receiver Enable control bit. Set/cleared by software to enable/disable serial data reception. Transmit bit 8. Set/cleared by hardware to determine state of ninth data bit transmitted in 9 bit UART mode. TB8 RB8 T1 Symbol Position RB8 TCON.2 R1 Name & Significance NOTE: Receive bit 8. Set/cleared by hardware to indicate state of ninth data bit received. TCON.1 Received interrupt flag. Set by hardware when byte transmitted. Cleared by software after servicing. TCON.0 Received interrupt flag. Set by hardware when byte received. Cleared by software after servicing. The state of (SM0,SM1) selects: (0,0) – (0,1) – (1,0) – (1,1) – Shift register I/O expansion. 8 bit UART. Variable data rate. 9 bit UART. Fixed data rate. 9 bit UART. Variable data rate. T1 T2 Figure 5-16 Description of the SCON register EB-3191 – Introduction to microprocessors and microcontrollers 161 Bits 7 and 6, called SM0 and SM1, determine the operating mode of the UART. In mode "00" SBUF does not function as a UART, but as a shift register only. In mode "01", SBUF acts as an eight bit UART with a variable transmitting/receiving rate. In mode "10" SBUF acts as a nine bit UART with a fixed transmitting/receiving rate. In mode "11", SBUF acts as a nine bit UART with a variable transmitting/receiving rate. By variable transmitting/receiving rate, we mean that the rate may be determined by the user, as described at the beginning of this chapter. This applies to MODE1 and MODE3. In MODE0 (SM1,SM0=0,0) a square wave is connected to the UART with a fixed rate of the CPU clock frequency divided by 12. In MODE2 the UART is driven by a prescaler with the CPU clock frequency divided by 64, and this cannot be changed. We can double the speed of the UART by setting bit 7 of the PCON register at '1'. We cannot access this bit by bit manipulation, and should therefore use the instruction: MOV PCON,#80H, (PCON is in cell 87H in direct addressing). Bit 5 (SM2) is related to the synchronous mode of the UART. Bit 4 (REN) is the receive enable bit. When this bit is '1', the UART will start receiving information and will fill SBUF. When SBUF is full, bit 0 (RI) is raised to '1'. If the serial interrupt is enabled then an interrupt request is also received. In mode 0, (RI) must be cleared to enable reception. Bit 3 (TB8) is the ninth transmitted bit (the count starts with TB0) in the 9 bit mode of the UART. Bit 2 (RB8) is the ninth bit received in the 9 bit mode of the UART. Bit 1 is the TI bit, which is raised to '1' when the UART completes transmission of a data byte from SUBF. If the serial interrupt is enabled, then an interrupt request is received. In all four modes, transmission is initiated by any instruction that uses SBUF as a destination register. EB-3191 – Introduction to microprocessors and microcontrollers 162 We can emulate serial communication with the help of software loops or by using interrupts. Routines for receiving and transmitting a character may be performed by the software in the following way: SEND Yes TI = 0 ? No RECEIVE Yes RI = 0 ? No 0 => T1 SUBF => A A => SBUF 0 => R1 RETURN RETURN Character Send Routine Character Receive Routine Pay attention to the clearance of flags, which is done by the routines. When the transmitting and receiving routines are part of an interrupt program, then the program should check whether the interrupt request is received after transmission or reception of a character has been completed. On return from the interrupt routine, the flags are automatically cleared. The communication of the 8051 of EB-3191 with the PC is done through the 8051 UART. We do not have to do any installation to exercise serial communication. We shall use the Display Terminal function of the SES51C on the PC to communicate with the EB-3191. EB-3191 – Introduction to microprocessors and microcontrollers 163 Exercise: Write a program that executes the following: a) b) c) d) e) Initializes the 8251 as described in the discussion. Waits to receive a character from the PC through the series communication line. Outputs this character to the LEDs of the computer trainer. Sends this character as an echo to the PC. Jump to paragraph (b). EB-3000 + EB-3191 IOPORT INITIAL: CCI: CCO: EQU 0FF00H ORG LJMP ORG CLR MOV MOV MOV MOV MOV SETB MOV JNB MOV CLR MOVX JNB 2000H INITIAL 2100H TR1 TH1,#0FCH TL1,#0 PCON,#80H TMOD,#20H SCON,#DE TR1 DPTR,#IOPORT RI,CCI A,SBUF RI @DPTR,A TI,CCO CLR MOV SJMP END TI SBUF,A CCI ;Stop TIMER1 ;-3 for 9600 baud ;Double baud rate to 19,200 ;TIMER1 8 bit auto reload ;9 bit UART with variable data rate ;Start timer ;Wait until character is received ;Move character to ACC ;Enable next reception ;Out to LEDs ;Wait until previous transmission completed ;Clear 'ready for transmission' flag ;Send echo Step 1: Write, compile and download the program to the EB-3191. Step 2: Run the program. Step 3: Select the Display Terminal function or run this program. This program will turn the PC into a terminal. EB-3191 – Introduction to microprocessors and microcontrollers 164 Step 4: Press character keys on the PC. Echo of these characters will be printed on the screen. The ASCII code of these characters will be displayed on the LEDs. Step 5: Press <RST> on the EB-3191. Step 6: Continue pressing keys on the PC and see that no characters are printed on the screen. Explain why. Challenge exercise Improve the program so that it stops running when the CR (Carriage Return) character received. The ASCII code of CR is 0DH. Run the program. Press keys on the PC and check if pressing CR stops the EB-3191 program. EB-3191 – Introduction to microprocessors and microcontrollers 165 Summary questions: 1. What does the following program execute? EB-3000 + EB-3191 IOPORT WARM EQU EQU 0FF00H 0103H PROC: PROC1: ORG MOV MOVX 2100H DPTR,#IOPORT A,@DPTR MOV ANL JNZ MOV MOVX SJMP CLR MOVX LCALL END B,A A,#08H PROC2 A,B @DPTR,A PROC1 A @DPTR,A WARM PROC2: ;Load A from switches & store result ;Check S3. Stop if ON ;Restore in A ;Move A to lights ;Turn the lights OFF (a) Moves the contents of the input port to the output port. (b) Moves the number 08 to the output port. (c) Moves the contents of the input port to the output port when S3 is OFF. (d) Clears the output port. EB-3191 – Introduction to microprocessors and microcontrollers 166 2. What does the following program execute? EB-3000 + EB-3191 IOPORT PLC: (a) (b) (c) (d) EQU 0FF53H ORG LJMP ORG MOV MOVX MOV ANL CLR MOV MOVX SJMP END 2000 PLC 2100H DPTR,#IOPORT A,@DPTR C,ACC.2 C,ACC.1 A ACC.7,C @DPTR,A PLC ;SW.2 status to carry flag ;SW.2 AND SW.1 to carry flag ;Clear accumulator ;Result to LEDs Turns LED.7 according to AND of SW.0 and SW.1. Turns LED.7 according to OR of SW.0 and SW.1. Clears the LEDs except LED.7. Turns the LEDs according to the switches. EB-3191 – Introduction to microprocessors and microcontrollers 167 3. What does the following program execute? EB-3000 + EB-3191 IOPORT EQU 0FF53H CONVRT: ORG LJMP ORG MOV 2000H CONVRT 2100H DPTR,#IOPORT MOVX ANL ADD A,@DPTR A,#0FH A,#3H MOVC MOVX A,@A+PC @DPTR,A SJMP DB DB DB DB END CONVRT 30H,31H,32H,33H,34H 35H,36H,37H,38H,39H 41H,42H,43H,44H,45H 46H TABLE: (a) (b) (c) (d) ;I/O address input from switches ;Clear 4 MS bits ;Table begins 3 bytes after PC ;Read from table ;Output converted byte ;Do it again Outputs the contents of the switches to the LEDs. Outputs the ASCII codes of the switches to the LEDs. Outputs the ASCII codes to the LEDs one by one. Outputs the right 4 bits of the switches to the LEDs. EB-3191 – Introduction to microprocessors and microcontrollers 168 Part III Chapter 6 – Addresses Decoding and Memories 6.1 Timing diagrams – general Timing diagrams are the simplest and clearest method for describing signals in the time domain. A timing diagram is a graphic description of a group of signals, showing their interdependence with relation to time. A group of signals of this nature cannot be described within a conventional set of axes. A timing diagram consists of a number of sets of axes, one for each of the signals under review, each one displaying a signal with relation to time (sometimes the axes themselves are omitted and left to the reader’s imagination). The time axes of the system are parallel and are coordinated in time and scale. The origins of the axes of the whole system are positioned one beneath the other. This description enables each signal to be reviewed depending on time, and to examine its interaction with the other signals. For example, the timing diagram of a binary counter which describes the signals at the outputs, and their dependence on the two input signals – the clock input and the RESET input. QA QB QC QD CLOCK RESET Figure 6-1 EB-3191 – Introduction to microprocessors and microcontrollers 169 RESET CLOCK QA QB QC QD Figure 6-2 The Timing Diagram of a Binary Counter The symbolization used at the beginning of the signal descriptions indicates that the condition of those signals is irrelevant - they could be High or Low. In this diagram we can see that the signals are synchronized with the leading edge of the clock pulse (usually symbolized as ). The timing diagram of a microcomputer system is far more complex. In addition to the various control signals, the bus signals (DATA BUS and ADDRESS BUS) are also described in the diagram. A BUS is a group of lines and may be in a number of different states. It may carry a fixed binary number according to the program, it could be in a disconnected state, or it may carry random binary numbers (when the CPU is not using the BUS). The possible states are described in figure 6-3. '0' state '1' state Constant Binary Number '3' state Random/Undefined Binary Number Figure 6-3 Possible BUS States EB-3191 – Introduction to microprocessors and microcontrollers 170 A microcomputer system is a very fast system. The pulses of the clock signal are of a very high frequency. A problem of signal stability exists in such systems. Pulses are not quite square, and transition times have a marked significance. Usually because of the rapid rise times of the pulses, phenomena such as overshoot, undershoot and low damping may be observed. This is the reason that the operation of microcomputer systems relies on signal sampling. The designers of microprocessors and support components give much thought to the setup times of the various pulses which we will see as we go on. A common microcomputer signal looks like this: Figure 6-4 Design considerations must also take decoding times into account. The support components take time to decode the address specified on the ADDRESS BUS, and to transfer and stabilize the data from the accessed cell, onto the DATA BUS; or to prepare the accessed cell to receive data. EB-3191 – Introduction to microprocessors and microcontrollers 171 6.2 The 8051 timing diagrams The CPU is a synchronous system, which alters its condition at the transitions of the clock pulses. The 8051 has an internal clock and its frequency is determined by an external crystal. The execution of an instruction is timed by a sequence of machine cycles, each one of them composed of several clock cycles. There is a difference between a machine cycle and a clock cycle. The number of clock cycles in a given machine cycle varies according to the type of the cycle and the type of the instruction. The first machine cycle of each instruction executes the "Fetch Instruction". The control unit has to decode the fetched instruction in this cycle and execute it if it does not include an additional accessing of the memory. The CPU access to the support component in 3 stages: 1) 2) 3) The CPU indicates the address of the required component or cell on the address lines. After a period of time, which let the address to be stable and to let the decoding circuits to decode the address, the CPU operates the control line to indicate if it requires to read from or to write to the memory cell or the I/O unit. After another period of time, to let the data to be stable, the CPU collects the data from the data bus or latches it in the addressed component. Because the data is not given at the same time as the address and in order to save CPU pins, Intel prefers to use the same CPU legs to transfer address and data. These lines are called AD0-AD7. The AD0-AD7 lines serve for transferring both addresses and data at different clock times of a machine cycle. At the first clock cycle of the machine cycle, the first eight low bits of the new address (A0-A7) are delivered. A high pulse at the ALE line appears for half a cycle of the clock cycle. This pulse latches the eight low bits of the address in an external component, which is designated for this purpose and which includes latch cells (e.g., 74LS373). EB-3191 – Introduction to microprocessors and microcontrollers 172 During the next two clock cycles, the CPU outputs or inputs data on the same lines (AD0-AD7). The A8-A15 lines output the eight high bits of the address. To indicate writing in an I/O unit or in a memory cell, the CPU uses the control line WR (WR'). To indicate reading from an I/O unit or from a memory cell, the CPU uses the control line RD (RD'). The 8051 has no IO/M' line. Its I/O units are built and addressed as memory cells. The 8051 has a special read line for reading from the program memory. This line is called P S EN (Program Set Enable). A8-A15 Address High byte Address AD0-AD7 Low byte Unstable Instruction Code ALE RD' Low address byte latched Figure 6-5 Reading Timing Diagram EB-3191 – Introduction to microprocessors and microcontrollers 173 Note the following points in the timing diagram of figure 6-5: a) b) c) d) 6.3 The stage at which the ALE line latches the low byte of the address, is while it is sinking to low. The duration of its stay at the high state enables the stabilization of the address lines. The RD' line is at low, only during the stage of data transfer. The data is received by the CPU when the RD' line is going high in order to stabilize the data. The 8051 uses the P S EN line instead the RD line when it reads an object code from the program memory. When the CPU writes to a memory cell or to an output unit, it uses the WR line with similar timing diagram. Memory types The memories of a microcomputer system are divided into three major types: 1) 2) 3) Reading/Writing memories, the so called RAM (Random Access Memory). The origin of the name has historical reasons. Read only memories, called ROM (Read Only Memory). External memories. The external memories are not connected directly to the CPU. They are connected to the CPU BUS through appropriate interface systems. It is possible to read from/write into these memories. These memories are magnetic memories such as disks, diskettes, magnetic tapes, bubble memory, optical discs (CD) and so on. The external memories allow non-erasable accumulation of programs and data, namely they are not erased when the power supply of the system is shut off, and they also allow rewriting (reloading). The capacity of an external memory is very large in general. Their problems are their large physical dimensions and the need of using special drivers and interfaces for their operation. The access time to these memories is also large in comparison with the typical ROM and RAM access times. A read only memory (ROM) is a memory device, which, under the normal operation conditions of the systems, does not allow writing into it. It is only possible to read it or run programs stored in it, but not to store (new) data in it. The contents of its cells is not erase upon power shut off or failure. Hence it is used for storing permanent programs and data, which does not change during program execution. EB-3191 – Introduction to microprocessors and microcontrollers 174 Consider the following typical read only memories: a) MASK ROM – This is a read only memory whose cells content is determined by the manufacturing plant. The customer gives the required contents of the cells to the manufacturer, and the latter "writes" the contents by the addition or cancellation of electrical connections (leads) during the manufacturing process. This type of ROM's are used when the required quantities justify the expense of ordering a pre programmed ROM from the manufacturer, namely when there is a need to a large number of identical memories. For large quantities, this type of ROM is the lowest in costs. b) PROM (Programmable ROM) – The cell contents of these memories can be determined by the customer using a relatively simple special system. All the bits of the cells of a PROM being delivered by a manufacturer, are usually high. Its contents are determined by accessing its cells, address after address, and delivering a high current or high voltage pulse to selected data bits. These pulses cause burning of built in fuses, sending these bits to low (there are also PROM components delivered with all low bits, parts of which are in turn raised to high). The contents of the PROM cells, can be determined once only. It cannot be changed later on. c) EPROM (Erasable PROM) – This memory is similar to the PROM memory in that it can be programmed by the customer using a suitable programming system similar to the process for the PROM. The big difference between the two is that the EPROM cells can be erased and reprogrammed (rewritten). This difference is due to the fact that an EPROM is programmed not by blowing (opening) internal fuses, rather the high voltage pulse induces accumulation of electrical charges in the (EPROM’s) internal gates which are separated one from each other by an SiO2 layer (silicon dioxide – which is an excellent insulation material). As a result of this separation the electrical charge is not discharged and thus the data is conserved when the power of the main system is disconnected. EB-3191 – Introduction to microprocessors and microcontrollers 175 The EPROM is erased by exposing its cells to ultraviolet (uv) light (radiation). This light causes electric current conduction in the silicon dioxide, enough to discharge the accumulated charge and return the memory to its original state. For this reason, the EPROM device is manufactured with a transparent window – through which the ultra violet light illuminates the cells. The EPROM is more expensive than the ROM or PROM and serves mainly for constructing prototypes or for manufacturing systems produced in small series. d) EEPROM (Electrically Erasable PROM). It is similar to the EPROM except that it is electrically erasable rather than by uv light. The "erase" operation is executed by giving an electrical pulse, which is different than the pulse performing the programming (at present there are already EAROM's which can be erased by a 5V pulse). The advantages of such a component is it capability of storing data and programs in a system. It can be used as a ROM, whose contents may be changed. It cannot replace a RAM, as the writing process (access time) is slow in comparison to the reading process. e) FLASH – This is another type of EEPROM. The different between them is the erase method. In the EEPROM any memory cell can be erased separately and in the flash, the erasing is done in pages (usually of 512 bytes). It is done in order to save place and to contain more cells per square mm. For the user it does not matter. He can write to and read from any cell without affecting the other. The lifetime of the flah is a little short than the EEPROM, but enough for most application. Read/Write memories (RAM) are memories whose access time to a cell in reading is equal to access time to a cell in writing (as distinguished from the EAROM). The meaning of the "random access" in the name is that all cells can be accessed in the same length of time, independently of the location of the cell in the component, which is different from the situation of serial access. The read only memories are also "random access memories", but the name RAM has survived as referring to the read/write memories. Hence, when we say "RAM" we are talking of a read/write component. When the power is shut off, the data stored in the RAM is erased (lost). When the power supply is reconnected, the information in the RAM is random. EB-3191 – Introduction to microprocessors and microcontrollers 176 The RAM memories are generally subdivided into Static RAM and Dynamic RAM types. The Static RAM stores the data bits in internal filp-flops and this data is preserved as long as the power supply is connected to the system and in operation. In the Dynamic RAM, the data bits are preserved in capacitive element. In order to preserve this information, the dynamic RAM elements have to be refreshed periodically, thus preventing the discharge of the cells. Thus, unionization of dynamic RAM dictates the application of a special refreshing circuit in the system, which somewhat complicates the system. On the other hand, the dynamic RAM has a much larger data storing capability than the static RAM. Dynamic RAM is thus effective for use in very large memory systems. We can also classify the memories according to the production processes and technologies used in their manufacturing. Manufacturing technologies are a world on their own, and shall not be discussed in our book. We shall present a comparison of the salient features, which are important to the user of the diverse technologies. The most important features are – price, speed, component density in a chip and power consumption. An ideal memory component ("the best of all worlds") is a low priced, high speed, high density (large memory capacity) and low power consumption component. The selection of a real component is the result of trade-off (compromise) considerations between the various desired features, and by giving higher weight to the property that interests us most (a question of priorities). EB-3191 – Introduction to microprocessors and microcontrollers 177 6.4 Structure of the memory units In this paragraph we treat the connection to the CPU of programmable and random access memory units, such as PROM, EPROM, EAROM and RAM. These memory units are arranged in a matrix like configuration of cells so that the access time to each cell is equal, as presented by figure 6-6. Address Input Control Lines Address Cells' Array Decoder Logic Control Input/Output buffer Figure 6-6 A Memory Unit – Block diagram The number of address lines is in accordance with the number of cells. n lines produce 2n different combinations and thus enable accessing 2n different cells. For example, a memory unit of 1024 cells has 10 address lines (210=1024=1K). The number of cells varies from component to component. A binary combination of the address lines determines which cell is accessed to the data lines buffer. The accessing can be for either reading from the cell or for writing into it. The control lines determine the status of the buffer. The buffer has three possible states – output (when reading from the component), input (when writing into the component) and 3-STATE condition, when the component is not being accessed. Accordingly, the control lines are divided into two. Lines establishing READ (from the component) or WRITE (into the component) and lines which establish the component in 3-STATE or in operation condition. We shall discuss the first type of lines in the following two paragraphs. EB-3191 – Introduction to microprocessors and microcontrollers 178 The lines determining the status of the component are called CS' (Chip Select) lines. Sometimes they are marked E (enable) instead. The number of CS' lines varies from one component to another. The logic of the lines also varies. Some of them operate by positive logic and are marked CS, but most of them use negative logic and are marked CS', respectively. A component exits the 3STATE when the AND operation on the CS lines gives a high. Consider for example the component of figure 6-7: the 6264 RAM quits the 3-STATE when CS1'=low and CS2=high. In other words, CS2.CS1'=high. A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 D0 D1 D2 D3 6264 D4 D5 D6 D7 CS2 CS1' Figure 6-7 6264 RAM Memory Consider now the internal construction of the random access type of memories. The decoder described in figure 6-11 is actually made up of two decoders, thus reducing the number of outputs. A decoder with 10 incoming address lines, has to provide 1024 (210) output lines, which is a difficult technology assignment. Splitting the decoder into two decoders with 5 input lines and 32 output lines each, can be implemented with a greater ease. The cells (themselves) are organized in lines and columns. EB-3191 – Introduction to microprocessors and microcontrollers 179 The output lines of one decoder pass along the columns while the output lines of the other decoder pass along the rows in the following manner: A4 31 A5 A6 A7 A8 A9 A3 A2 A1 2 0 1 2 A0 1 0 Row lines Column line Word line Row line 31 Column lines Figure 6-8 Cells Array - Configuration An AND gate whose inputs are a column line and a row line is located at each junction where a column line crosses a row line. Its output is called a word line. There are 1024 junctions in all, hence there are 1024 word lines. The word lines arrive at the memory cells. Every word line is activated only when the suitable combination appears at the ten address lines. There is a single (and only one) combination for each word line. Each word line activates one memory cell. The common arrangement uses eight bits, and in this case the word line reaches all eight bits. The outputs of all cells flow into the data buffer through the so called "bit lines". The configuration of the cell varies according to the component type: ROM, PROM, EPROM, RAM and so on. EB-3191 – Introduction to microprocessors and microcontrollers 180 The ROM cells array consists of a matrix of diodes or a transistors matrix, inter connected as in the following figure. 0 Word 1 Lines 2 Address lines Decoders Bit lines Control lines Data Buffer Data lines Figure 6-9 A ROM Diodes Array Upon activation of word line 1, the number FFH is received at the inputs of the buffer (because all the diodes drive '1'). When word line 2 is activated, the number 24H (00100100) is received at the inputs of the buffer, in accordance with the diodes. MOSFET gates can replace the diodes, providing the same function. As mentioned in paragraph 6.3, there are four principal types of ROM: 1) 2) 3) 4) MASK ROM. PROM. EPROM EEPROM and FLASH. EB-3191 – Introduction to microprocessors and microcontrollers 181 MASK ROM – This is a ROM whose cell contents is determined by the user and is manufactured accordingly in the production plant. The manufacturer using a suitable materialization mask during the integrated circuit production process performs the connections of the diodes array. PROM (Programmable ROM) – A ROM, which can be programmed (by the user). This component arrives from the manufacturer with no information in its cells (generally the contents of all cells is FF). It is a complete diodes array, but each diode is connected to the array via a small fuse. Information is registered into this ROM by providing the data to the cells, one after the other, with a simultaneous high voltage pulse. The high voltage pulse creates a high current flow through the diodes where the "0: information is located, the fuse connected to it is blown and the data is registered. There is no possibility to change the data contents of a PROM, which has been programmed (to revert the bit state back to '1'). The data storing operation is called "burning". EPROM (Erasable PROM) – Consists of an array (matrix) of MOSFET gates, each gate structured as follows: S Select Gate Floating Gate D Si Si Source n+ Drain n+ P Silicon Oxide SiO2 Figure 6-10 Structure of an EPROM Switching Transistor This array is also burned in a similar way to the one explained above – by providing the data to the cells, one after the other, with a simultaneous high voltage pulse. EB-3191 – Introduction to microprocessors and microcontrollers 182 In a transistor with a '0' state data, the high voltage pulse causes a charge transfer from the "select gate" to the "floating gate" in the silicon dioxide. After the high pulse is terminated, this gate remains charged and prevents the transistor from conduction. [This is an enhanced n-channel transistor – an n channel is formed in the p region between the Source (S) and the Drain (D)]. When electrons are reside in the floating gate, the electrons are repelled from the channel region, the channel disappears and the transistor is no longer conducting. In order to erase the EPROM (namely to revert it back to a state with all cells containing FF and all switching transistors are cutoff) a uv light is irradiated upon the EPROM. The radiation causes the silicon dioxide (which is in principle an excellent insulation) to become conducting and the charges of the floating gate return to their original place. Thus the transistors revert to their original state until the next burning operation. This is the reason for the transparent plastic window installed on them, through which it is possible to irradiate the chip. To prevent accidental erasure of the EPROM contents, the window is covered by an opaque sticker after it has been burned. The duration of the burning process is approximately 20 minutes. It is not possible to erase a selected cell, just all the cells of the component. EB-3191 – Introduction to microprocessors and microcontrollers 183 EEPROM (Electrical EPROM) – This is an EPROM, which can be erased by an electrical procedure (hence its other name Electrically Alterable ROM). It is exactly what its names imply: Electrically Alterable. Both the storage of information and its changes are executed by an electrical manner. Actually, the information stored in it may be modified, when we write into it under high voltage. New EEPROMS exist which can be burned by voltages of only 5V. This ROM cannot serve as a RAM, because the writing cycle (duration) is much longer than the reading time. The EEPROM switching transistors are also MOSFET transistors, and are constructed as follows: Si3N4 Gate Aluminum S D P+ P+ N Figure 6-11 Structure of an EEPROM Switching Transistor The floating gate of the EPROM is replaces in the EEPROM by a silicon nitride (Si3N4) layer and an aluminum gate over it. The burning pulse results in a charge accumulation in the silicon nitride and the transistor conducts, and it is discharged by the erasing pulse. This technology is known as the NMOS technology. Note that we have here a p-channel transistor. In this case we can replace the contents of a single cell. The FLASH has the same technology of the EEPROM. The only difference is the organization of the cells the erase procedure and writing to them. When embedded microcontroller system is shut down, the power voltage goes down gradually. There is a voltage period where the CPU acts randomly and may write into the EEPROM. In order to protect from random writing, the data that should be written should follow a predetermined sequence of characters. EB-3191 – Introduction to microprocessors and microcontrollers 184 STATIC RAM – The RAM cells are made of D-F.F. The word line causes the selection of the required cell. The bit line enables reading the data in the designated cell. The bit line also enables writing data into the cell. This data remains in the cell until the next occurrence of data writing. The RAM memory contains a double system of bit lines (A data line and its complementary line, D and D', respectively). The structure of a one bit cell is as shown below. +5V Q1 Q2 Word line Bit line D 0.5V Bit line D' Figure 6-12 Static RAM Cell - Structure The D bit lines arrive at the data buffer. When a word line is selected, it gets the value '1'. If the data buffer is in the reading state and transistor Q1 is in saturation (Q2 is cutoff), a '0' appears in the D bit line. If the data buffer is in the writing state and drive a '1' in the D bit line it will drive Q2 to saturation. After this flip-flop is released (word line drops to '0'), Q2 will drive Q1 to cutoff. The next time this cell is read, we shall find the information '1' in the bit line. EB-3191 – Introduction to microprocessors and microcontrollers 185 6.5 Separating the multiplexed bus As already described in the preceding paragraphs, the 8051 has a multiplexed bus. This bus contains the AD0-AD7 lines and both addresses and data flow there at different times of the machine cycle. This method was chosen in order to better exploit the pins of the CPU. Intel produces components, which are able to discern and separate between addresses and data, and hence they may be connected directly to the CPU. We shall study such a component in the next chapter. On the other hand, separate address lines and data lines have to be provided in general for the standard support components of microprocessors, such as memory components (ROM, RAM) or ports. At the onset (beginning) of the machine cycle, the CPU outputs the low part of the address (A0-A7) on the AD0-AD7 lines. It uses the ALE (Address Latch Enable) line, which goes high, to denote that this is an address. A short while after the ALE drops to low, data shall flow in the AD0-AD7 lines from or into the CPU. In order to preserve the low part of the address also during the second part of the machine cycle, it is latched in a component called "latch". Such a components contains eight D-latch cells, having a common clock input, unto which the ALE lines is connected. The AD0-AD7 lines are connected to inputs of the cells. When the ALE line is high, the outputs of the cells receive the status of their inputs, namely the A0-A7 addresses. Upon the ALE line going low latches in the latch cell the state at the time of the drop and the A0A7 address is kept until the next rise of the ALE line to high, in the following machine cycle. The duration of time in which the ALE line stays in high enables the stabilization of the address in the lines, so that at the latching instant the data is stable. The latch cell outputs serve as the A0-A7 lines. The only signals that always appear there are the address signals. The AD0-AD7 lines emanating from the CPU and connected to the inputs of the cells, serve as the data lines of the support components. Even though address signals also appear in them, this does not interfere (with operation) because the support components receive also other signals, which tell them when to refer to the data bus. The 74373 is a (widely) accepted latch component. The separating circuit is described in figure 6-13. EB-3191 – Introduction to microprocessors and microcontrollers 186 A35 A34 A38 A33 A33 A33 A3 A3 ALE +5V CPU AD7 AD6 AD5 AD4 AD3 AD2 AD1 AD0 CLK D0 D1 D2 D3 D4 D5 D6 D7 OE VCC Q0 Q1 Q2 Q3 Q4 Q5 Q6 Q7 GND A7 A6 A5 A4 A3 A2 A1 A0 D7 D6 D5 D4 D3 D2 D1 D0 Figure 6-13 Separating the Multiplexed Bus A microprocessor system is composed of a large number of lines, which are connected to the various components. In order to avoid an electrical drawing which includes a dense network of unclear lines, it is customary to collect the lines into harnesses, as seen in the figure. This procedure forces us to denote each line by a name, according to the function of that line. EB-3191 – Introduction to microprocessors and microcontrollers 187 Experiment 6.1 – Selecting a RAM in an address range Objectives: How to connect a memory unit (RAM, ROM) to the CPU and to expand its memory. How to determine the location of a RAM in the CPU memory range. Equipment required: EB-3000 EB-3191 Banana wires Discussion: Determining a ROM unit in the addresses range We shall refer to the memory unit connected to the CPU as ONE memory unit having a defined number of cells, each cell being of eight bits. Such a unit may also be composed of several sub-units. Such a memory unit has eight data lines and n address lines, according to the number of cells. The number of cells equals 2n. Thus, a ten address lines memory unit contain 1024 (210) cells. Denoting a given binary number in the address lines addresses to the data lines the specific cell that this is its number. As pointed out in chapter 1, the support components are connected in parallel to the CPU through the data bus. Upon each call from the CPU, a single support component is connected to the data bus. The memory units include a line called chip select (CS') in order to enable such a connect/disconnect. The ' character depicts a negative logic operation procedure. EB-3191 – Introduction to microprocessors and microcontrollers 188 When the CS' line is low, the cell whose address is designated in the address lines will be connected to the data lines of the component. When the CS' line is high, even if an address is written in the address lines, the cells are disconnected from the data lines. The data lines of the component are in disconnect state known as "high impedance" or 3-STATE, the third state being neither '0' nor '1'. Besides the CS' line, most memory units have an additional line, denoted OE'. This line provides a reduced current consumption of the component, and also results in shorter decoding circuit delay times. When the CPU denotes in the address lines an address of a cell in the memory unit, some time is required for this address designation to settle down in the lines, as a result of various transitional phenomena (e.g., bouncing). The memory unit, too, requires some time until it decodes the address and sends the cell in the direction of the data outputs of the unit. The memory unit includes also a buffer at its output, which is switched when the OE' line drops to low. The CS' line goes low when the CPU accesses the memory unit. There is no point in simultaneously sending the OE' line to low because the address is not yet stabilized and the data arriving at the data buffer are still going to change. The highest current consumption of logic units is measured under their transitional conditions. The OE' line is sent to low a short while after giving the address. The RD' line or PSEN' of the 8051 is connected to the OE' line, which goes low whenever the CPU requests to read data at the memory unit. If we study the timing diagrams, we shall see that these lines go low a short while after the reading and access designation cycle has started, which is done in order to improve operation: enable the address lines to stabilize. EB-3191 – Introduction to microprocessors and microcontrollers 189 Let us describe 8K cells of 8 bits (1K=1024) EPROM memory unit, the 2764. The standard EPROM units start at the digits 27 and the other (following) digits designate the number of bits (64K bits). Such a unit is described in figure 6-14. VCC VCC A33 A33 A33 A3 A3 A7 A3 A5 A4 A8 A3 A3 A3 CS' A33 A33 A33 A3 A3 A7 A3 A5 A4 A8 A3 A3 A3 OE' D7 D6 D5 D4 D3 D2 D1 D0 D7 D6 D5 D4 D3 D2 D1 D0 GND Figure 6-14 An 8K * 8 Bit EPROM Unit In order to locate the memory unit in a given addresses range, the MSB bits which are not connected to it are decoded by a decoding circuit. EB-3191 – Introduction to microprocessors and microcontrollers 190 Let us locate the memory unit (of preceding figure) in the 8000-9FFF addresses range. In this range there are 8192 addresses. Check this. Each accessing of an address in this range shall form a combination of some sort in the A0-A12 lines, but the A13 to A15 lines shall display the number 100. 8000H = Address = within range 9FFFH = A15 A14 A13 A12 A11 A10 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 1 1 0 0 0 0 0 x 0 x 0 x 0 x 0 x 0 x 0 x 0 x 0 x 0 x 0 x 0 x 0 x 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 The decoding circuit will decode the A13-A15 lines. Its output will go low when the combination 100 appears at its input. The circuit is shown in figure 6-15. A15 A14 A13 CS' 8051 Figure 6-15 A Decoding Circuit for Identifying 100 The memory unit connected to the CS' line shall be switched only when the required combination (100) materialized in the A13-A15. EB-3191 – Introduction to microprocessors and microcontrollers 191 Locating a RAM unit in the addresses range A RAM unit is structured on the same lines as a ROM unit. Similarly, it includes an address lines for 2n cells, a CS' line and an OE' line which is connected to the output buffer. The RAM contains also an input buffer whose inputs are connected to the data bus lines and its outputs to the inputs of the output buffer. This buffer is operated through a special line, denoted WE'. These buffers (input and output) may be regarded as bi-directional buffer. OE' Memory Cell Array 8 8 8 Output Buffer 8 Input Buffer 8 8 D0-D7 WR' Figure 6-16 The RAM Buffers Upon the OE' line going low (with the WE' line in high) only the output buffer is activated and the data flows from the memory cells array to the D0-D7 data lines. When the WE' goes low (and the OE' line in high) only the input buffer is activated and the data flows from the D0-D7 data lines to the memory cells array. The WR' line of the CPU is connected to this WE' line. The RD' (or the PSEN') will be connected to the OE' line, as explained in the preceding paragraph. The CPU ensures that there shall never be a condition such that both the RD' (or PSEN') line and the WR' line will be simultaneously in low, though a condition of both being in high is possible, hence the two buffers shall never be switched ON simultaneously. EB-3191 – Introduction to microprocessors and microcontrollers 192 Locating a RAM unit in a given address range is done in a similar way to the method we employed for the ROM unit. The only difference is that the WR' line of the CPU is connected to the WE' pin of the unit. For example, connecting an 8K * 8 RAM unit (6264) to the 8000-9FFF addresses range. The decoding circuit is taken over from the example of the preceding paragraph – the ROM connection. RD' A15 A14 A13 +5V CS' A33 A33 A33 A3 A3 A7 A3 A5 A4 A8 A3 A3 A3 OE' VCC A33 A A33 A3 3A3 A7 3A3 A5 A4 A8 A 3 WE' D7 D6 D5 D4 D3 D2 D1 D0 D7 D6 D5 D4 D3 D2 D1 D0 A3 A3 GND WR' Figure 6-17 Locating RAM 6264 in an Addresses Range EB-3191 – Introduction to microprocessors and microcontrollers 193 In this experiment we are going to address the 2864 located on the EB-3191. This component constitutes an 8K*8 bits EEPROM. A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A15 WR’ RD’ 10 9 8 7 6 5 4 3 25 24 21 23 2 20 A0 A1 A2 A3 A4 A5 A6 D0 D1 D2 D3 D4 A7 D7 11 12 13 15 16 17 D5 18 D6 19 D0 D1 D2 D3 D4 D5 D6 D7 A8 A9 A10 A11 2864 A12 CS’ 27 WE’ 22 OE’ Figure 6-22 EEPROM connection of the EB-3191 The chip select of the 2864 is connected to A15. The 2864 is enabled when we address the range of 0000-7FFF. The 2864 has 13 address lines for the 8K memory cells. It means that we have double mapping of: 0000 – 1FFF 2000 – 3FFF 4000 – 5FFF 6000 – 7FFF When we write a certain contents in address 2000, we shall find it also at addresses 0000, 4000 and 6000. The OE' line of the 2864 is connected to the PSEN' line of the 8051. It means that it is used as a program memory for the 8051. We can view its contents in the Display Program window of the SES51C debugger. The WE' line of the 2864 is connected to the WR' line of the 8051. The writing to the 2864 is done using the writing commands to external momory. EB-3191 – Introduction to microprocessors and microcontrollers 194 The writing to the 2864 is not as simple as writing to a RAM. As mentioned before, the EEPROM is write-protected as default state. We must write a certain sequence of characters to open it before writing the data and to make a delay for the data to be burnt into the cells. This is done by the SES51C changing contents functions. EB-3191 – Introduction to microprocessors and microcontrollers 195 Procedure: Step 1: Connect the EB-3000 to the power supply. Step 2: Connect the power supply to the Mains. Step 3: Turn ON the trainer. The DVM screen should appear on the display. Step 4: Plug the EB-3191 into the EB-3000. Step 5: Observe the display and check that the experiment board name appear and no fault is detected. Step 6: Connect the EB-3000 to the PC with the USB cable. Step 7: Run the SES51C software by double clicking on SES51C icon on the desktop. Step 8: Check that the VP/EA switch is at VP position. Step 9: Press <RST> on the EB-3191. Step 10: Access the 2000 address, using the debugger update memory function, and enter the data '10' into it. Step 11: Continue to the next address and enter there the number '11'. Step 12: Continue in this manner up to cell 2009 and enter numbers 12 - 19. Step 13: Call Update Program memory sub-function again and check the cells 2000-2009 and verify whether the numbers 10 to 19 exist in them. You will find these numbers there. Step 14: Use the debugger Update External memory function to view the range 2000-203F. You will not find your numbers. Why? Step 15: Use the debugger Update Program memory function to view the range 4000-403F. You will find your numbers. Why? EB-3191 – Introduction to microprocessors and microcontrollers 196 Step 16: Use the debugger Update Program memory function to view the range 6000-603F. You will find your numbers. Why? Step 17: Use the debugger Update Program memory function to view the range 0000-003F. You will not find your numbers because when the switch EA/VP is at VP position, this range is in the 8051 ROM and the monitor cannot read it. Step 18: Write, assemble and download the following program, which located in the EEPROM and reads data from cell 4200 to the accumulator in an infinite loop. CHK: ORG MOV MOVX SJMP 2100H DPTR,#4200H A,@DPTR CHK Step 19: Run the program. Step 13: Connect the probe of CH1 to the CS' line of the EEPROM. You should see that the line stays low all the time. Why. Note: If you try to write to the EEPROM in your program, the 8051 will jump out of the program. This is because the writing takes time and during that the next byte of the program cannot be read. Experiment Report: 1) Copy the circuit in figure 6-22 and explain the memory range of this unit. EB-3191 – Introduction to microprocessors and microcontrollers 197 Summary questions: 1. What is the address location of the following circuit? RD' A15 A14 A13 +5V CS' A33 A33 A33 A3 A3 A7 A3 A5 A4 A8 A3 A3 A3 OE' VCC A33 A A33 A3 3A3 A7 3A3 A5 A4 A8 A 3 WE' D7 D6 D5 D4 D3 D2 D1 D0 D7 D6 D5 D4 D3 D2 D1 D0 A3 A3 GND WR' (a) (b) (c) (d) 0000-1FFF 8000-1FFF 2000-3FFF C000-FFFF EB-3191 – Introduction to microprocessors and microcontrollers 198 2. What is the address location of the following circuit? A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A15 WR’ RD’ (a) (b) (c) (d) 10 9 8 7 6 5 4 3 25 24 21 23 2 20 A0 A1 A2 A3 A4 A5 A6 D0 D1 D2 D3 D4 A7 D7 11 12 13 15 16 17 D5 18 D6 19 D0 D1 D2 D3 D4 D5 D6 D7 A8 A9 A10 A11 2864 A12 CS’ 27 WE’ 22 OE’ 0000-1FFF 2000-3FFF 4000-5FFF All of the above EB-3191 – Introduction to microprocessors and microcontrollers 199 Chapter 7 – Ports 7.1 Addressing to input / output ports The concept port refers to a unit, which serves the CPU as its interface with the outside world (of the microcomputer system). An input port receives a binary number from the outside world and transmits it to the CPU. An output port receives a binary number from the CPU and transmits it to the outside world. An output port generally contains latch cells or F.F. (Flip-Flop) cells which save the binary number at the output until the CPU accesses it again. Ports are also called Input/Output (I/O) units. The 8051 has neither special line nor any special commands for accessing the I/O units. The input and output ports are set in the memory mapping. The decoding circuit decodes the A0-A15 lines and the RD' and WR' lines in accordance with the type of the port (input or output, respectively). In general, accessing the port is performed by accessing by a cell in an external RAM. A range of addresses is selected as the I/O sector. For example, the FF00FFFF range of addresses is selected as the I/O sector for the 8051 trainers. An IORQ' (I/O ReQuest) line is formed in this case, which drops to low when it identifies that this sector has been accessed. Consider for example the circuit presented by figure 7-1. A15 A14 A13 A12 A11 A10 A9 A8 IORQ' Figure 7-1 Forming an 8051 IORQ Line EB-3191 – Introduction to microprocessors and microcontrollers 200 Experiment 7.1 – Input and Output Ports Objectives: Simple output port and its decoding circuit Simple input port and its decoding circuit EB-3191 input and output ports Equipment required: EB-3000 EB-3191 Banana wires Discussion: The EB-3191 output port The EB-3191 uses the 74LS273 as output port. This component is composed of eight single bit F.F. cells sharing a common clock input as shown by figure 7-2. D0 D1 3 11 D2 4 D3 7 D4 8 D5 13 D6 14 D7 17 18 CP CP D CP D CP D CP D CP D CP D CP D CP D Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q CLR' 1 2 Q0 5 Q1 6 Q2 9 Q3 12 Q4 15 Q5 16 Q6 VCC = Pin 20 GND = Pin 10 = Pin Numbers Figure 7-2 Description of the 74LS273 Component EB-3191 – Introduction to microprocessors and microcontrollers 19 Q7 201 The cell outputs are provided with buffers. The data lines (D0-D7) are connected to the data bus of the CPU. This output unit is a single cell unit and hence shall occupy a single address. The decoder circuit has to lower the CLK line of the 74LS273 (pin 11) to low, when the CPU is "writing" at port address. The data present at the data lines shall be transferred to the cells of the component, when this line rises to high. The delivered data shall be latched at the F.F. cells until the next writing is performed at this address. The decoder circuit must be capable of also decoding the control lines IORQ and WR'. The decoding circuit of the output port is as follows: A7 A6 A5 A4 A3 A2 A1 A0 WR' CLK D0-D7 8 8 F-F 74273 8 Q0-Q7 RST' Figure 7-3 The Output Port Decoder circuit This is a partial decoding that covers the range FF00 to FFFF. We usually address to this port using the address FF00. The output lines of the port are connected to 8 LEDs. They are also connected to the display units as described in chapter 8. EB-3191 – Introduction to microprocessors and microcontrollers 202 The EB-3191 input port The EB-3191 uses the 74LS244 as a simple (non programmable) input port. In fact it is only a buffer. It does not store the input data. The component only separates between the data lines of the microcomputer system and the outside world. It is only opened when the CPU accesses it in order to read a data from an outside system connected to its inputs. This component is composed of eight buffers, arranged in two quadruplets, where each quadruplet has a separate enable line, as depicted by figure 7-4. Lowering the enable line to low, takes the buffers out of the 3-STATE condition and enables data transfer from the input lines to the buffers' output lines. 1 20 VCC 2 19 E2' 3 18 4 17 5 16 6 15 7 14 8 13 9 12 GND 10 11 E1' Figure 7-4 Description of the 74LS244 This input unit, like the simple output port, occupies an address of one memory cell. As an example, we shall establish the address of the former output unit with the aid of a decoder circuit. EB-3191 – Introduction to microprocessors and microcontrollers 203 The CS' output of this decoder unit is connected to pins 1 and 19 of the 74LS244. This line has to drop to low when the CPU is reading from this address. The decoder circuit must also decode the RD' control line. The decoder circuit is presented below. A7 A6 A5 A4 A3 A2 A1 A0 WR' E1 D0-D7 8 E2 74244 8 J0-J7 Figure 7-5 Decoder circuit for Input Port This is also partial decoding that covers the range FF00 to FFFF. We usually address to this port using the address FF00. The input lines of the port are connected to 8 switches. They are also connected to the keyboard unit as described in chapter 9. EB-3191 – Introduction to microprocessors and microcontrollers 204 Procedure: Step 1: Connect the EB-3000 to the power supply. Step 2: Connect the power supply to the Mains. Step 3: Turn ON the trainer. The DVM screen should appear on the display. Step 4: Plug the EB-3191 into the EB-3000. Step 5: Observe the display and check that the experiment board name appear and no fault is detected. Step 6: Connect the EB-3000 to the PC with the USB cable. Step 7: Run the SES51C software by double clicking on SES51C icon on the desktop. Step 8: Check that the VP/EA switch is at VP position. Step 9: Press <RST> on the EB-3191. Step 10: Write a program that reads the switches status from the input port, and outputs it to the LEDs, in an infinite loop. IOPORT EQU ORG ; LOOP1: MOV MOVX MOVX SJMP END 0FF00H 2100H DPTR,#IOPORT A,@DPTR @DPTR,A LOOP1 Step 11: Change the condition of the switches to display the number 0F. Run the program. Do the appropriate 4 LEDs displaying the binary number for 0F light up? If not, check your program. EB-3191 – Introduction to microprocessors and microcontrollers 205 Step 12: Change the condition of the switches to different numbers. Do the correct LEDs light up, displaying the binary value of the numbers that you chose? Step 13: Connect the oscilloscope CH1 probe to the input port clock (the chip select of the input port). Step 14: Draw the port chip select signal. The EB-3000 scope is not fast enough for this signal, but you can see the chip select dropping down quite clear. Step 15: Connect the oscilloscope CH1 probe to the input port clock (the chip select of the input port). Step 16: Press <RST> on EB-3191. Experiment Report: 1) Copy the circuits in figures 7-3 and 7-5 and explain the memory range of these units. EB-3191 – Introduction to microprocessors and microcontrollers 206 Summary questions: 1. In the following circuit, in which address the data is latched in the output port? A7 A6 A5 A4 A3 A2 A1 A0 WR' CLK D0-D7 8 8 F-F 74273 8 Q0-Q7 RST' (a) (b) (c) (d) At address FF00 and the WR' line rises from '0' to '1'. At address FF00 and the WR' line is at '0'. At address 00FF and the WR' line is at '0'. At address 00FF and the WR' line rises from '0' to '1'. EB-3191 – Introduction to microprocessors and microcontrollers 207 2. In the following circuit, when is the data latched in the input port? A7 A6 A5 A4 A3 A2 A1 A0 WR' E1 D0-D7 (a) (b) (c) (d) 8 E2 74244 8 J0-J7 When the CPU address to the input port. When the data is on the input lines. It is never latched because the port is only a buffer. After the CPU reads this input port. EB-3191 – Introduction to microprocessors and microcontrollers 208 Chapter 8 – Displays 8.1 LED's and their connection to an output port The LED (Light Emitting Diode) is, as its name implies, a diode, which emits light when a current flows through it. The intensity of the light is a function of the current density through the LED. A current of 1mA to 10mA is sufficient to produce light of reasonable intensity. The LED may be connected directly to the output port, but it is better to connect it to a "driver circuit" which is operated by the port. This driver circuit may be implemented by a simple circuit (a single transistor), as in the following figure. Gold Layer RC RB To output port bit c b e Figure 8-1 A LED Driver Circuit (using transistors) The values of RC and RB are determined according to the desired current density (IC) designed to flow through the LED. Assume we wish to have a current of IC=10mA. The voltage drops across the diode and on VCE (in saturation) is approximately 1.5V. Hence, the voltage drop across RC is 3.5V RC VR C 350 IC EB-3191 – Introduction to microprocessors and microcontrollers 209 It is an accepted practice to connect an R=330 resistor when we wish to have a current of approximately 10mA, and an R=680 resistor when a 5mA current is desired. The transistor will be switched (activated) when the output byte of the port, connected to the transistor, is VOH (VOut,High), the high output voltage, regularly 3.3V for devices in logic circuits. The current Ib required to activate the transistor is calculated through min: IC 10m 0.2mA β min 50 V VBE (Sat) 3.3 0.8 RB OH 12.5K IB 0.2m IB We find RB to be approximately 10K. If RB is taken smaller than this value, the transistor enters into deep saturation. Note that switching times are not important for display components. Hence, a lower RB can be tolerated. The LED may also be activated through an integrated driver circuit, such as the 7406 or the ULN2001, as in figure 8-2. Vcc R To output port bit Figure 8-2 LED Driver Circuit (using an IC) The LED is illuminated when the bit of the output port is in high, which is the same as for the former case. EB-3191 – Introduction to microprocessors and microcontrollers 210 8.2 An image of an output port It is impossible to read the contents of most (of the available) output ports. Assume that we want to perform "a running light" effect, light advancing over the line of LED's connected to an output port. The common approach is to perform it by applying a loop. We start with lighting-up the LED on the right and provide a delay. If the port would have behaved like an accumulator, we could have simply rotate its contents to the left and return to the loop execution. If the port would have behaved like a memory cell, we could have transferred its contents to the accumulator, rotate it to the left and return it to the cell. Because it is impossible to read the contents of an output port and transfer it to the accumulator, we have no other choice but to designate a memory cell as the image of the output port. Every time a variable is transferred to the output port, it is transferred concurrently to this cell. The reading of the data (variable), in order to rotate it, shall be done from the cell. EB-3191 – Introduction to microprocessors and microcontrollers 211 Experiment 8.1 – 7-Segment display Objectives: How to operate a 7-Segment display unit through a BCD to 7Segment decoder. How to operate four 7-Segment display units through output port and decoders. How to write a program, which drives the 7-Segment units in multiplexed mode. Equipment required: EB-3000 EB-3191 Banana wires Discussion: The 7-Segment display As is well known, the 7-Segment display is made up of seven LED's forming the shape of the digit 8, and an eight LED for the decimal point. a f g b c e d D.P. Figure 8-3 Segments Pattern in the 7-Segment Unit EB-3191 – Introduction to microprocessors and microcontrollers 212 The eight LEDs share a common cathode. This common cathode is grounded. On the market there are also 7-Segment units with a common anode. The eight anodes may be connected via a driver circuit to the bit of an output port. Driving an output bit to high lights up one LED. When it is required to operate a display with several 7-Segment units, it is possible to connect each unit to a different output port. This method suffers from two gross disadvantages: 1) 2) Using a large number of output ports. High current consumption. Under this method, every unit operates all the time. The current required is the sum of all the currents serving all the units. 7-Segment display in multiplexing The accepted method of operating several display units in tandem, is to employ dynamic operation. Under this method, the eight LEDs of the display unit are connected in parallel, through a driver circuit, to the outputs of one output port. Let us denote this port a port A. A binary number appearing at the outputs of this port, actually appears at all the inputs of the 7-SEG. units. The voltage inputs of the display units, are connected through a driver circuit to an additional port – say port B (see figure 8-4). DISP 1 1 DISP 2 1 DISP 3 1 DISP 4 D.P. g f e d c b a PORT A 1 DISP 4 DISP 3 DISP 2 PORT B DISP 1 Figure 8-4 A Driver Circuit for 7-Segment Units EB-3191 – Introduction to microprocessors and microcontrollers 213 The steps of operating a display by this method are as follows: 1) 2) 3) 4) 5) 6) 7) 8) Outputting the number intended for the first display unit through port A. Closing the circuit of this unit by employing port B. A short delay sequence (it is possible to forgo this step). Disconnect the circuit from the display unit (00 to port B). Outputting the number intended for the second display unit through port A. Closing the circuit of this unit by employing port B. A short delay sequence. Disconnect the circuit from the display unit, and so on. After activating the last display unit, we return to the first display unit and so on, repeatedly. When this method is implemented, the CPU is busy all the time in running the display. This program can also be built in a manner employing a secondary sub-routine, and call on this sub-routine any time displaying a number on the display unit is required. We can use one port less and avoid the need of using the conversion table by using decoders in a configuration as shown in figure 8-5. DISP 4 DISP 3 DISP 2 DISP 1 a b c d e f g BCD to 7-SEG. 4511 DECODER Q5 Q4 Q3 Q2 Q1 Q0 OUTPUT PORT Figure 8-5 Multiplexed display (by using decoders) EB-3191 – Introduction to microprocessors and microcontrollers 214 To implement this method, the seven LED's of each display unit are connected in parallel to the output port, through a decoder called "BCD to 7-Segment" (BCD = Binary Coded Decimal, namely a binary number denoting a decimal number). A binary number arriving at the outputs of this port, is converted to 7-Segment code and appears at the inputs of all the 7-Segment units. The common line of all the 7-Segment units is connected to the second decoder. The 4511 decoder decodes a four bits binary number and drives the seven segments of the display unit commensurate with the decimal value. The second decoder drives a different display unit every time, according to the two bits binary number at its inputs. The steps of driving the display by this method are: 1) Outputting the number destined to be sent to the first display unit and activating this unit. A six bit binary number is required. 2) Outputting the number destined to be sent to the second display unit and activating this unit, and so on. When this method is employed, the computer is busy all the time just in driving the display. This program can also be constructed as a subroutine, which displays the contents of four memory cells or four variables in an array. Additional methods are available for driving a display. Some methods integrate hardware with software, others operate solely on hardware. The EB-3191 includes four 7-segement display units connected to output port (in parallel to the 8 LEDs) as in the figure 8-5. EB-3191 – Introduction to microprocessors and microcontrollers 215 Procedure: Step 1: Connect the EB-3000 to the power supply. Step 2: Connect the power supply to the Mains. Step 3: Turn ON the trainer. The DVM screen should appear on the display. Step 4: Plug the EB-3191 into the EB-3000. Step 5: Observe the display and check that the experiment board name appear and no fault is detected. Step 6: Connect the EB-3000 to the PC with the USB cable. Step 7: Run the SES51C software by double clicking on SES51C icon on the desktop. Step 8: Check that the VP/EA switch is at VP position. Step 9: Press <RST> on the EB-3191. Step 10: Move the display ON/OFF switch to ON position. The Q0-Q3 bits of the output port are connected to the inputs of a BCD to 7-Segment decoder. Q4, Q5 are connected to a decoder which determines the unit to be activated, as shown in figure 8-5. Step 11: To understand how to operate the 7-segment display, we will operate the output port directly from the debugger I/O functions. Enter the Display Terminal sub-function. EB-3191 – Introduction to microprocessors and microcontrollers 216 Step 12: Output the number 1 to the first digit, the number 2 to the second digit, the number 3 to the third digit and the number 4 to the fourth digit. *OU14,1<ENTER> *OU14,12<ENTER> *OU14,23<ENTER> *OU14,34<ENTER> Analyze these numbers. Step 13: Write a program, which performs the same. PORTA EQU ; ORG ; DISP: MOV MOV MOVX ADD MOVX ADD MOVX ADD MOVX SJMP END 0FF00H 0100H DPTR,#PORTA A,#01 @DPTR,A A,#11 @DPTR,A A,#11 @DPTR,A A,#11 @DPTR,A DISP Step 14: Assemble the program, download it and run the program. Even though activation of the display units is alternated, they all seem to be illuminated all the time. EB-3191 – Introduction to microprocessors and microcontrollers 217 Step 15: Improve the program by employing a counting loop. PORTA EQU ; ORG ; DISP: MOV MOV MOV DISP2: MOVX ADD DJNZ SJMP END 0FF00H 0100H DPTR,#PORTA A,#01 R7,#4 @DPTR,A A,#11 R7,DISP2 DISP Step 16: Assemble the program, download it and run the program. Step 17: Write a program that transfers the contents of four memory cells to the four display units, each unit receiving the contents of a different cell. PORTA EQU ; ORG ; DISP: MOV MOV MOV DISP2: MOV MOV ANL ADD MOVX MOV ADD MOV INC DJNZ SJMP END 0FF00H 0100H R0,#50H R1,#00 R2,#4 DPTR,#PORTA A,@R0 A,#0FH A,R1 @DPTR,A A,R1 A,#10H R1,A R0 R2,DISP2 DISP EB-3191 – Introduction to microprocessors and microcontrollers 218 Step18: Store different numbers in the four cells using debugger functions. Step 19: Assemble the program, download it and run the program. Check and verify that these numbers actually appear on the four display units. Experiment Report: 1) Copy the drawing in figure 8-5 and the program in step 17. Add remarks to the program and explain it. EB-3191 – Introduction to microprocessors and microcontrollers 219 Experiment 8.2 – LCD display Objectives: Liquid Crystal Display How to operate and write to LCD How to write a program, which write to LCD Equipment required: EB-3000 EB-3191 Banana wires Discussion: Liquid crystal display (LCD) The liquid crystal display is based on a specific solution contained in the gap within two glass plates. One of the glass plates is coated by a very thin gold layer, and the other plate is coated by a very thin gold leafs (foil). The gold coating are so thin that they are transparent. A liquid crystal 7-SEG. unit is shown in figure 8-6. Figure 8-6 7-SEG. Display in Liquid Crystal Gold conductors connect between the pins of the unit and the thin gold foils. The unique property of the solution is expressed by the fact that when there is an electric field across it, the molecules are arranged in a crystalline format. In this aggregate state, the solution becomes transparent. EB-3191 – Introduction to microprocessors and microcontrollers 220 Upon supplying a voltage to one of the upper foils (relative to the lower gold plate), the solution lying under it becomes transparent. If any kind of a colored background is laid under it, it will become visible. The layer becomes opaque, masking the background, when the voltage is turned off, the solutions revert to its turbid (regular) condition (hence the name "liquid crystal display"). The gold foils can be located in any desired design, and thus provide a variety of displays. One big advantage of this system stems from the fact that it does not require a current – it is voltage controlled. Its biggest drawback is that it requires external illumination, and that the user has to face it in order to see the information clearly. Modern LCD displays include an internal illumination source and special structures, which enable to discern a message at high quality, even when viewed at an angle. Dedicated alphanumeric displays are available, as well as custom graphic patterns. LCD's range from 8 characters short one line displays, to large displays of up to the size of a computer screen with 640*400 pixels (picture elements). In order to enable ease of handling when connecting an LCD display to a P system, LCD manufacturers supply the LCD unit with a compatible controller circuit, which drives the display foils. The controller circuit is adapted for connection as a support device of the CPU. It contains an internal RAM, into which the data is written. Each RAM byte represents one alphanumeric representative display item. The device includes also a dedicated decoding circuit, known as the Character Generator (CG). The CS translates the binary number supplied by the byte into suitable binary numbers for the various columns of the display units belonging to this byte. Consider the connection of the following highly popular LCD display unit, which is manufactured by many subcontractors, and which is available in many and diversified configurations. The method of connection is identical in all cases, and is not dependent on the number of the display units it contains. EB-3191 – Introduction to microprocessors and microcontrollers 221 The unit occupies two I/O addresses. The various control commands are written into the lower address. Data is written into, or read from, the higher address. Assume for example that we wish to introduce (write) a given variable into a specific cell of the internal RAM. The address of the cell is specified in the command to the lower address, and then the variable is written into the higher address. The following figure represents the block diagram of the unit. VDD R/W' LCD E RS DB0-DB7 8 VL Controller RL SOK Driver VSS Figure 8-7 LCD Display – Block Diagram The DB0-DB7 lines are the LCD data lines. As noted, the component occupies two addresses in the memory. RS denotes whether we are accessing the high address or the low one. The R/W' line denotes if we are writing into the device or reading from it. Writing into the COMMAND register is done when RS is low and into the DATA register when RS is high. We can give up the reading functions from the LCD. We can use a RAM image of the needed data in the 8051 RAM and read it from there. The LCD needs time to perform the commands and the display. We can read its status and wait while the LCD controller is busy. Instead of that, we can replace this reading status and waiting with a short delay. EB-3191 – Introduction to microprocessors and microcontrollers 222 The following diagram is the timing diagram of the device. DATA READ RS 2.2V 2.2V 0.6V 0.6V tAS tH 2.2V 2.2V R/W tH PWEH 2.2V E 2.2V 0.6V 0.6V tE tDDR tE 0.6V tH 2.4V DB0-DB7 0.4V 2.4V Valid Data 0.4V tCYC DATA WRITE RS R/W 2.2V 2.2V 0.6V 0.6V tAS tH 0.6V 0.6V tH PWEH tE 2.2V E 2.2V 0.6V 0.6V 0.6V tE tDSW tH 2.4V DB0-DB7 0.4V Valid Data 2.4V 0.4V tCYC Figure 8-8 LCD Display – Timing Diagram EB-3191 – Introduction to microprocessors and microcontrollers 223 The LCD on EB-3191 is controlled by output ports. The R/W' line is connected constantly to GND. We just write to the LCD without reading. The LCD data lines DB0-DB7 are connected to the output port of the board. The LEDs show the data that we are writing into the LCD. The E and the RS lines are controlled by P1 (port 1 of the 8051) bits. The E is connected to P1.1 and the RS is connected to P1.2. The LCD is initiated by the following data string of numbers to its command register: 38H, 38H, 08H, 01H, 06H, 0CH This string clears also the screen and turn on the cursor. Writing 80H into the command register, brings the cursor to the beginning of the LCD upper line. Writing C0H into the command register, brings the cursor to the beginning of the LCD lower line. EB-3191 – Introduction to microprocessors and microcontrollers 224 Procedure: Step 1: Connect the EB-3000 to the power supply. Step 2: Connect the power supply to the Mains. Step 3: Turn ON the trainer. The DVM screen should appear on the display. Step 4: Plug the EB-3191 into the EB-3000. Step 5: Observe the display and check that the experiment board name appear and no fault is detected. Step 6: Connect the EB-3000 to the PC with the USB cable. Step 7: Run the SES51C software by double clicking on SES51C icon on the desktop. Step 8: Check that the VP/EA switch is at VP position. Step 9: Press <RST> on the EB-3191. Step 10: Observe the following program that print 'HELLO' on the upper line of the LCD and analyze it. EB-3191 – Introduction to microprocessors and microcontrollers 225 PORTA WARM EN RS ; IINIT: EQU EQU EQU EQU 0FF00H 0103H 91H 92H ORG CLR CLR MOV LCALL MOV LCALL MOV LCALL MOV LCALL MOV LCALL MOV LCALL MOV LCALL MOV LCALL 2100H EN RS A,#38H WRITE A,#38H WRITE A,#38H WRITE A,#08H WRITE A,#01H WRITE A,#06H WRITE A,#0CH WRITE A,#80H WRITE MOV MOV CLR MOVC SETB LCALL INC DJNZ LCALL DPTR,#TABLE R7,#5 A A,@DPTR+A RS WRITE DPTR R7,NEXT WARM PUSH PUSH MOV DJNZ MOV MOVX SETB CLR MOV DJNZ POP POP RET DPH DPL R6,#200 R6,DELAY1 DPTR,#PORTA @DPTR,A EN EN R6,#200 R6,DELAY2 DPL DPH DB END 'HELLO' ;P1.1 ;P1.2 ;for addressing COMMAND register ;clear LCD ;turn cursor ON ;blink cursor ;move cursor to upper line ; NEXT: ; WRITE: DELAY1: DELAY2: ; TABLE: ;string address ;5 characters to send ;for addressing DATA register ;return to monitor Step 11: Write the program. EB-3191 – Introduction to microprocessors and microcontrollers 226 Step 12: Assemble the program, download it and run the program. Step 13: Check that the word HELLO appears on the upper line. Step 14: Change the program so the word HELLO appears in the center of the lower line. Step 15: Write different messages on the LCD. Experiment report: 1) Copy figure 8-7 and adapt it to the way it is connected in 3191. 2) Copy the program in step 10 and explain each stage. EB-3191 – Introduction to microprocessors and microcontrollers EB- 227 Summary questions: 1. In the following circuit, what should be the HEX number written in the output port in order to display the number 2 in DISP 3? DISP 4 DISP 3 DISP 2 DISP 1 a b c d e f g BCD to 7-SEG. 4511 DECODER Q5 Q4 Q3 Q2 Q1 Q0 OUTPUT PORT (a) (b) (c) (d) 02H 12H 42H 32H EB-3191 – Introduction to microprocessors and microcontrollers 228 2. According to the DATA WRITE diagram of the LCD, when is the data written into the LCD? DATA WRITE RS R/W 2.2V 2.2V 0.6V 0.6V tAS tH 0.6V 0.6V tH PWEH tE 2.2V E 2.2V 0.6V 0.6V 0.6V tE tDSW tH 2.4V DB0-DB7 0.4V 2.4V Valid Data 0.4V tCYC (a) (b) (c) (d) When R/W' is low. When R/W' is high. When E is high. When E goes from high to low. EB-3191 – Introduction to microprocessors and microcontrollers 229 Chapter 9 – Switches and Keys Experiment 9.1 – Identifying a key being pressed Objectives: How to write a program that reads switches and identifies the switch being operated. Equipment required: EB-3000 EB-3191 Banana wires Discussion: Reading switches status and identifying the switch being pressed The connection of switches to an input port was exercised in chapter 3, where we also learned how to read the status of the switches and transfer the data to an output port, which outputs it to the LED's. In order to react on the activation of any switch, it is necessary to identify in the binary number received from the switches, when the respective bit is going to high ('1'). The test is performed through the "AND" logic operation. Consider for example that bit D1 (the second bit) has to be checked and that the number is located in the accumulator. An AND operation is executed upon the accumulator using the immediate accessing mode, [AND] with the 00000010 binary number. The zeroes shall enforce the respective bits of the accumulator to go low ('0'), regardless of any previous value. The D1 bit is the only bit that shall remain at its previous state (value). EB-3191 – Introduction to microprocessors and microcontrollers 230 If the accumulator contains a zero following this operation, then D1 was '0'. If a number different from zero exists in the accumulator, then D1 was '1'. The check of the status of the bits shall be done according to the JZ or JNZ instructions. Let us write a program, which outputs the number of the switch being pressed to the output LED. Pressing the fourth switch, for example, results in the display of number 04H at the output lights (not the number 08H which would have appeared there if the state of the switches would have been sent directly to the output). The AND operation changes the contents of the accumulator. Hence it is required to preserve the contents of the accumulator in a register and to freshly reload the accumulator after each operation. A suitable program is described in flow chart A. Note that this program checks eight switches, one after the other, in an infinite loop. Consider what shall happen when two switches are operated simultaneously. The aim of this experiment is to read the status of switches on the trainer and to identify the switch being pressed, by transferring its serial number to the output LEDs. EB-3191 – Introduction to microprocessors and microcontrollers 231 The algorithm of the program is based on the following "Flow Chart C": Flow Chart C Read switches 8 counter 01 B Rotate A right through carry If CY 0 Yes No B+1B Counter – 1 counter Yes Count 0 No Jump B output EB-3191 – Introduction to microprocessors and microcontrollers 232 Procedure: Step 1: Connect the EB-3000 to the power supply. Step 2: Connect the power supply to the Mains. Step 3: Turn ON the trainer. The DVM screen should appear on the display. Step 4: Plug the EB-3191 into the EB-3000. Step 5: Observe the display and check that the experiment board name appear and no fault is detected. Step 6: Connect the EB-3000 to the PC with the USB cable. Step 7: Run the SES51C software by double clicking on SES51C icon on the desktop. Step 8: Check that the VP/EA switch is at VP position. Step 9: Press <RST> on the EB-3191. Step 10: Observe the following program that implement flow chart C and analyze it. PORTA WARM ; ; SWTCH: SWTCH2: ; SWTCH3: EQU EQU 0FF00H 0103H ORG 2100H MOV MOVX MOV MOV RRC JC INC DJNZ SJMP DPTR,#PORTA @DPTR,A R7,#8 R6,#1 A SWTCH3 R6 R7,SWTCH2 SWTCH MOV MOVX SJMP END A,R6 @DPTR,A SWTCH EB-3191 – Introduction to microprocessors and microcontrollers 233 Step 11: Write the program. Step 12: Assemble the program, download it and run the program. Step 13: Change the status of the switches and verify that the number of the switch being turned ON does actually appear at the output LEDs. Step 14: Examine and write the result. Step 15: Check what happens when two switches are turned ON? Step 16: We will improve the program (underlined) to output the switch number only after the switch is dropped back down. After identifying the one switch is ON, the program calculates its number, waiting until the switch will be OFF again and then output its number. PORTA WARM ; ; SWTCH: SWTCH2: ; SWTCH3: ; SWTCH4: EQU EQU 0FF00H 0103H ORG 2100H MOV MOVX MOV MOV RRC JC INC DJNZ SJMP DPTR,#PORTA A,@DPTR R7,#8 R6,#1 A SWTCH3 R6 R7,SWTCH2 SWTCH MOV MOVX A,R6 @DPTR,A MOVX JNZ A,@DPTR SWTCH4 SJMP END SWTCH ; Step 17: Run the program in an infinite loop. Step 18: Alter the status of the switches and verify that the number of the switch being turned ON does actually appear at the output LEDs. EB-3191 – Introduction to microprocessors and microcontrollers 234 Experiment Report: 1) Copy the program in step 16, add remarks and explain each stage. 2) Explain what happens when two switches are raised. EB-3191 – Introduction to microprocessors and microcontrollers 235 Experiment 9.2 – Scanning momentary switches Objectives: The switch bounce problem. How to overcome switch bounce with software. Equipment required: EB-3000 EB-3191 Banana wires Discussion: Scanning momentary switches A momentary switch is a switch possessing a regular state (close or open) and a momentary one – the complement of the regular state. When the switch is pressed, it switches to this complement state and remains in it until it is released. A computer's keyboard keys are an example of momentary switches. For our convenience, let us assume that the regular state is the low one and the momentary state is the high one. In order to react on an operation of a key, the rise of the key to high has to be checked and to operate according to the function of the key being pressed. Pressing a character – key of a computer keyboard, causes the display of the character on the monitor. The reaction of the computer to the key going high is terminated before the key drops to low (the computer is faster than our finger). In such a case, the computer continues to scan the keys and if it finds the key still in high, it reacts again (and again…) and thus we receive a line of character resulting from our single pressing of a key. A simple solution to this problem (there are also other solutions) is to record that a given key has gone high but to react only after it has returned to low. EB-3191 – Introduction to microprocessors and microcontrollers 236 The purpose of this experiment is to observe the switch bounce phenomenon. This experiment will be based on reading the status of the switches of the EB3191 and identifying the switch being pressed, just as in experiment 9.1. However, instead of transferring the numbers of the switches being pressed to the LEDs, we now transfer them to a table, one after the other, according to the following "Flow Chart D". Flow chart D Table Address to IX (IndeX register) Read switches to A 8 counter 01 B Rotate right A through carry CY 0 Yes No B output B+1B B (IX) IX + 1 IX Counter – 1 counter 1 Yes Count = 0 Read switches to A No Compare A with 0 Jump Yes A 0 No EB-3191 – Introduction to microprocessors and microcontrollers 2 237 Debouncing (canceling key bouncing) The bouncing problem is common to all switches. It is expressed in every key transition action. When a key is pressed, its contacts bounce (make/break the connection) several times until they stabilized in the new state. Bouncing occurs similarly on key disconnect action. If we would have run the program of the previous paragraph (flow chart B) as it was written, we shall discover that pressing a key once causes several instances of its serial number being recorded in the table. The computer is faster than the settling time of the switch. Two methods - one through the hardware and the other with software – are available for solving this problem. The method of solving the problem by hardware is based on connecting a flipflop to every key, as described in figure 9-1. A Q B Figure 9-1 A Debouncing Circuit for a Switch If the gates are of the TTL type, an open input terminal is a '1'. If CMOS logic is used, inputs A and B have to be connected to VCC through pull-up resistors. During the transition interval, the bouncing effects occur between the contacts (A or B) and the gap, but not between the A and B contacts themselves. For the state of affairs shown in the figure, B in '0' and A in '1', hence Q (for this case) is in '0'. During the switch transition interval, terminal B alternates between open and close. Terminal A remains in '1' throughout this interval, while B bounces. EB-3191 – Introduction to microprocessors and microcontrollers 238 Even though B oscillates between '0', '1' and back to '0' several times, Q remains unchanged (test and verify it). Only when A is short circuited to ground, for the first time, Q changes its status to '1'. Similarly, additional bouncing of A shall not cause any change of Q, which shall remain in '1' until B is short circuited to ground once more. All this is the outcome of the feedback existing between the gates. This solution of the problem is of course one with high costs. It requires the use of changeover switches and connection of an electronic circuit for each individual key. Consider the following two methods for solving the problem by software application. The first one is based on sampling a series of data from the keys. Only when it is observed that a continuous series of samples provides the same state, the action dictated by the change of state is taken. In this method we consider only the stabilized states of the switches, not their bouncing ones. The other method is simpler, yet relatively reliable. This method is based on adding a delay loop, for a longer duration than the bouncing times, after every instant at which a change of status is detected. This method requires that we know the duration of the bouncing times of the switch. Providing exaggerate long times is not desirable, as then fast (sequential) press operations shall not be detected. The delay loops shall be added at the junctions marked 1 and 2 in flow chart D. EB-3191 – Introduction to microprocessors and microcontrollers 239 Procedure: Step 1: Connect the EB-3000 to the power supply. Step 2: Connect the power supply to the Mains. Step 3: Turn ON the trainer. The DVM screen should appear on the display. Step 4: Plug the EB-3191 into the EB-3000. Step 5: Observe the display and check that the experiment board name appear and no fault is detected. Step 6: Connect the EB-3000 to the PC with the USB cable. Step 7: Run the SES51C software by double clicking on SES51C icon on the desktop. Step 8: Check that the VP/EA switch is at VP position. Step 9: Press <RST> on the EB-3191. Step 10: Observe the following program that implement flow chart C and analyze it. Step 11: Write a program for "FLOW CHART D", while you assign an initial address for the table. To this address the program shall transfer the numbers of the switches being pressed. Disregard POINT1 and POINT2 in the program. They will be explained later. EB-3191 – Introduction to microprocessors and microcontrollers 240 PORTA WARM ; ; BOUNCE: BOUNCE2: BOUNCE3: ; BOUNCE4: POINT1: BOUNCE5: EQU EQU 0FF00H 0103H ORG 2100H MOV MOV MOVX MOV MOV RRC JC INC DJNZ SJMP R0,#50H DPTR,#PORTA A,@DPTR R7,#8 R6,#1 A BOUNCE4 R6 R7,BOUNCE3 BOUNCE2 MOV MOV INC MOVX A,R6 @R0,A R0 @DPTA,A MOVX JNZ A,@DPTR BOUNCE5 SJMP END BOUNCE2 POINT2: Step 12: Assemble the program, download it and run the program. Step 13: Turn ON one switch at a time and turn it OFF. Keep a record (for your own use) of the order by which the switches were turned. Step 14: Press <RST> to stop the program. Step 15: Access the table by the debugger Display function and check whether the numbers stored match the order in which the switches were operated. Step 16: There is a reasonable probability, that for each key operation, you received its serial number several times. Explain why. Step 17: Improve the program in order to eliminate the phenomenon described in step 16. EB-3191 – Introduction to microprocessors and microcontrollers 241 Add delay loops (underlined) at POINT1 and POINT2 in the program. Start by introducing very short delay loops. POINT1: BOUNCE5: POINT2: ; DELAY: DELAY2: DELAY3: LCALL MOVX JNZ LCALL SJMP DELAY A,@DPTR BOUNCE5 DELAY BOUNCE2 MOV MOV DJNZ DJNZ RET END R7,#2 R6,#80H R6,DELAY3 R7,DELAY2 Step 18: Run the program and check whether the computer still reacts to the bouncing of switches. Step 19: If positive, increase the delay and repeat step 12, until you succeed in eliminating the computer's reaction to bouncing of the switches. Step 20: Record how many delay loops you need to eliminate the switch bounce phenomenon. Experiment Report: 1) Copy the program in step 11, add remarks and explain each stage. 2) Explain what happens when two switches are raised. 3) Why haven't we seen the bouncing problem in the previous experiment? EB-3191 – Introduction to microprocessors and microcontrollers 242 Experiment 9.3 – Connecting a keyboard in a matrix Objectives: How to connect a keyboard in a matrix to I/O ports. How to write a program to scan the keys and to identify the key being pressed. Equipment required: EB-3000 EB-3191 Banana wires Discussion: The keyboard The key scanning methods described on the previous experiment specified the connection of each switch to a bit of a port. This requires the use of N/8 input ports, where N is the number of keys. A keyboard contains numerous keys, and such a scanning method is a wasteful method. A 64 keys (full) keyboard, for example, requires the use of eight ports and a large number of wires. In order to overcome the necessity of connecting an input port for every 8 keys, the keyboard is arranged in a matrix of columns and rows, and an input port and an output port are used. The following example describes the configuration of a 16 keys array. In order to operate this array, we need two output port bits and eight input port bits. One may also use four output bits and four input port bits. Consider the first of these two configurations. EB-3191 – Introduction to microprocessors and microcontrollers 243 In this experiment we are going to use a 16 key matrix connected (in parallel to the 8 switches) to the input port and to write a program, which identifies the key being pressed. INPUT PORT Q7 Q6 Q5 Q4 Q3 Q2 Q1 Q0 OUTPUT PORT A Figure 9-2 Configuring a 16 Keys Matrix The principle of key scanning is based on the following algorithm: a) b) c) d) e) f) Output '0' to the Q7 line of the output port. Scan the input lines of the input port according to Flow Chart B (see experiment 9.2). If none of the keys in this line is pressed, all inputs shall be '1'. If one of the keys in this line is pressed, a '0' is received at its line. Go to subparagraph (f). Output a '0' to line Q6 of the output port. Repeat subparagraph (b) and (c). The number of the key being pressed is (given by) the number of the line in the output port connected to the key being pressed times eight (8), plus the number of the line in the input port at which the '0' appears. EB-3191 – Introduction to microprocessors and microcontrollers 244 It is easy to see in Figure 9-2, the method of expanding the keyboard to 64 keys by adding additional key lines. The circuit in EB-3191 is very similar to the circuit in figure 9-2 with one difference. The line control is P1.0 of the 8051 port 1 and NOT gate. INPUT PORT P1.0 Figure 9-3 Configuring a 16 Keys Matrix EB-3191 – Introduction to microprocessors and microcontrollers 245 Procedure: Step 1: Connect the EB-3000 to the power supply. Step 2: Connect the power supply to the Mains. Step 3: Turn ON the trainer. The DVM screen should appear on the display. Step 4: Plug the EB-3191 into the EB-3000. Step 5: Observe the display and check that the experiment board name appear and no fault is detected. Step 6: Connect the EB-3000 to the PC with the USB cable. Step 7: Run the SES51C software by double clicking on SES51C icon on the desktop. Step 8: Check that the VP/EA switch is at VP position. Step 9: Press <RST> on the EB-3191. Step 10: The 16 keys matrix, organized in 2 * 8 array, is connected to the input port and controlled by P1.0 as described in figure 9-3. Write a program in accordance with the algorithm above. This program shall output the number of the switch (0-F) being pressed to the 7-Segment display unit. Step 11: Observe and analyze the following program. EB-3191 – Introduction to microprocessors and microcontrollers 246 PORTA P10 WARM ; ; KEB: KEB1: EQU EQU EQU 0FF00H 90H 0103H ORG 2100H MOV SETB MOVX CJNE DPTR,#PORTA P10 A,@DPTR A,#0FFH,KEB2 CLR MOVX CJNE SJMP P10 A,@DPTR A,#0FFH,KEB3 KEB1 LCALL SJMP LCALL ADD MOVX SJMP CNVRT KEB4 CNVRT A,#8 @DPTR,A KEB1 MOV RRC JNC INC SJMP MOV RET B,#1 A CNVRT3 B CNVRT2 A,B ;P1.0 ; ; KEB2: KEB3: KEB4: ; CNVRT: CNVRT2: CNVRT3: ; END Step 12: Assemble the program, download it and run the program. Step 13: Activate several keys and check the results at the output. Experiment Report: 1) Copy the circuit in figure 9-3 and the program in step 11. Add remarks to the program and explain each stage. EB-3191 – Introduction to microprocessors and microcontrollers 247 Summary questions: 1. What does the following program execute? PORTA WARM ; ; SWTCH: SWTCH2: ; SWTCH3: (a) (b) (c) (d) 2. EQU EQU 0FF00H 0103H ORG 2100H MOV MOVX MOV MOV RRC JC INC DJNZ SJMP DPTR,#PORTA @DPTR,A R7,#8 R6,#1 A SWTCH3 R6 R7,SWTCH2 SWTCH MOV MOVX SJMP END A,R6 @DPTR,A SWTCH Outputs the number of the switch that is ON. Outputs the number of the switch that is OFF. Transfers the switches to the LEDs. Waits for the number 80H on the switches. In the above program, when two switches are ON, the number of which switch will be displayed? (a) (b) (c) (d) The right one. The left one. Both of them. None of them. EB-3191 – Introduction to microprocessors and microcontrollers 248 3. In the keyboard circuit of EB-3191, what causes only the keys being scanned to affect the reading? INPUT PORT P1.0 (a) (b) (c) (d) The NOT gate. The pull-up resistors. The diodes. The input port. EB-3191 – Introduction to microprocessors and microcontrollers 249 Chapter 10 – D/A and A/D Converters Experiment 10.1 – Operating a DAC Objectives: Parallel and serial DACs. How to deliver a number to the DAC and to see it converted into an analog signal (voltage). How to write a program that reads a binary number from the switches and outputs it to the DAC. How to write a program that creates an analog signal (such as a triangle wave) at the output of the serial DAC. Equipment required: EB-3000 EB-3191 Banana wires Discussion: Implementing a DAC with an operational amplifier & a resistor network A digital to analog converter is a circuit receiving any binary number at its inputs and outputting an electric voltage (signal) at its outputs. The binary number is made of binary digits (bits) which can assume the value of either logic '0' or '1', where '0' equals 0V and '1' equals a given reference voltage – VR. Throughout this book, we use the following three terms (for each converter) as completely equivalent synonyms: DAC, D/A, D to A – for Digital to Analog Converters. ADC, A/D, A to D – for Analog to Digital Converters. EB-3191 – Introduction to microprocessors and microcontrollers 250 A DAC circuit is generally constructed by an operational amplifier and a resistor network, as shown in figure 10-1. R +V R 2R 4R 8R 16R 32R 64R 128R V7 V6 V5 V4 V3 V2 V1 V0 Vo + -V R Figure 10-1 A DAC Implemented by an Operational Amplifier & a Network of Binary Weighted Resistors Calculating the output voltage Vo as a function of V0-V7: R V7 R Vo R 2R V6 R V5 4R R 8R V4 R 16R V3 R V2 32R R 64R V1 R 123R V0 Divide throughout (reducing the fractions) by R: 1 1 1 1 1 1 1 Vo ( V 7 V 6 V5 V 4 V 3 V 2 V1 V 0) 2 4 8 16 32 64 128 Divide and multiply by 128: Vo 1 (128V 7 64V 6 32V 5 16V 4 8V 3 4V 2 2V1 1V 0) 128 If each voltage input equals the reference voltage times the value of the bit connected to it ('0' or '1'): VI VR DI EB-3191 – Introduction to microprocessors and microcontrollers 251 We get: Vo 1 ( 128VR D 7 64VR D 6 32VR D 5 16VR D 4 8 VR D 3 4 VR D 2 2 VR D1 VR D 0 ) 128 Hence: Vo 1 VR (128D7 64D6 32D5 16D4 8D3 4D2 2D1 1D0) 128 Thus we get the output voltage whose absolute value is a function of the binary number being fed to the inputs of the circuit. The factor of this circuit 1 equals 128 VR. The voltage at the output of the circuit equals the decimal value of the binary number, multiplied by VR and multiplied by a factor (the factor being a function of the circuit). Assume for example that the binary number is 01001110, which equals 7810, the reference voltage is 5V and the factor determined by the circuit is 0.01. The voltage at the output of the circuit would be: Vo 0.01 5 78 0.05 78 3.9V The output voltage has a negative value. In order to receive a positive voltage value an inverter (amplifier) may be connected to the output of the circuit. It is also possible to provide the circuit with a given gain, in order to change the general factor of the circuit. The accuracy of the resistors is a significant item in DAC circuits. The problem in such circuits is the result of having to use resistors of different values which never the less must maintain high accuracy of the ratios between them, as described in the figure. Hence, assembling an accurate circuit of this kind is a difficult and expensive task. However, accurate resistor networks in a single package (hence – similar performance under environmental conditions) may be purchased. EB-3191 – Introduction to microprocessors and microcontrollers 252 A monolithic DAC A monolithic DAC is a digital to analog converter constructed on a single chip. This is done by manufacturing an integrated circuit containing the resistors network, the operational amplifier and diverse compensation circuits. There are many types of DAC's in the market. The major differences being in their resolution (the number of bits of the binary number), response speed and accuracy. Mostly, the device outputs a current, which is a function of the binary number at its inputs. The operational amplifier converts these currents to voltages in the designated range. The inputs of the DAC are connected to the outputs of the output port. The DAC 0830 connection mode is depicted in figure 10-3. +12V +5V 14 3K 1K 1.6K 15 1 D7 IOUT1 3 RFB IOUT2 DAC 0830 4 +12V S5 7 - 2 4 + 6 3 IO' WR' D6 D5 D4 D3 D2 D1 D0 IE WR' 2 -12V GND Aout Figure 10-2 A 0-5V DAC Circuit Implemented by the DAC 0830 The potentiometer located at the input of the operational amplifier is used for calibrating its gain in order to obtain the required range. Usually, pin 15 is grounded and a filtered and regulated voltage supply is connected to pin 14. EB-3191 – Introduction to microprocessors and microcontrollers 253 When it is required to operate a given (selected) device, the required current is usually higher than the current which can be supplied by the operational amplifier. An amplifier in a circuit as shown by figure 10-4 is added to the circuit in such cases. IL IB DAC RL Figure 10-3 DAC and Current Amplifier Circuit The DAC supplies current IB {equal to IL/(B+1)} to the transistor. If higher current gain is required, a Darlington circuit can be added in series. A controlled power supply can be realized by a similar configuration. We get a more accurate circuit if we connect the feedback resistor to the load and not to the transistor base as follows: RF + IO DAC + V RL Figure 10-4V An interesting application of a DAC is its integration as a P controlled amplifier for AC power. An AC voltage, amplified to the maximum value (without distortion, of course) is connected to the VREF input. The DAC output shall then be an AC voltage source whose value is a function of the binary number at its input. EB-3191 – Introduction to microprocessors and microcontrollers 254 The DAC circuit includes a trimmer-potentiometer, serving to calibrate the operational amplifier once. When the DAC receives 00 at its inputs, the operational amplifier delivers 0V. When the DAC receives FF at its inputs, the operational amplifier delivers 5V. AD 7303 8-bit serial input dual voltage DAC The AD7303 is a dual, 8-bit voltage out DAC that operates from a single +2.7V to +5.5V supply. Its on-chip precision output buffers allow the DAC outputs to swing rail to rail. This device uses a versatile 3-wire serial interface that operates at clock rates up to 30MHz, and is compatible with QSPI, SPI, microwire and digital signal processor interface standards. The serial input register is sixteen bits wide; 8 bits act as data bits for the DACs, and the remaining eight bits make up a control register. The on-chip control register is used to address the relevant DAC, to power down the complete device or an individual DAC, to select internal or external reference and to provide a synchronous loading facility for simultaneous update of the DAC outputs with a software LDAC function. AD7303 Input Register DAC Register I DAC A I/V VOUT A Input Register DAC Register I DAC B I/V VOUT B Control (8) 8 Data (8) DIN SCLK SYNC Power On Reset MUX 16-bit Shift Register :2 REF GND VDD Figure 10-5 EB-3191 – Introduction to microprocessors and microcontrollers 255 The AD7303 is a dual 8-bit voltage output digital-to-analog converter. The architecture consists of a reference amplifier and a current source DAC, followed by a current-to-voltage converter capable of generating rail-to-rail voltages on the output of the DAC. Figure 10-6 shows a block diagram of the basic DAC architecture. VDD 30K REF Reference Amplifier + - AD7303 11.7K Current DAC 11.7K Vo A/B + 30K Output Amplifier Figure 10-6 DAC Architecture Both DAC A and DAC B outputs are internally buffered and these output buffer amplifiers have rail-to-rail output characteristics. The output amplifier is capable of driving a load of 10K to both VDD and ground and 100pF to ground. The reference selection for the DAC can be either internally generated from VDD or externally applied through the REF pin. Reference selection is via a bit in the control register. The range on the external reference input is from 1.0V to VDD/2. The output voltage from either DAC is given by: Vo A/B 2 VREF (N/256) V Where: VREF is the voltage applied to the external REF pin or VDD/2 when the internal reference is selected. N is the decimal equivalent of the code loaded to the DAC register and ranges from 0 to 255. EB-3191 – Introduction to microprocessors and microcontrollers 256 Analog outputs: The AD7303 contains two independent voltage output DACs with 8-bit resolution and rail-to-rail operation. The output buffer provides a gain of two at the output. The slew rate of the output amplifier is typically 8 V/s and has a full-scale settling to 8 bits with a 100pF capacitive load in typically 1.2s. The input coding to the DAC is straight binary. The following table shows the binary transfer function for the AD7303. Any DAC output voltage can ideally be expressed as: VOUT 2 VREF (N/256) Where: N is the decimal equivalent of the binary input code. N ranges from 0 to 255. VREF is the voltage applied to the external REF pin when the external reference is selected and is VDD/2 if the internal reference is used. Digital Input MSB . . . LSB 11111111 11111110 10000001 10000000 01111111 00000001 00000000 Analog Output 2 x 255/256 x VREF V 2 x 254/256 x VREF V 2 x 129/256 x VREF V VREF V 2 x 127/256 x VREF V 2 x VREF/256 V 0V EB-3191 – Introduction to microprocessors and microcontrollers 257 Serial interface: The AD7303 contains a versatile 3-wire serial interface hat is compatible with SPI, QSPI and Microwire interface standards as well as a host of digital signal processors. An active low SYNC enables the shift register to receive data from the serial data input DIN. Data is clocked into the shift register on the rising edge of the serial clock. The serial clock frequency can e as high as 30MHz. This shift register is 16 bits wide. The first eight bits are control bits and the second eight bits are data bits for the DACs. Each transfer must consist of a 16-bit write or two 8-bit writes. SPI and Microwire interfaces output data in 8-bit bytes and thus require two 8-bit transfers. In this case the SYNC input to the DAC should remain low until all sixteen bits have been transferred to the shift register. QSPI interfaces can be programmed to transfer data in 16-bit words. After clocking all sixteen bits to the shift register, the rising edge of SYNC executes the programmed function. The DACs are double buffered which allows their outputs to be simultaneously updated. Input shift register description: The input shift register is 16 bits wide. The first eight bits consist of control bits and the last eight bits are data bits. EB-3191 – Introduction to microprocessors and microcontrollers 258 Procedure: Step 1: Connect the EB-3000 to the power supply. Step 2: Connect the power supply to the Mains. Step 3: Turn ON the trainer. The DVM screen should appear on the display. Step 4: Plug the EB-3191 into the EB-3000. Step 5: Observe the display and check that the experiment board name appear and no fault is detected. Step 6: Connect the EB-3000 to the PC with the USB cable. Step 7: Run the SES51C software by double clicking on SES51C icon on the desktop. Step 8: Check that the VP/EA switch is at VP position. Step 9: Press <RST> on the EB-3191. Step 10: Write a program that reads a data item from input port (from the switches) and outputs it to the output port and sends it to the DAC. The program runs in an infinite loop. EB-3191 – Introduction to microprocessors and microcontrollers 259 PORTA WARM ADC_CS SER_DO SER_DI SER_CLK DAC_SYNC ; DAC: ; SDAC: ; SDAC1: SDAC2: EQU EQU EQU EQU EQU EQU EQU 0FF00H 0103H 93H 94H 95H 96H 97H ORG MOV MOVX MOVX LCALL SJMP 2100H DPTR,#PORTA A,@DPTR @DPTR,A SDAC DAC PUSH CLR CLR CLR MOV LCALL POP LCALL SETB RET ACC DAC_SYNC SER_CLK SER_DI A,#3 SDAC1 ACC SDAC1 DAC_SYNC MOV RRC MOV SETB CLR DJNZ RET R0,#8 A SER_DI,C SER_CLK SER_CLK R0,SDAC2 ;P1.3 ;P1.4 ;P1.5 ;P1.6 ;P1.7 ;for DAC channel 1 (7 for ch2) Step 11: Assemble the program, download it and run the program. Step 12: Change the switches and measure the voltage between the output of the DAC circuit (point ANO) and the GND. Step 13: Press <RST> to stop the program. EB-3191 – Introduction to microprocessors and microcontrollers 260 Step 14: Write a program that does the following: a) b) c) d) Outputs gradually increasing numbers to the DAC up to FF. Outputs gradually diminishing numbers all the way to 00. Jump to paragraph (a) for cyclic repeating. Between the output of one number and the following one, the program executes a delay, in accordance with the status of the input port switches. PORTA WARM ADC_CS SER_DO SER_DI SER_CLK DAC_SYNC ; DAC: DAC1: DAC2: DELAY1: EQU EQU EQU EQU EQU EQU EQU 0FF00H 0103H 93H 94H 95H 96H 97H ORG MOV MOV MOV LCALL MOVX DJNZ INC CJNE 2100H DPTR,#PORTA R0,#0 A,R0 SDAC A,@DPTR ACC,DELAY1 R0 R0,#0,DAC2 DEC MOV LCALL MOVX DJNZ DJNZ SJMP R0 A,R0 SDAC A,@DPTR ACC,DELAY2 R0,DAC3 DAC2 PUSH CLR CLR CLR MOV LCALL POP LCALL SETB RET ACC DAC_SYNC SER_CLK SER_DI A,#3 SDAC1 ACC SDAC1 DAC_SYNC MOV RRC MOV SETB CLR DJNZ RET R0,#8 A SER_DI,C SER_CLK SER_CLK R0,SDAC2 ;P1.3 ;P1.4 ;P1.5 ;P1.6 ;P1.7 ; DAC3: DELAY2: ; SDAC: ; SDAC1: SDAC2: ;for DAC channel 1 (7 for ch2) EB-3191 – Introduction to microprocessors and microcontrollers 261 Step 15: Assemble the program, download it and run the program. Step 16: Connect an oscilloscope to the output of the DAC circuit. Draw the shape of the waveform as displayed. Step 17: Change the combination of the switches and examine the influence of this operation on the waveform. Examine the linearity of the wave and the magnitude of a step. Step 18: Suggest a way for generating a sinusoidal wave. Experiment Report: 1) Copy the program in step 14, add remarks and explain each stage. EB-3191 – Introduction to microprocessors and microcontrollers 262 Experiment 10.2 – Employing the ADC Objectives: How the ADC-0808 is connected to the CPU bus. How to write a program that converts an analog signal (voltage) into binary number and outputs it to the LEDs. Equipment required: EB-3000 EB-3191 Banana wires Discussion: The ADC 0808 – a channel multiplexed monolithic ADC The discussion of ADC's cannot be complete without mentioning the monolithic ADC components, suited to a microcomputer. These devices contain internally all the conversion circuit described in the preceding paragraph with different conversion methods, including an output buffer. All they need in order to operate is clock pulses at a suitable frequency and a START pulse for starting the conversion. At the end of the conversion they output an EOC signal. Accessing the output channel results in the output of the data to the output lines. Nowadays it is common practice to use more sophisticated devices than ADC for handling a single input voltage. A device multiplexing several inputs (a multiplexer) is used. We describe a device, which multiplexes eight analog inputs. In addition to the regular ADC lines, this device has three inputs of address. Eight different analog inputs may be connected to the device. Accessing the component with a channel address in these three address lines, converts the channel from analog to digital. EB-3191 – Introduction to microprocessors and microcontrollers 263 The ADC0808, described in figure 10-7, is such a device. Start Clock End Of Conversion (Interrupt) 8-Bit A/D Control & Timing 8 Analog Inputs 8 Channels Multiplexing Analog Switches S.A.R. 3-State Output Latch Buffer Comparator 8-Bit Outputs Switch Tree 3-Bit Address Address Latch Enable Address Latch and Decoder 256R Resistor Ladder VCC GND REF(+) REF(-) Output Enable Figure 10-7 The ADC0808 ADC0838 8-bit serial ADC The ADC0831 series are 8-bit successive approximation A/D converters with a serial I/O and configurable input multiplexers with up to 8 channels. The serial I/O is configured to comply with the NSC Microwire serial data exchange standard for easy interface to the COPS family of processors, and can interface with standard shift registers or Ps. The 2-, 4- or 8-channel multiplexers are software configured for single-ended or differential inputs as well as channel assignment. The differential analog voltage input allows increasing the common-mode rejection and offsetting the analog zero input voltage value. In addition, the voltage reference input can be adjusted to allow encoding any smaller analog voltage span to the full 8 bits of resolution. EB-3191 – Introduction to microprocessors and microcontrollers 264 The design of these converters utilizes a sample-data comparator structure which provides for a differential analog input to be converted by a successive approximation routine. The actual voltage converted is always the difference between an assigned "+" input terminal and a "–" input terminal. The polarity of each input terminal of the pair being converted indicates which line the converter expects to be the most positive. If the assigned "+" input is less than the "–" input the converter responds with an all zeros output code. A unique input multiplexing scheme has been utilized to provide multiple analog channels with software configurable single-ended, differential, or a new pseudo-differential option which will convert the difference between the voltage at any analog input and a common terminal. The analog signal conditioning required in transducer-based data acquisition systems is significantly simplified with this type of input flexibility. One converter package can now handle ground referenced inputs and true differential inputs as well as signals with some arbitrary reference voltage. A particular input configuration is assigned during the MUX addressing sequence, prior to the start of a conversion. The MUX address selects which of the analog inputs are to be enabled and whether this input is single-ended or differential. In the differential case, it also assigns the polarity of the channels. Differential inputs are restricted to adjacent channel pairs. For example channel 0 and channel 1 may be selected as a different pair but channel 0 or 1 cannot act differentially with any other channel. In addition to selecting differential mode the sign may also be selected. Channel 0 may be selected as the positive input and channel 1 as the negative input or vice versa. The MUX address is shifted into the converter via the DI line. Because the ADC0831 contains only one differential input channel with a fixed polarity assignment, it does not require addressing. The common input line on the ADC0838 can be used as a pseudo-differential input. In this mode, the voltage on this pin is treated as the "–" input for any of the other input channels. This voltage does no have to be analog ground; it can be any reference potential which is common to all of the inputs. This feature is most useful in single-supply application where the analog circuitry may be biased up to a potential other than ground and the output signals are all referred to this potential. EB-3191 – Introduction to microprocessors and microcontrollers 265 Procedure: Step 1: Connect the EB-3000 to the power supply. Step 2: Connect the power supply to the Mains. Step 3: Turn ON the trainer. The DVM screen should appear on the display. Step 4: Plug the EB-3191 into the EB-3000. Step 5: Observe the display and check that the experiment board name appear and no fault is detected. Step 6: Connect the EB-3000 to the PC with the USB cable. Step 7: Run the SES51C software by double clicking on SES51C icon on the desktop. Step 8: Check that the VP/EA switch is at VP position. Step 9: Press <RST> on the EB-3191. Step 10: A potentiometer is connected across +5V and GND. Connect the potentiometer slider terminal to the AI0 input of the ADC. Step 11: Write a program that executes the following: a) Conversion of the voltage from the input of the ANI0 channel of the ADC to binary data. b) Outputs the binary value to the LEDs connected to the output port. c) Jumps to paragraph (a). EB-3191 – Introduction to microprocessors and microcontrollers 266 PORTA WARM ADC_CS SER_DO SER_DI SER_CLK DAC_SYNC ; ADC: ; SADC: SADC2: EQU EQU EQU EQU EQU EQU EQU 0FF00H 0103H 93H 94H 95H 96H 97H ORG MOV LCALL MOVX SJMP 2100H DPTR,#PORTA SADC @DPTR,A ADC SETB SETB CLR CLR SETB NOP CLR MOV MOV CLR SETB NOP CLR RLC MOV SETB NOP NOP CLR SER_DI ADC_CS SER_CLK ADC_CS SER_CLK SETB CLR MOV SETB NOP NOP NOP CLR MOV RLC DJNZ RET SER_DI A R0,#8 SER_CLK SER_CLK R0,#4 A,#80H ADC_CS SER_CLK ;P1.3 ;P1.4 ;P1.5 ;P1.6 ;P1.7 ;for channel 1 ;start bit SER_CLK A SER_DI,C SER_CLK SER_CLK ; SADC3: ;to enable receive SER_CLK C,SER_DO A R0,SADC3 Step 12: Assemble the program, download it and run the program. Step 13: Change the potentiometer (slider) position. Measure the voltage being supplied to the ADC input and compare the measured voltage to the binary number you have obtained. EB-3191 – Introduction to microprocessors and microcontrollers 267 Step 14: Improve the program that it sends the data also to the DAC. We shall write the main program without the SADC and SDAC routines, which are the same as before. PORTA WARM ADC_CS SER_DO SER_DI SER_CLK DAC_SYNC ; ADC: EQU EQU EQU EQU EQU EQU EQU 0FF00H 0103H 93H 94H 95H 96H 97H ORG MOV LCALL LCALL MOVX SJMP 2100H DPTR,#PORTA SADC SDAC @DPTR,A ADC ;P1.3 ;P1.4 ;P1.5 ;P1.6 ;P1.7 Step 15: Assemble the program, download it and run the program. Step 16: Change the potentiometer and compare the voltage at the ADC input with the voltage at the DAC output. Step 17: Let's do an interesting experiment. Connect the analog output of the DAC (AO) to the analog input of the ADC (AI0). Step 18: Write a program that reads the switches connected to input port, sends this data to the DAC, reads the AI0 of the ADC and outputs this data to the LEDs connected to output port. If both converters are accurate, the LEDs should show the switches status. We shall write the main program without the SADC and SDAC routines, which are the same as before. EB-3191 – Introduction to microprocessors and microcontrollers 268 PORTA WARM ADC_CS SER_DO SER_DI SER_CLK DAC_SYNC ; ADC: EQU EQU EQU EQU EQU EQU EQU 0FF00H 0103H 93H 94H 95H 96H 97H ORG MOV MOVX LCALL LCALL MOVX SJMP 2100H DPTR,#PORTA A,@DPTR SDAC SADC @DPTR,A ADC ;P1.3 ;P1.4 ;P1.5 ;P1.6 ;P1.7 Step 19: Assemble the program, download it and run the program. Change the switches condition and watch the LEDs. Draw your conclusions. Experiment Report: 1) Copy the program in step 14, add remarks and explain each stage. EB-3191 – Introduction to microprocessors and microcontrollers 269 Summary questions: 1. What does the following program execute? PORTA WARM ADC_CS SER_DO SER_DI SER_CLK DAC_SYNC ; DAC: DAC1: DAC2: DELAY1: EQU EQU EQU EQU EQU EQU EQU 0FF00H 0103H 93H 94H 95H 96H 97H ORG MOV MOV MOV LCALL MOVX DJNZ INC CJNE 2100H DPTR,#PORTA R0,#0 A,R0 SDAC A,@DPTR ACC,DELAY1 R0 R0,#0,DAC2 DEC MOV LCALL MOVX DJNZ DJNZ SJMP R0 A,R0 SDAC A,@DPTR ACC,DELAY2 R0,DAC3 DAC2 ;P1.3 ;P1.4 ;P1.5 ;P1.6 ;P1.7 ; DAC3: DELAY2: (a) (b) (c) (d) Transfers the switches number to the DAC. Creates a square wave signal at the DAC output. Creates a triangle wave signal at the DAC output. Creates a sine wave signal at the DAC output. EB-3191 – Introduction to microprocessors and microcontrollers 270 2. What does the following program execute? PORTA WARM ADC_CS SER_DO SER_DI SER_CLK DAC_SYNC ; ADC: EQU EQU EQU EQU EQU EQU EQU 0FF00H 0103H 93H 94H 95H 96H 97H ORG MOV LCALL LCALL MOVX SJMP 2100H DPTR,#PORTA SADC SDAC @DPTR,A ADC ;P1.3 ;P1.4 ;P1.5 ;P1.6 ;P1.7 (a) Reads the switches and transfers the number to the DAC. (b) Reads the ADC and transfers the number to the DAC and to the LEDs. (c) Transfers the switches to the DAC, reads the ADC and transfers it to the LEDs. (d) Transfers the ADC to the DAC. EB-3191 – Introduction to microprocessors and microcontrollers 271 Appendix A – 8051 Instruction Set Interrupt response time: To finish execution of current instruction, respond to the interrupt request, push the PC and to vector to the first instruction of the interrupt service program requires 38 to 81 oscillator periods. Instructions that effect flag settings: Instruction ADD ADDC SUBB MUL DIV DA RRC RLC SETB C Flag C 0V AC x x x x x x x x x 0 x 0 x x x x 1 Instruction CLR C CPL C ANL C,bit ANL C,/bit ORL C,bit ORL C,/bit MOV C,bit CJNE Flag C 0V AC 0 x x x x x x Notes on instruction set and addressing modes: Rn direct @Ri #data #data 16 addr 16 addr 11 rel bit Register R0-R7 of the currently selected register bank. 8-bit internal data location's address. This could be an internal data RAM location (0-127) or a SFR [i.e., I/O port control register, status register, etc. (128-255)]. 8-bit internal data RAM location (0-225) addressed indirectly through register R1 or R0. 8-bit constant included in instruction. 16-bit constant included in instruction. 16-bit destination address. Used by LCALL & LJMP. A branch can be anywhere within the 64K byte program memory address space. 11-bit destination address. Used by ACALL & AJMP. The branch will be within the same 2K bytes page of program memory as the first byte of the following instruction. Signed (two's complement) 8-bit offset byte. Used by SJMP and all conditional jumps. Range is -128 to +127 bytes relative to first byte of the following instruction. Direct addressed bit in internal data RAM or special function register. EB-3191 – Introduction to microprocessors and microcontrollers 272 Arithmetic Operations MNEMONI C ADD ADD ADD ADD ADDC ADDC ADDC ADDC SUBB SUBB SUBB SUBB INC INC INC INC DEC DEC DEC DEC INC MUL DIV DA A,Rn A,direct A,@Ri A,#data A,Rn A,direct A,@Ri A,#data A,Rn A,direct A,@Ri A,#data A Rn direct @Ri A Rn direct @Ri DPTR AB AB A DESCRIPTION Add register to ACC. Add direct byte to ACC. Add indirect RAM to ACC. Add immediate data to ACC. Add register to ACC. with carry Add direct byte to ACC. with carry Add indirect RAM to ACC. with carry Add immediate data to ACC. with carry Subtract register from ACC. with borrow Subtract direct byte from ACC. with borrow Subtract indirect RAM from ACC. with borrow Subtract immediate data from ACC. with borrow Increment ACC. Increment register Increment direct byte Increment indirect RAM Decrement ACC. Decrement register Decrement direct byte Decrement indirect RAM Increment data pointer Multiply A & B Divide A by B Decimal adjust ACC. COD E 28-2F 25 26,27 24 38-3F 35 36,37 34 98-9F 95 96,97 94 04 08-0F 05 06,07 14 18-1F 15 16,17 A3 A4 84 D4 BYT E OSC. PER. 1 2 1 2 1 2 1 2 1 2 1 2 1 1 2 1 1 1 2 1 1 1 1 1 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 24 48 48 12 EB-3191 – Introduction to microprocessors and microcontrollers 273 Logical Operations MNEMONIC ANL ANL ANL ANL ANL ANL ORL ORL ORL ORL ORL ORL XRL XRL XRL XRL XRL XRL CLR CPL RL RLC RR RRC SWAP A,Rn A,direct A,@Ri A,#data direct,A direct,#data A,Rn A,direct A,@Ri A,#data direct,A direct,#data A,Rn A,direct A,@Ri A,#data direct,A direct,#data A A A A A A A DESCRIPTION AND register to ACC. AND direct byte to ACC. AND indirect RAM to ACC. AND immediate data to ACC. AND ACC. to direct byte AND immediate data to direct byte OR register to ACC. OR direct byte to ACC. OR indirect RAM to ACC. OR immediate data to ACC. OR ACC. to direct byte OR immediate data to direct byte XOR register to ACC. XOR direct byte to ACC. XOR indirect RAM to ACC. XOR immediate data to ACC. XOR ACC. to direct byte XOR immediate data to direct byte Clear ACC. Complement ACC. Rotate ACC. left Rotate ACC. left through the carry Rotate ACC. right Rotate ACC. right through the carry Swap nibbles within the ACC. COD E 58-5F 55 56,57 54 52 53 48-4F 45 46,47 44 42 43 68-6F 65 66,67 64 62 63 E4 F4 23 33 03 13 C4 BYT E OSC. PER. 1 2 1 2 2 3 1 2 1 2 2 3 1 2 1 2 2 3 1 1 1 1 1 1 1 12 12 12 12 12 24 12 12 12 12 12 24 12 12 12 12 12 24 12 12 24 48 48 12 EB-3191 – Introduction to microprocessors and microcontrollers 274 Data Operatuons MNEMONIC MOV MOV MOV MOV MOV MOV MOV MOV MOV MOV MOV MOV MOV MOV MOV MOV MOVC MOVC MOVX MOVX A,Rn A,direct A,@Ri A,#data Rn,A Rn,direct Rn,#data direct,A direct,Rn direct,direct direct,@Ri direct,#data @Ri,A @Ri,#data @Ri,#direct DPTR,#data 16 A,@A+DPTR A,@A+PC A,@Ri A,@DPTR MOVX MOVX PUSH POP XCH XCH XCH XCHD @Ri,A @DPTR,A direct direct A,direct A,Rn A,@Ri A,@Ri DESCRIPTION CODE BYTE OSC. PER. Move register to ACC. Move direct byte to ACC. Move indirect RAM to ACC. Move immediate data to ACC. Move ACC. to register Move direct byte to register Move immediate data to register Move ACC. to direct byte Move register to direct byte Move direct byte to direct Move indirect RAM to direct byte Move immediate data to direct byte Move ACC. to indirect RAM Move immediate datato indirect RAM Move direct byte to indirect RAM Load data pointer with a 16-bit constant Move code byte relative to DPTR to ACC. Move code byte relative PC to ACC. Move external RAM (8-bit addr) to ACC. Move external RAM to (16-bitaddr) to ACC. Move ACC. to external RAM (8-bit addr) Move ACC. to external RAM (16-bit addr) Push direct byte onto stack Pop direct byte from stack to the carry Exchange direct byte with ACC. Exchange register Exchange indirect RAM with ACC. Exchange low order digit indirect RAM with ACC. E8-EF E5 E6,E7 74 F8-FF A8-AF 78-7F F5 88-8F 85 86,87 75 F6,F7 76,77 A6,A7 90 93 83 E2,E3 E0 1 2 1 2 1 2 2 2 2 3 2 3 1 1 1 3 1 1 1 1 12 12 12 12 12 24 12 12 24 24 24 24 12 12 12 24 24 24 24 24 F2,F3 F0 C0 D0 C5 C8-CF C6,C7 D6,D7 1 1 2 2 2 1 1 1 24 24 24 24 12 12 12 12 EB-3191 – Introduction to microprocessors and microcontrollers 275 Boolean Variable Manipulation MNEMO NIC CLR CLR SETB SETB CPL CPL ANL ANL ORL ORL MOV MOV JC JNC JB JNB JBC C bit C bit C bit C,bit C,/bit C,bit C,/bit C,bit bit,C rel rel bit,rel bit,rel bit,rel DESCRIPTION Clear carry Clear direct bit Set carry Set direct bit Complement carry Complement direct bit AND direct bit to carry AND complement of direct bit to carry OR direct bit to carry OR complement of direct bit to carry Move direct bit to carry Move carry to direct bit Jump if carry is set Jump if carry not set Jump if direct bit is set Jump if direct bit is not set Jump if direct bit is set and clear bit COD E BYT E OSC. PER. C3 C2 D3 D2 B3 B2 82 B0 72 A0 A2 92 40 50 20 30 10 1 2 1 2 1 2 2 2 2 2 2 2 2 2 3 3 3 12 12 12 12 12 24 12 12 24 24 24 24 12 24 24 24 24 EB-3191 – Introduction to microprocessors and microcontrollers 276 Program Branching MNEMONIC ACALL LCALL RET RET1 AJMP LJMP SJMP JMP JZ JNZ CJNE addr11 addr16 CJNE A,#data,rel CJNE Rn,#data,rel CJNE @Ri,#data,rel DJNZ DJNZ NOP Rn,rel direct,rel addr11 addr16 rel @A+DPTR rel rel A,direct,rel DESCRIPTION Absolute subroutine call Long subroutine call Return from subroutine Return from interrupt Absolute jump Long jump Short jump (relative addr) Jump indirect relative to the DPTR Jump if ACC. is zero Jump if ACC. is not zero Compare direct byte to ACC. and jump if not equal Compare immediate to ACC. and jump if not equal Compare immediate register and jump if not equal Compare immediate to indirect and jump if not equal Decrement register and jump if not zero Decrement direct byte and jump if not zero No operation CODE BYTE OSC. PER. *1 12 22 32 *1 02 80 73 60 70 B5 2 3 1 1 2 3 2 1 2 2 3 24 24 24 24 24 24 24 24 24 24 24 B4 3 24 B8-BF 3 24 B6,B7 3 24 D8-DF D5 00 3 3 1 24 24 12 EB-3191 – Introduction to microprocessors and microcontrollers 277 Appendix B – The 8051 Special Function Registers The internal RAM and the special registers in the 8051 Region 6 – for storage of data in a usual manner Region 5 - for bit addressing Region 4 - BANK3 of R0-R7 RAM Byte 7FH H83 2FH HH3 2DH HH3 HH3 HH3 H33 H33 H37 H33 H35 H34 H38 H33 H33 H33 HH3 (MSB) (LSB) 127 7F 77 6F 67 5F 57 4F 47 3F 37 2F 27 1F 17 0F 07 7E 76 6E 66 5E 56 4E 46 3E 36 2E 26 1E 16 0E 06 7D 75 6D 65 5D 55 4D 45 3D 35 2D 25 1D 15 0D 05 7C 74 6C 64 5C 54 4C 44 3C 34 2C 24 1C 14 0C 04 7B 73 6B 63 5B 53 4B 43 3B 33 2B 23 1B 13 0B 03 7A 72 6A 62 5A 52 4A 42 3A 32 2A 22 1A 12 0A 02 79 71 69 61 59 51 49 41 39 31 29 21 19 11 09 01 78 70 68 60 58 50 48 40 38 30 28 20 18 10 08 00 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 Bank 3 Region 3 - BANK2 of R0-R7 H33 H37 Region 2 - BANK1 of R0-R7 H33 HH3 Region 1 - BANK0 of R0-R7 H33 H37 24 23 Bank 2 16 15 Bank 1 8 7 Bank 0 H33 EB-3191 – Introduction to microprocessors and microcontrollers 6 278 Registers in bit addressing and their bits addresses Direct Byte Address (LSB) Hardware Register Symbol (MSB) 240 F7 F6 F5 F4 F3 F2 F1 F0 B 224 E7 E6 E5 E4 E3 E2 E1 E0 ACC 208 CY D7 AC D6 F0 D5 RS1 D4 RS0 D3 0V D2 D1 P D0 PSW 200 TF2 CF EXF2 CE RCLK CD TCLK CC EXEN2 CB TR2 CA CT/ T 2 C9 CP/ RL 2 C8 184 - - PT2 BD PS BC PT1 BB PX1 BA PT0 B9 PX0 B8 IP 176 B7 B6 B5 B4 B3 B2 B1 B0 P3 168 EA AF - ET2 AD ES AC ET1 AB EX1 AA ET0 A9 EX0 A8 IE 160 A7 A6 A5 A4 A3 A2 A1 A0 P2 152 SM0 9F SM1 9E SM2 9D REN 9C TB8 9B RB8 9A TI 99 RI 98 SCON 144 97 96 95 94 93 92 91 90 P1 136 TF1 8F TR1 8E TF0 8D TR0 8C IE1 8B IT1 8A IE0 89 IT0 88 TCON 128 87 86 85 84 83 82 81 80 P0 Bit Address EB-3191 – Introduction to microprocessors and microcontrollers T2CON 279 The SFR (Special Function Registers) of the 8051 The registers are arranged a bit oddly, thus they are described by their function and not their addresses. Full Name ACCumulator B register Program Status Word Stack Pointer Data Pointer Low byte Data Pointer High byte Port 0 Port 1 Port 2 Port 3 Interrupt Enable control Interrupt Priority control Timer/counter MoDe control Timer/counter CONtrol Timer/counter 0 Low byte Timer/counter 0 High byte Timer/counter 1 Low byte Timer/counter 1 High byte Power CONtrol Serial CONtrol Serial data BUFFer Designation Address *ACC E0H *B F0H *PSW D0H SP 81H DPL 82H DPH 83H *P0 80H *P1 90H *P2 A0H *P3 B0H *IE A8H *IP B8H TMOD 89H TCON C8H TL0 8AH TH0 8CH TL1 8BH TH1 8DH PCON 97H *SCON 98H SBUF 99H All the registers marked '*' can be also addressed in bit addressing. EB-3191 – Introduction to microprocessors and microcontrollers 280 At the CPU's initialization, the special registers get the following values: Register Content PC ACC B PSW SP DPTR P0-P3 IP IE TMOD TCON TH0 TL0 TH1 TL1 SCON SBUF PCON 0000H 00H 00H 00H 07H 0000H FFH xx000000B 0x000000B 00H 00H 00H 00H 00H 00H 00H Not defined 0xxx0000B EB-3191 – Introduction to microprocessors and microcontrollers 281 The 8051 pins description P1.0 1 40 VSS P1.1 2 39 P0.0/AD0 P1.2 3 38 P0.1/AD1 P1.3 4 37 P0.2/AD2 P1.4 5 36 P0.3/AD3 P1.5 6 35 P0.4/AD4 P1.6 7 34 P0.5/AD P1.7 8 33 5P0.6/AD6 RST 9 32 P0.7/AD7 31 EA M80C51 M80C31 P3.0/RXD 10 P3.1/TXD 11 30 ALE P3.2/INT0 12 29 PSEN P3.3/INT1 13 28 P2.7/A15 P3.4/T0 14 27 P2.6/A14 P3.5/T1 15 26 P2.5/A13 P3.6/ WR 16 25 P2.4/A12 P3.6/ RD 17 24 P2.3/A11 XTAL.2 18 23 P2.2/A10 XTAL.1 19 22 P2.1/A9 VSS 20 21 P2.0/A8 EB-3191 – Introduction to microprocessors and microcontrollers