AND DESIGN PREFACE MICROPROCESSORS AND MICROCONTROLLERS -INTERFACING, PROGRAMMING

Size: px
Start display at page:

Download "AND DESIGN PREFACE MICROPROCESSORS AND MICROCONTROLLERS -INTERFACING, PROGRAMMING"

Transcription

1 MICROPROCESSORS AND MICROCONTROLLERS -INTERFACING, PROGRAMMING AND DESIGN PREFACE When discrete components and integrated circuits played a vital role in technology development, the advent of microprocessor has changed completely the system design for various real time applications. The Microelectronics industry has changed the technology into user friendly, ease of system design,increases productivity and reduces the time of design. One of the objectives of writing this book is to impart the skill sets for system design using microprocessor and microcontrollers. This book serves as an introduction to the field of microprocessor design and implementation. Designer of an embedded system must have a thorough understanding of hardware, software and system integration. In view of this, various aspects of hardware design, such as interfacing of memory and different types of I/O devices, been covered in details. As it is customary to write software in machine or assembly language or C program for embedded system applications, assembly language programming of 8085,8086 and 8051 and Embedded C program for 8051 been covered with solved examples. The book covers the detailed concepts in architectural, programming and design with microprocessor and microcontroller. Programming examples been elaborated with solved examples.case studies is been included for application of microprocessor and microcontrollers in various areas. The entire contents of the book are described with examples for interfacing then and there. MICROPROCESSORS AND MICROCONTROLLERS -INTERFACING, PROGRAMMING AND DESIGN: is designed as a textbook for the V semester ECE students of ANNA University, Chennai. To start with, the book Chapter 1 opens with the basics of a microprocessor/microcontroller system, its organization, programming system and advances in technology. Chapter 1 is intended as a first level course for microcomputer and embedded system design.(unit 1 of syllabus) Chapter 2 introduces the 16 bit microprocessor architecture to the readers. The pin description,different units BIU and EU,Pipelining, registers and various modes of operation like minimum and maximum mode is been discussed with signal diagrams and block diagram. Interrupts been discussed in detail(unit 1) Chapter 3 describes the 8086 instruction set and programming. Various groups of instructions been discussed with suitable examples. Assembler directives been discussed with many illustrative examples. Assembly language programs with directives been presented. UNIT 2 of syllabus Chapter 4 describes the interfacing of microprocessor with peripheral devices. The chapter covers the interfacing of communication devices 8255&8251,Keyboard display interface, DMA and Programmable timer.the chapter extends to interface the data acquisition units like ADC and DAC with real time examples. The chapter covers the interfacing of the devices in memory mapped I/O and I/O mapped I/O. Memory and Input/output device interfacing is described with examples for partial and absolute decoding. Both 8085 and 8086 interfacing with devices been presented.(unit3 of syllabus) Chapter 5 introduces the architecture of 8 bit Microcontroller 8051.Internal architecture of 8051 is covered in detail. SFRs, Timers, Serial communication, Ports, Interrupts, registers and basic programming model been described in detail. The chapter also deals with instruction set and programming. Various groups of instructions been discussed with suitable examples. Assembly language programs with directives been presented for Timers, Serial communication, Ports and Interrupts.(UNIT4 of syllabus) Chapter 6 describes the real time interfacing of 8051 with peripheral devices. The chapter covers the interfacing communication devices 8255, interfacing with Traffic light control, washing machine control, RTC Interfacing using I2C Standard, Motor Control, Relay, PWM, DC & Stepper Motor. 1

2 Finally the Instruction set of 8086 and 8051 been summarized in separate Appendix. I believe diagrams would convey more information than words.more diagrams and signal graphs been included for better presentation of the concepts. Finally I hope that the book would meet the requirement of the student s educational needs and provide the teachers a different perspective to teach the subject effectively. -S.Ravindrakumar & D.Nithya 2

3 SYLLABUS EC2304 MICROPROCESSOR AND MICROCONTROLLER L T P C AIM To learn the architecture, programming, interfacing and rudiments of system design of microprocessors and microcontrollers. OBJECTIVES To introduce microprocessors and basics of system design using microprocessors. To introduce h/w architecture, instruction set and programming of 8085 microprocessor. To introduce the h/w architecture, instruction set and programming of 8086 microprocessor. To introduce the peripheral interfacing of microprocessors. To introduce through case studies, the system design principles using 8085 and To introduce the h/w architecture, instruction set, programming and interfacing of 8051 microcontroller. UNIT I INTRODUCTION TO 8 BIT AND 16 BIT MICROPROCESSORS H/W ARCHITECTURE 9 Introduction to microprocessor, computer and its organization, Programming system, Address bus, data bus and control bus, Tristate bus, clock generation, Connecting Microprocessor to I/O devices, Data transfer schemes, Architectural advancements of microprocessors. Introductory System design using microprocessors, 8086 Hardware Architecture, External memory addressing, Bus cycles, some important Companion Chips, Maximum mode bus cycle, 8086 system configuration, Memory Interfacing, Minimum mode system configuration, Maximum mode system configuration, Interrupt processing, Direct memory access. UNIT II 16 BIT MICROPROCESSOR INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMMING 9 Programmer s model of 8086, operand types, operand addressing, assembler directives, instruction set - Data transfer group, Arithmetic group, logical group, control transfer group, miscellaneous instruction groups, programming. UNIT III MICROPROCESSOR PERIPHERAL INTERFACING 9 Introduction, Generation of I/O Ports, Programmable Peripheral Interface (PPI)-Intel 8255, Sample-and- Hold Circuit and Multiplexer, Keyboard and Display Interface, Keyboard and Display Controller (8279), Programmable Interval timers (Intel 8253, 8254), D-to-A converter, A-to-D converter, CRT Terminal Interface, Printer Interface. UNIT IV 8 BIT MICROCONTROLLER- H/W ARCHITECTURE, INSTRUCTION SET AND PROGRAMMING 9 Introduction to 8051 Micro-controller, Architecture, Memory organization, Special function registers, Port Operation, Memory Interfacing, I/O Interfacing, Programming 8051 resources, interrupts, Programmer s model of 8051, Operand types, Operand addressing, Data transfer instructions, Arithmetic instructions, Logic instructions, Control transfer instructions, Programming 3

4 UNIT V SYSTEM DESIGN USING MICRO PROCESSOR & MICROCONTROLLER 9 Case studies Traffic light control, washing machine control, RTC Interfacing using I2C Standard- Motor Control- Relay, PWM, DC & Stepper Motor. L: 45, T: 15, TOTAL= 60 PERIODS TEXT BOOKS 1. Krishna Kant, MICROPROCESSORS AND MICROCONTROLLERS Architecture, programming and system design using 8085, 8086, 8051 and PHI Douglas V Hall, MICROPROCESSORS AND INTERFACING, PROGRAMMING AND HARDWARE TMH, REFERENCES 1. Muhammad Ali Mazidi, Janice Gillispie Mazidi, Rolin D.MCKinlay The 8051 Microcontroller and Embedded Systems, Second Edition, Pearson Education Kenneth J. Ayala, The 8086 Microprocessor: Programming & Interfacing The PC, Delmar Publishers, A K Ray, K M Bhurchandi, Advanced Microprocessors and Peripherals, TMH,

5 TABLE OF CONTENTS CHAPTER 1 INTRODUCTION TO MICROPROCESSOR BASED SYSTEM Introduction to microprocessor, Microcontroller and System Design Pre-PC Microprocessor History Processor Specifications Brief History of Multi-core CPUs 1.2. Microprocessor and microcontroller as a programmable device Computer organization and typical microprocessor CPU structure Microprocessor ALU Control unit Memory/storage components Main memory types Bipolar v/s MOS Memories Input and Output System Bus Address bus Data bus Control bus Tristate bus Cache How Cache Works Peripheral Interfacing Functions 5

6 1.3. Basic CPU Architecture CISC vs. RISC Registers Instruction Register Stack Pointer Instruction Decoder Program or Instruction Counter Accumulator Computer Status Word (CSW) or Flag Register Arithmetic and Logic Unit Control Unit The System Clock Instruction Cycle 1.4. Programming system Computer Program Programming language Categories of programming languages Microprocessor Languages Machine language Assembly language High level languages 1.5. Data Transfer Programmed Data Transfer Direct Memory Access (DMA) Transfer or Cycle Stealing Transfer 1.6. Microprocessors vs. microcontrollers 1.7. Architectural Advancement Key Architectural Trends 6

7 Family of Microprocessors Manufacturing Technologies 1.8. SUMMARY CHAPTER 2 INTRODUCTION TO 16-BIT MICROPROCESSOR Introduction 2.2. Pin Diagram of 8086 and Pin description of Pin description of Architecture of 8086 or functional block diagram of Bus interface unit execution unit Registers General Purpose Registers Index or Pointer Registers Segment Registers Other registers of Programing model Memory map Segment registers Logical and physical address Advantages of segmented memory 2.5. Interrupts Performance of Software Interrupts Interrupt Vector Table 7

8 Performance of Hardware Interrupts 2.6. General Bus Operation 2.7. Minimum mode 8086 system Write Cycle Timing Diagram for Minimum Mode Bus Request and Bus Grant Timings in Minimum Mode System of Minimum Mode Interface 2.8. Maximum mode 8086 system Memory Read Timing Diagram in Maximum Mode of Memory Write Timing in Maximum mode of RQ/GT Timings in Maximum Mode Bus Controller Bus Command and Control Signals 2.9. Direct memory access DMA Controller The DMA interface Functional behavior of a DMA transaction DMA interface operation DMA interface with I/O Controller accessing memory CHAPTER INSTRUCTIONS SET AND PROGRAMMING Instruction format 3.2. Addressing modes Immediate Addressing Mode Register addressing mode Memory Addressing Modes Direct Addressing Mode Register Indirect Addressing Mode 8

9 Based Addressing Mode Indexed Addressing Modes Based Indexed Addressing Modes Based Indexed Plus Displacement Addressing Mode 3.2. Instruction set Data Transfer Group Arithmetic and Logical Instructions String Instructions Program Flow Instructions Assembler Directives CHAPTER 4 PERIPHERALS AND INTERFACING Introduction 4.2. The 8255 programmable peripheral interface (PPI) Pin Diagram Block diagram of Control word Mode Selection Interrupt Control Functions Modes of operation BIT/RESET Mode,BSR mode MODE 0: Simple input or Output MODE1: input or Output with handshake MODE 2: Bidirectional Data Transfer Interfacing with microprocessor 4.3. Interfacing with Intel 8251a (USART) Features of

10 Block diagram of Read/Write control logic: Transmitter Section Receiver section Interfacing with microprocessor 4.4. Keyboard/display controller Features of Pin diagram Block diagram of Keyboard Section Display section Scan section CPU interface section Modes of operation Interfacing with microprocessor 4.5 Programmable Timer Pin Diagram Block diagram of Data Bus Buffer Read/Write Logic Control Word Register Counter #0, Counter #1, Counter # SYSTEMS INTERFACE Control Word 10

11 OPERATIONAL DESCRIPTION Programming the Control World Format Modes of operation 4.6. Programmable DMA controller - Intel The features of Pin Diagram Block diagram of Modes of operation Interfacing with microprocessor 4.7. Interfacing Digital-to-Analog Converter (DAC) Pin Configuration Interfacing with microprocessor Example 1 Interfacing DAC Example 2 Interfacing DAC Interfacing Analog to-digital (ADC) Pin Configuration Interfacing with microprocessor Interfacing ADC 0809 WITH I/O interfacing Interfacing I/O and Peripheral Devices Solved Examples I/O interfacing Examples of memory interfacing Memory Address Decoding CRT interface 11

12 4.11. Printer interface CHAPTER 5 INTEL 8051 MICROCONTROLLER ARCHITECTURE AND PROGRAMMING Introduction 5.2. Programming model of Pin description Pinout Description The 8051 Oscillator and Clock Program Counter and Data Pointer A and B CPU Registers Flags and the Program Status Word (PSW) Internal Memory Internal RAM The Stack and the Stack Pointer Special Function Registers Internal ROM 5.4. I/O ports 5.5. Timers TMOD Register (Timer Mode) Timer Control (TCON) Register 5.6. UART (Universal Asynchronous Receiver and Transmitter) 5.7. Operation Interrupts Interrupt Priorities Handling Interrupt Microcontroller Power Consumption Control Instruction Set and Programming Addressing Modes 12

13 Instruction set Programming Timer/Counter Serial Communication Interrupts Programming I/O programming CHAPTER 6 SYSTEM DESIGN USING MICRO PROCESSOR & MICROCONTROLLER Interfacing with DC Motor Introduction DC motor direction control using L293d 6.2. Stepper Motor Working of Stepper Motor Connecting Unipolar Stepper Motor Connecting Bipolar Stepper Motor Programming 6.3. PWM Assembly Code Example 6.4. Traffic light SOFTWARE FOR TRAFFIC LIGHT CONTROL Traffic Lights controller using 8051 microcontroller (Easy Assembly Program) 6.5. Relay Interfacing Relays Interfacing Relay with Real Time Clock Interfacing (DS1307) with AT89S RTC (DS1307) Interfacing with AT89C

14 6.7. Washing machine Circuits 6.8. Water Level Controller QUESTION BANK APPENDIX A COMPLETE 8086 INSTRUCTION SET APPENDIX B SYNTAX OF 8086/8088 ASSEMBLY LANGUAGE APPENDIX C 8086 PROGRAMS APPENDIX D PHERIPHERAL INTERFACING PROGRAMS WITH 8086 APPENDIX E 8051 INSTRUCTIONS OPCODE APPENDIX F 8051 INSTRUCTIONS APPENDIX G 8051 PROGRAMS APPENDIX H 8051 REAL TIME INTERFACING PROGRAMS IN ASM AND EMBEDDED C 14

15 CHAPTER 1 INTRODUCTION TO MICROPROCESSOR BASED SYSTEM 15

16 1.1. INTRODUCTION TO MICROPROCESSOR, MICROCONTROLLER AND SYSTEM DESIGN The brain or engine of the PC is the processor (sometimes called microprocessor), or central processing unit (CPU). The CPU performs the system s calculating and processing. The processor is easily the most expensive single component in the system, costing up to four or more times greater than the motherboard it plugs into. Intel is generally credited with creating the first microprocessor in 1971 with the introduction of a chip called the Today Intel still has control over the processor market, at least for PC systems. This means that all PC-compatible systems use either Intel processors or Intel-compatible processors from a handful of competitors (such as AMD or Cyrix). Intel s dominance in the processor market had not always been assured. Although Intel is generally credited with inventing the processor and introducing the first one on the market, by the late 1970s the two most popular processors for PCs were not from Intel (although one was a clone of an Intel processor). Personal computers of that time primarily used the Z-80 by Zilog and the 6502 by MOS Technologies. The Z-80 was noted for being an improved and less expensive clone of the Intel 8080 processor, similar to the way companies today such as AMD, Cyrix, IDT, and Rise Technologies have cloned Intel s Pentium processors. In that case though, the clone had become more popular than the original. The Z-80 was used in systems of the late 1970s and early1980s that ran the CP/M operating system, while the 6502 was best known for its use in the early Apple computers (before the Mac). The fate of both Intel and Microsoft was dramatically changed in 1981 when IBM introduced the IBM PC, which was based on a 4.77MHz Intel 8088 processor running the Microsoft Disk Operating System (MS-DOS) Pre-PC Microprocessor History The microprocessor was invented by Intel in The PC was created by IBM in The processors powering our PCs today are still backward compatible in many ways with the 8088 selected by IBM in The 4004 processor was introduced on November 15, 1971, and originally ran at a clock speed of 108KHz (108,000 cycles per second, or just over one-tenth a megahertz). The 4004 contained 2,300 transistors and was built on a 10 micron process. Data was transferred four bits at a time, and the maximum addressable memory was only 640 bytes. The 4004 was designed for use in a calculator, but proved to be useful for many other functions because of its inherent programmability. In April 1972, Intel released the 8008 processor, which originally ran at a clock speed of 200KHz (0.2MHz). The 8008 processor contained 3,500 transistors and was built on the same 10 micron process as the previous processor. The big change in the 8008 was that it had an 8-bit data bus, which meant it could move data 8 bits at a time twice as much as the previous chip. It could also address more memory, up to 16KB. This chip was primarily used in dumb terminals and general-purpose calculators. The next chip in the lineup was the 8080, introduced in April 1974, running at a clock rate of 2MHz.Due mostly to the faster clock rate, the 8080 processor had 10 times the performance of the The 8080 chip contained 6,000 transistors and was built on a 6 micron process. Like the previous chip, the 8080 had an 8- bit data bus, so it could transfer 8 bits of data at a time. The 8080 could address up to 64KB of memory, significantly more than the previous chip. It was the 8080 that helped start the PC revolution, as this was the processor chip used in what is generally regarded as the first personal computer, the Altair The CP/M operating system was written for the 8080 chip, and Microsoft was founded and delivered its first product: Microsoft BASIC for the Altair. These initial tools provided the foundation for a revolution in software because thousands of programs were written to run on this platform 16

17 The Z-80 also incorporated a superset of 8080 instructions, meaning it could run all 8080 programs. It also included new instructions and new internal registers, so software that was designed for the Z-80 would not necessarily run on the older The Z-80 ran initially at 2.5MHz (later versions ran up to 10MHz), and contained 8,500 transistors. The Z-80 could access 64KB of memory. Intel released the 8085, its follow up to the 8080, in March of The 8085 ran at 5MHz and contained 6,500 transistors. It was built on a 3-micron process and incorporated an 8-bit data bus. Along different architectural lines, MOS Technologies introduced the 6502 in The chip was used in Apple I and Apple II design and systems by Commodore and other system manufacturers. The 6502 and its successors were also used in computer games, including the original Nintendo Entertainment System (NES) among others. Motorola went on to create the series, which became the basis for the Apple Macintosh line of computers. Intel introduced the 8086 in June 1978.The 8086 chip brought with it the original x86 instruction set that is still present on x86-compatible chips such as the Pentium III. A dramatic improvement over the previous chips, the 8086 was a full 16-bit design with 16-bit internal registers and a 16-bit data bus. This meant that it could work on 16- bit numbers and data internally and also transfer 16-bits at a time in and out of the chip. The 8086contained 29,000 transistors and initially ran at up to 5MHz. The chip also used 20-bit addressing,meaning it could directly address up to 1MB of memory. In 1979, Intel released a crippled version of the 8086 called the The 8088 processor used the same internal core as the 8086, had the same 16-bit registers, and could address the same 1MB of memory, but the external data bus was reduced to 8 bits. This allowed support chips from the older 8-bit 8085 to be used, and far less expensive boards and systems could be made. It is for these reasons that IBM chose the crippled chip, the 8088, for the first PC. This decision would affect history in several ways. The 8088 was fully software compatible with the 8086, so it could run 16-bit software. Also, because the instruction set was very similar to the previous 8085 and 8080, programs written for those older chips could be quickly and easily modified to run. This allowed a large library of programs to be quickly released for the IBM PC, thus helping it become a success. The overwhelming blockbuster success of the IBM PC left in its wake the legacy of requiring backward compatibility with it. In order to maintain the momentum, Intel has pretty much been forced to maintain backward compatibility with the 8088/8086 in most of the processors it has released since then. In some ways the success of the PC, and the Intel architecture it contains, has limited the growth of the personal computer. In other ways, however, its success has caused a huge number of programs, peripherals, and accessories to be developed, and the PC to become a de facto standard in the industry. The original 8088 processor used in the first PC contained close to 30,000 transistors and ran at less than 5MHz. Intel recently introduced a version of the Pentium III Xeon with 2MB of on die cache that has a whopping 140 million transistors, the largest ever in a single processor chip. Both AMD and Intel are manufacturing processors that run at 1GHz (AMD has some bragging rights there; it beat Intel to 1GHz by two days), and both have demonstrated processors running in the 2GHz range. And the progress doesn t stop there, as according to Moore s Law, processing speed and transistor counts are doubling every 1.5 to 2 years Processor Specifications Many confusing specifications often are quoted in discussions of processors. The following sections discuss some of these specifications, including the data bus, address bus, and speed. Processors can be identified by two main parameters: how wide they are and how fast they are. The speed of a processor is a fairly simple concept. Speed is counted in megahertz (MHz), which means millions of cycles per second and faster is better They are l Internal registers 17

18 l Data input and output bus l Memory address bus `Systems below 16MHz usually had no cache memory at all. Starting with 16MHz systems, highspeed cache memory appeared on the motherboard because the main memory at the time could not run at 16MHz. Prior to the 486 processor, the cache on the motherboard was the only cache used in the system. Starting with the 486 series, processors began including what was called L1 (Level 1) cache directly on the processor die. This meant that the L1 cache always ran at the full speed of the chip, especially important when the later 486 chips began to run at speeds higher than the motherboards they were plugged into. During this time the cache on the motherboard was called the second level or L2 cache, which ran at the slower motherboard speed. Starting with the Pentium Pro and Pentium II, Intel began including L2 cache memory chips directly within the same package as the main processor. Originally this built-in L2 cache was implemented as physically separate chips contained within the processor package but not a part of the processor die. Since the speed of commercially available cache memory chips could not keep pace with the main processor, most of the L2 cache in these processors ran at one-half speed (Pentium II/III and AMD Athlon), while some ran the cache even slower, at two-fifths or even one-third the processor speed (AMD Athlon) Brief History of Multi-core CPUs Multi-core processing has been at the heart of the computing revolution for more than a decade. The transition began with server CPU manufacturers adopting multi-core processor architectures to address growing performance demands, combined with the dramatic increase in power consumption of single core processors running at high frequencies. Multi-core CPUs can operate at lower frequency, often consuming less power, and completing work much faster by running tasks in parallel compared to single core predecessors MICROPROCESSOR AND MICROCONTROLLER AS A PROGRA- MMABLE DEVICE COMPUTER ORGANIZATION AND TYPICAL MICROPROCESSOR The CPU executes a sequence of instructions.the execution of an instruction is organized as an instruction cycle. it is performed as a succession of several steps.each step is executed as a set of several microoperations.a basic computer organization block diagram is given below The task performed by any microoperation falls in one of the following categories: - Transfer data from one register to another; - Transfer data from a register to an external interface (system bus); - Transfer data from an external interface to a register; - Perform an arithmetic or logic operation, using registers for input and output. In order to allow the execution of a microoperation, one or several control signals have to be issued; they allow the corresponding data transfer and/or computation to be performed. The CPU executes an instruction as a sequence of control steps. In each control step one or several microoperations are executed. One clock pulse triggers the activities corresponding to one control step for each clock pulse the control unit generates the control signals corresponding to the microoperations to be executed in the respective control step. 18

19 Block diagram of a typical CPU CPU structure The main functions are data transfer arithmetic and logic operations decision making (instructional flow control) The register array consists of at least one accumulator, program counter and stack pointer. The control unit controls all the operations in a CPU and basically it puts the CPU in one of the fetch and execution phases 19

20 Microprocessor A microprocessor incorporates the functions of a computer's central processing unit (CPU) on a single integrated circuit (IC), or at most a few integrated circuits. It is a multipurpose, programmable device that accepts digital data as input, processes it according to instructions stored in its memory, and provides results as output. It is an example of sequential digital logic, as it has internal memory. Microprocessors operate on numbers and symbols represented in the binary numeral system. The advent of low-cost computers on integrated circuits has transformed modern society. General-purpose microprocessors in personal computers are used for computation, text editing, multimedia display, and communication over the Internet. Many more microprocessors are part of embedded systems, providing digital control over myriad objects from appliances to automobiles to cellular phones and industrial process control ALU In computing, an arithmetic and logic unit (ALU) is a digital circuit that performs integer arithmetic and logical operations. The ALU is a fundamental building block of the central processing unit of a computer, and even the simplest microprocessors contain one for purposes such as maintaining timers. The processors found inside modern CPUs and graphics processing units (GPUs) accommodate very powerful and very complex ALUs; a single component may contain a number of ALUs. Mathematician John von Neumann proposed the ALU concept in 1945, when he wrote a report on the foundations for a new computer called the EDVAC. Research into ALUs remains as an important part of computer science, falling under Arithmetic and logic structures in the ACM Computing Classification System. Most of a processor's operations are performed by one or more ALUs. An ALU loads data from input registers. Then an external control unit tells the ALU what operation to perform on that data, and then the ALU stores its result into an output register. The control unit is responsible for moving the processed data between these registers, ALU and memory Control unit The basic task of the control unit: - for each instruction the control unit causes the CPU to go through a sequence of control steps; - in each control step the control unit issues a set of signals which cause the corresponding microoperations to be executed. The control unit is driven by the processor clock. The signals to be generated at a certain moment depend on: - the actual step to be executed; - the condition and status flags of the processor; - the actual instruction executed; - external signals received on the system bus (e.g. interrupt signals). 20

21 Memory/storage components The memory in a computer system stores the data and instructions of the programs. Semiconductor memories are required in a microcomputer for storing information which may comprise of (a) the data to be used for computation, (b) instructions and (c) computational results. A program starts as a set of instructions on a paper, then this is transferred to a set of cards with the instructions punched in code on them. These instructions also can be transferred to magnetic tape, paper tape or directly into semiconductor memory which is the eventual storage space for a program. The semiconductor memory chips are connected to the μp through the address bus, data bus and control bus. (This is also the way that I/O devices are connected to the μp). See Figure below for Connection of I/O Devices and Memory and address decoding atructure) Figure:Connection of I/O Devices and Memory 21

22 Main memory types Memories may be broadly divided into two classes: (a) Random Access Memory (RAM) or Read/Write Memory (RWM) There is provision in RAMs (RWMs) for writing information into the memory and reading it when the microcomputer is in operation. It is, therefore, used to store information which changes or may change 22

23 during the operation of the system, viz. data for calculations and results of calculations. It is also used to store the programs which are to be changed frequently. Semiconductor RAM is a volatile memory. A RAM can be of static or dynamic type. Dynamic RAMs have higher packing densities, are faster and consume less power in the quiescent state. However, because of external refreshing circuitry requirement, the dynamic RAMs are profitable only in large sizes. (b) Read-Only Memory (ROM) The ROM functions as a memory array whose contents once programmed, are permanently fixed and can not be altered by the μp while the system is operating. It is non-volatile. ROMs exist in many forms. (i) Mask ROM : It is custom programmed or mask programmed when manufactured and can not be altered thereafter. The cost of a custom built mask for programming is so high that thousands of ROMs storing the same information must be produced to pay for the mask. (ii) Programmable ROM (PROM) : This type is programmable by the user (typically by electrically overheating fusible links in selected manner). Once programmed, the contents can not be altered. The memory may be programmed one at a time by the user and is thus suitable for the cases where small quantities of a ROM are needed. (iii) Electrically Alterable ROM (EAROM) : In this type of memory, the contents can be electrically erased (by applying a large negative voltage to control gates of memory cells) and the memory can be then reprogrammed (by applying a large positive voltage to control gates). This type is convenient when the user is not sure of the program and may wish to modify it. This is a typical requirement in prototype development. (iv) Erasable Programmable ROM (EPROM) : Like EAROM, this type of memory can also be erased and reprogrammed. However, erasing is by exposing the memory chips to high intensity ultravoilet light of a wavelength close to 2537 Å. It has the same application filed as the EAROM Bipolar v/s MOS Memories Basically there are two semiconductor technologies, namely, bipolar and MOS unipolar. Mask ROMs and PROMs are available in both types whereas EAROMs and EPROMs are made with MOS technology only. In general, bipolar devices (including memories) are faster and have higher drive capabilities. On the other hand, MOS devices consume less space and power and are cheaper. Therefore, MOS memories are preferred where speed is not a critical factor. The following table summarizes the characteristics of the various kinds of data storage in the storage hierarchy Input and Output In computing, input/output or I/O is the communication between an information processing system (such as a computer) and the outside world, possibly a human or another information processing system. Inputs are the signals or data received by the system, and outputs are the signals or data sent from it. The term can also be used as part of an action; to "perform I/O" is to perform an input or output operation. I/O 23

24 devices are used by a person (or other system) to communicate with a computer. For instance, a keyboard or a mouse may be an input device for a computer, while monitors and printers are considered output devices for a computer. Devices for communication between computers, such as modems and network cards, typically serve for both input and output. Note that the designation of a device as either input or output depends on the perspective. Mouse and keyboards take as input physical movement that the human user outputs and convert it into signals that a computer can understand. The output from these devices is input for the computer. Similarly, printers and monitors take as input signals that a computer outputs. They then convert these signals into representations that human users can see or read. For a human user the process of reading or seeing these representations is receiving input. These interactions between computers and humans is studied in a field called human computer interaction System Bus What is a Bus? A communication pathway connecting two or more devices Usually broadcast Often grouped A number of channels in one bus e.g. 32 bit data bus is 32 separate single bit channels The majority of system buses are made up of 50 to 100 distinct lines for communication. The system bus consists of three types of buses: Data Bus: Carries the data that needs processing Address Bus: Determines where data should be sent Control Bus: Determines data processing Address bus 24

25 The address bus is the set of wires that carries the addressing information used to describe the memory location to which the data is being sent or from which the data is being retrieved. As with the data bus, each wire in an address bus carries a single bit of information. This single bit is a single digit in the address. The more wires (digits) used in calculating these addresses, the greater the total number of address locations. The size (or width) of the address bus indicates the maximum amount of RAM that a chip can address Data bus The size of the internal registers indicate how much information the processor can operate on at one time and how it moves data around internally within the chip. This is sometimes also referred to as the internal data bus. The register size is essentially the same as the internal data bus size. A register is a holding cell within the processor; for example, the processor can add numbers in two different registers, storing the result in a third register. The register size determines the size of data the processor can operate on. The register size also describes the type of software or commands and instructions a chip can run. That is, processors with 32-bit internal registers can run 32-bit instructions that are processing 32-bit chunks of data, but processors with 16-bit registers cannot. Most advanced processors today chips from the 386 to the Pentium III use 32-bit internal registers and can therefore run the same 32-bit operating systems and software Control bus A control bus is a computer bus that is used by the CPU to communicate with devices that are contained within the computer. This occurs through physical connections such as cables or printed circuits. The CPU transmits a variety of control signals to components and devices to transmit control signals to the CPU using the control bus. One of the main objectives of a bus is to minimize the lines that are needed for communication. An individual bus permits communication between devices using one data channel. The control bus is bidirectional and assists the CPU in synchronizing control signals to internal devices and external components. It is comprised of interrupt lines, byte enable lines, read/write signals and status lines. Communication between the CPU and control bus is necessary for running a proficient and functional system. Without the control bus the CPU cannot determine whether the system is receiving or sending data. It is the control bus that regulates which direction the write and read information need to go. The control bus contains a control line for write instructions and a control line for read instructions. When the CPU writes data to the main memory, it transmits a signal to the write command line. The CPU also sends a signal to the read command line when it needs to read. This signal permits the CPU to receive or transmit data from main memory Tristate bus In digital electronics three-state, tri-state, or 3-state logic allows an output port to assume a high impedance state in addition to the 0 and 1 logic levels, effectively removing the output from the circuit. This allows multiple circuits to share the same output line or lines (such as a bus which cannot listen to more than one device at a time). Three-state outputs are implemented in many registers, bus drivers, and flip-flops in the 7400 and 4000 series as well as in other types, but also internally in many integrated circuits. Other typical uses are internal and external buses in microprocessors, memories, and peripherals. Many devices are controlled by 25

26 an active-low input called OE (Output Enable) which dictates whether the outputs should be held in a highimpedance state or drive their respective loads (to either 0- or 1-level). The whole concept of the third state (Hi-Z) is to effectively remove the device's influence from the rest of the circuit. If more than one device is electrically connected, putting an output into the Hi-Z state is often used to prevent short circuits, or one device driving high (logical 1) against another device driving low (logical 0). Three-state buffers can also be used to implement efficient multiplexers, especially those with large numbers of inputs. [2] In particular, they are essential to the operation of a shared electronic bus. Three-state logic can reduce the number of wires needed to drive a set of LEDs (tristate multiplexing or Charlieplexing) Cache All modern processors starting with the 486 family include an integrated L1 cache and controller. The integrated L1 cache size varies from processor to processor, starting at 8KB for the original 486DX and now up to 32KB, 64KB, or more in the latest processors. Since L1 cache is always built in to the processor die, it runs at the full-core speed of the processor internally. By full-core speed, I mean this cache runs at the higher clock multiplied internal processor speed rather than the external motherboard speed. This cache basically is an area of very fast memory built in to the processor and is used to hold some of the current working set of code and data. Cache memory can be accessed with no wait states because it is running at the same speed as the processor core. Using cache memory reduces a traditional system bottleneck because system RAM often is much slower than the CPU. This prevents the processor from having to wait for code and data from much slower main memory therefore improving performance. Without the L1 cache, a processor frequently would be forced to wait until system memory caught up How Cache Works To learn how the L1 and L2 cache work, consider the following analogy. The main feature of L1 cache is that it has always been integrated into the processor core, where it runs at the same speed as the core. This, combined with the hit ratio of 90 percent or greater, makes L1 cache very important for system performance. Just as with the L1 cache, most L2 caches have a hit ratio also in the 90 percent range, which means that if you look at the system as a whole, 90 percent of the time it will be running at full speed (233MHz in this example) by retrieving data out of the L1 cache. Ten percent of the time it will slow down to retrieve the data from the L2 cache. Ninety percent of the time the processor goes to the L2 cache the data will be in the L2, and 10 percent of that time you will have to go to the slow main memory to get the data due to an L2 cache miss. This means that by combining both caches, our sample system runs at full processor speed 90 percent of the time (233MHz in this case), motherboard speed nine percent (90 percent of 10 percent) of the time (66MHz in this case), and RAM speed about one percent (10 percent of 10 percent) of the time (16MHz in this case). You can clearly see the importance of both the L1 and L2 caches; without them the system will be using main memory more often, which is significantly slower than the processor. 26

27 PERIPHERAL INTERFACING Functions When one or more I/O devices (peripherals) are to be connected to a for each device, called peripheral interface, is required. The interface incorporate commonly the following four functions: (a) Buffering peripheral. (b) Address Decoding : Which is required to select one of the several peripherals connected in the system. (c) Command Decoding : Which is required for peripherals that perform actions other than data transfers. (d) Timing and Control : All the above functions require timing and control BASIC CPU ARCHITECTURES CISC vs. RISC There are two types of fundamental CPU architecture: complex instruction set computers (CISC) and reduced instruction set computers (RISC). CISC is the most prevalent and established microprocessor architecture, while RISC is a relative newcomer. Intel s 80x86 and Pentium microprocessor families are CISC-based, although RISC-type functionality has been incorporated into Pentium CPUs. Motorola s family of microprocessors is another example of this type of architecture. Sun Microsystems SPARC microprocessors and MIPS R2000, R3000 and R4000 families dominate the RISC end of the market; however, Motorola s PowerPC, G4, Intel s i860, and Analog Devices Inc. s digital signal processors (DSP) are in wide use. In the PC/Workstation market, Apple Computers and Sun employ RISC microprocessors as their choice of CPU.` Table 1 CISC and RISC CISC Large instruction set Complex, powerful instructions Instruction sub-commands micro-coded in on board ROM Compact and versatile register set Numerous memory addressing options for operands RISC Compact instruction set Simple hard-wired machine code and control unit Pipelining of instructions Numerous registers Compiler and IC developed simultaneously The difference between the two architectures is the relative complexity of the instruction sets and underlying electronic and logic circuits in CISC microprocessors. For example, the original RISC I prototype had just 31 instructions, while the RISC II had 39. In the RISC II prototype, these instructions are hard-wired into the microprocessor using 41,000 integrated transistors, so that when a program instruction is presented for execution it can be processed immediately. This typifies the pure RISC approach, which results in up-to-a fourfold increase in processing power over comparable CISC processors. 27

28 In contrast, the Intel 386 has 280,000 and uses microcode stored in on-board ROM to process the instructions. Complex instructions have to be first decoded in order to identify which microcode routine needs to be executed to implement the instructions. The Pentium II used 9.5 million transistors and while older microcode is retained, the most frequently used and simpler instructions, such as MMX, are hardwired. Thus Pentium CPUs are essentially a hybrid, however they are still classified as RISC as their basic instructions are complex. Remember the internal transistor logic gates in a CPU are opened and closed under the control of clock pulses (i.e. electrical voltage values of 0 or 5 V (volts) being 0 or 1). These simply process the binary machine code or data by producing predetermined outputs for given inputs. Machine code or instructions (the binary equivalent of high level programming code) control the operation of the CPU so that logical or mathematical operations can be executed. In CISC processors, complex instructions are first decoded and the corresponding microcode routine dispatched to the execution unit. The decode activity can take several clock cycles depending on the complexity of the instruction. In the 1970s, an IBM engineer discovered that 20% of the instructions were doing 80% of the work in a typical CPU. In addition, he found that a collection of simple instructions could perform the same operation as a complex instruction in less clock cycles. This led him to propose an architecture based on reduced instruction set size, where small instructions could be executed without decoding and in parallel with others. As indicated, this simplified CPU design and made for faster processing of instructions with reduced overhead in terms of clock cycles. Inside the CPU Figure 1 Typical Microprocessor Architectures The basic function of a CPU is to fetch, decode and execute instructions held in ROM or RAM. To accomplish this it must fetch data from an external memory source and transfer it into its own internal memory, each addressable component of which is called a register. It must also be able to distinguish between instructions and operands, that is, the. read/write memory locations containing the data to be operated on. These may be byte addressable location in ROM, RAM or in the CPU s own registers. In 28

29 addition, the CPU must perform additional tasks such as responding to external events such as resets and interrupts, provide memory management facilities to the operating system, etc. A consideration of the fundamental components in a basic microprocessor is first undertaken before introducing more complex modern devices. Figure 6 illustrates a typical microprocessor architecture Microprocessors must perform the following activities: Provide temporary storage for addresses and data Perform arithmetic and logic operations Control and schedule all operations Registers Registers for a variety of purposes such as holding the address of instructions and data, storing the result of an operation, signaling the result of a logic operation, or indicating the status of the program or the CPU itself. Some registers may be accessible to programmers, while others are reserved for us by the CPU itself. Registers store binary values such as 1 or 0 as electrical voltages of say 5 volts (or less) or 0 volts. They consist of several integrated transistors which are configured as a flip-flop circuits each of which can be switched into a 1 or 0 state. They remain in that state until changed under control of the CPU or until the power is removed from the processor. Each register has a specific name and is addressable, some, however, are dedicated to specific tasks while the majority are general purpose. The width of a register depends on the type of CPU, e.g., a 16, 32 or 64 bit microprocessor. In order to provide backward compatibility, registers may be sub-divided. For example, the Pentium processor is a 32 bit CPU, and its registers are 32 bits wide. Some of these are sub-divided and named as 8 and 16 bit registers in order to run 8 and 16 bit applications designed for earlier x86 microprocessors Instruction Register When the Bus Interface Unit receives an instruction it transfers it to the Instruction Register for temporary storage. In Pentium processors the Bus Interface Unit transfers instructions to the L1 I-Cache, there is no instruction register as such Stack Pointer A stack is a small area of reserved memory used to store the data in the CPU s registers when: (1) system calls are made by a process to operating system routines; (2) when hardware interrupts generated by input/output (I/O) transactions on peripheral devices; (3) when a process initiates an I/O transfer; and (4) when a process rescheduling event occurs on foot of a hardware timer interrupt. This transfer of register contents is called a context switch. The stack pointer is the register which holds the address of the most recent stack entry. Hence, when a system call is made by a process (to say print a document) and its context is stored on the stack, the called system routine uses the stack pointer to reload the register contents when it is finished printing. Thus the process can continue where it left off Instruction Decoder The Instruction Decoder is an arrangement of logic elements which act on the bits that constitute the instruction. Simple instructions with corresponding logic hard-wired into the execution unit are simply passed to the Execution Unit (and/or the MMX in the Pentium II, III and IV), complex instructions are decoded so that related microcode modules can be transferred from the CPU s microcode ROM to the execution unit. The Instruction Decoder will also store referenced operands in appropriate registers so data at the memory locations referenced can be fetched Program or Instruction Counter 29

30 The Program Counter (PC) is the register that stores the address in primary memory (RAM or ROM) of the next instruction to be executed. In 32 bit systems, this is a 32 bit linear or virtual memory address that references a byte (the first of 4 required to store the 32 bit instruction) in the process s virtual memory address space. This value is translated to determine the real memory address in which the instruction is stored. When the referenced instruction is fetched, the address in the PC is incremented to the address of the next instruction to be executed. Remember each byte in RAM is individually addressable, however each complete instruction is 32 bits or 4 bytes, and the address of the next instruction in the process will be 4 bytes on Accumulator The accumulator may contain data to be used in a mathematical or logical operation, or it may contain the result of an operation. General purpose registers are used to support the accumulator by holding data to be loaded to/from the accumulator Computer Status Word (CSW) or Flag Register The result of a ALU operation may have consequences of subsequent operations; for example, changing the path of execution. Individual bits in the CSW are set or reset in accordance with the result of mathematical or logical operations. Also called a flag, each bit in the register has a pre-assigned meaning and the contents are monitored by the control unit to help control CPU related actions Arithmetic and Logic Unit The Arithmetic and Logic Unit (ALU) performs all arithmetic and logic operations in a microprocessor viz. addition, subtraction, logical AND, OR, EX-OR, etc. A typical ALU is connected to the accumulator and general purpose registers and other CPU components that help transfer the result of its operations to RAM via the Bus Interface Unit and the system bus. The results may also be written into internal or external caches Control Unit The control unit coordinates and manages CPU activities, in particular the execution of instructions by the arithmetic and logic unit (ALU). In Pentium processors its role is complex, as microcode from decoded instructions are pipelined for execution by two ALUs The System Clock The Intel 8088 CPU had a clock speed of 4.77 MHz; that is, its internal logic gates were opened and closed under the control of a square wave pulsed signal that had a frequency of 4.77 million cycles per second. Alternatively put, the logic gates opened and closed 4.77 million times per second. Thus, instructions and data were pumped through the integrated transistor logic circuits at a rate of 4.77 million times per second. Later designs ran at higher speeds viz. the i MHz, the i MHz, i MHz. Where does this clock signal come from? Each motherboard is fitted with a quartz oscillator in a metal package that generates a square wave clock pulse of a certain frequency. In i8088 systems the crystal oscillator ran at MHz and this was fed to the i8284 to generate the system clock frequency of 4.77 MHz in earlier system, to 10 MHz is later designs. Later, the i286 PCs had a 12 MHz crystal which provided i82284 IC multiplier/divider with the primary clock signal. This then divided/multiplied the basic 12 MHz to generate the system clock signal of 8-20 MHz. With the advent of the i486dx, the system clock signal, which ran at 25 or 33 MHz, was effectively multiplied by factors of 2, 3 or more to deliver an internal CPU clock speed 30

31 of 50, 66, 75, 100 MHz. This approach is used in Pentium IV architectures, where the primary crystal source delivers a relatively slow 50 MHz clock signal that is then multiplied to the system clock speed of MHz. The internal multiplier in the Pentium then multiplies this by a fact or 20+ to obtain speeds of 2 Ghz and above Instruction Cycle An instruction cycle consists of the activities required to fetch and execute an instruction. The length of time take to fetch and execute is measured in clock cycles. In CISC processors this will take many clock cycles, depending on the complexity of the instruction and number of memory references made to load operands. In RISC computers the number of clock cycles are reduced significantly. When the CPU finishes the execution of an instruction it transfers the content of the program or instruction register into the Bus Interface Unit (1 clock cycle). This is then gated onto the system address bus and the read signal is asserted on the control bus (1 clock cycle). This is a signal to the RAM controller that the value of this address is to be read from memory and loaded onto the data bus (4+ clock cycles). The instruction is read in from the data bus and decoded (2 + clock cycles). The fetch and decode activities constitute the first machine cycle of the instruction cycle. The second machine cycle begins when the instruction s operand is read from RAM and ends when the instruction is executed and the result written back to memory. This will take at least another 8+ clock cycles, depending on the complexity of the instruction. Thus an instruction cycle will take at least 16 clock cycles, a considerable length of time. Together, RISC processors and fast RAM can keep this to a minimum. However, Intel made advances by super pipelining instructions, that is by interleaving fetch, decode, operand read, execute, and retire (i.e. write the result of the instruction to RAM) activities into two separate pipelines serving two ALUs PROGRAMMING SYSTEM Computer Program A series of instructions that direct a computer to perform tasks Such as? Who is the programmer? Programming language is a series of rules for writing the instructions There are hundreds of computer programs need-based! Programming language - Two basic types: Low- and high-level programming languages Low-level: Programming language that is machine-dependent _ Must be run on specific machines High-level: Language that is machine-independent _ Can be run on different types of machines Categories of programming languages Machine language Only language computer understands directly Assembly language Instructions made up of symbolic instruction codes Assembler converts the source code to the machine language Third-generation language Uses a series of English-like words to write instructions 31

32 Procedural language -> Programming instructions to tell computer what to accomplish and how to do it Compiler: _ Separate program that generates programming list (consists of errors) _ Program that converts entire source program into machine Nonprocedural language -> Programmer specifies only what the program should accomplish; it does not explain how Forth-generation language Syntax is closer to human language than that of a 3GL SQL and report generator are examples Fifth-generation language Provides visual or graphical interface for creating source code Visual Basic.NET is an example - Common procedural programming languages BASIC _ Designed for use as a simple, interactive problem-solving language _ Beginner's All-purpose Symbolic Instruction Code COBOL C (Changed B to C!)language before executing it Object program _ Used for execution later Interpreter _ Program that translates and executes one program code statement at a time Microprocessor Languages Machine language a computer can understand only special signals, which are represented by 1s and Os. These two digits are called binary digits. Computer understands program written in binary digits. The language, which uses binary digits, is called the machine level language. Machine language has its own advantages and disadvantages. 1. Machine Dependent: As the internal design of the computer differ from one computer to another, their machine codes are also different. So, the program designed for one type of machine cannot be 32

33 used for another type of machine. 2. Fast processing: As the machine code instructions are directly understood by the computer and do not require any translator, the program written in the machine language are very fast and processed very quickly. 3. Error prone: As the programmer has to write all the instructions using 0's and 1's it is a very cumbersome job, the chances of error prone codes are more in writing a machine level language program. 4. Difficult to use: As machine language uses only 0 and 1 two symbols to represent all data and instructions it is very difficult to remember the machine codes for the different commands Assembly language Even the incredibly simple microprocessor will have a fairly large set of instructions that it can perform. The collection of instructions is implemented as bit patterns, each one of which has a different meaning when loaded into the instruction register. Humans are not particularly good at remembering bit patterns, so a set of short words are defined to represent the different bit patterns. This collection of words is called the assembly language of the processor. An assembler can translate the words into their bit patterns very easily, and then the output of the assembler is placed in memory for the microprocessor to execute. An opcode (operation code) is the portion of a machine language instruction that specifies the operation to be performed. Their specification and format are laid out in the instruction set architecture of the processor in question (which may be a general CPU or a more specialized processing unit). Apart from the opcode itself, an instruction normally also has one or more specifiers for operands (i.e. data) on which the operation should act, although some operations may have implicit operands, or none at all. Assembly language, or just assembly, is a low-level programming language, which uses mnemonics, instructions and operands to represent machine code. This enhances the readability while still giving precise control over the machine instructions High level languages PROGRAM TRANSLATORS Since a computer can only understand machine language, any program written in a High level language such as Visual Basic, cannot be executed directly; therefore, it must be first translated to machine language. In order to convert it to machine language a translator is required. There are 3 types of translators used for translating a program written in High level language or assembly language to a form that the computer can execute (i.e., machine code). The three types of translators are: 1. Assembler Assembly language is a low-level programming language in which a mnemonic is used to represent each of the machine language instructions. Assembly languages were developed to make programming easy. Since the computer cannot understand assembly language, however, a program called assembler is used to convert assembly language programs into machine code 2. Compiler The high-level languages are English-like and easy to learn and program. A Compiler is a program that translates a high level language into machine code. The Visual Basic compiler, for example, translates a program written in Pascal into machine code that can be run on a PC. 33

34 Advantages of a Compiler 1. Fast in execution. 2. The object/executable code produced by a compiler can be distributed or executed without having to have the compiler present. 3. The object program can be used whenever required without the need to of recompilation. Disadvantages of a Compiler 1. Debugging (Correcting errors) a program is much harder. Therefore, not so good at finding errors. 2. When an error is found, the whole program has to be re-compiled. 3. Interpreter An Interpreter is also a program that translates high-level source code into executable code. However, the difference between a compiler and an interpreter is that an interpreter translates one line at a time and then executes it, no object code is produced and so the program has to be interpreted each time, it is to be run. If the program performs a section code 1000 times, then the section is translated into machine code 1000 times since each line is interpreted and then executed. Advantages 1. Good at locating errors in programs 2. Debugging is easier since the interpreter stops when it encounters an error. 3. Useful for learning purpose. Note: Debugging is the process of finding and removing errors from a program. Disadvantages 1. Rather slow. 2. No object code is produced, so a translation has to be done every time the program is running. 3. For the program to run, the Interpreter must be present DATA TRANSFER Data exchange or transfers which occur between a peripheral device and the μc fall into one of the following two broad categories: Programmed Data Transfer A software routine residing in memory requests the peripheral device for data transfer to or from the μp. Generally, the data is transferred to or from the accumulator though in some μps, others internal registers may also participate in the transfer. Programmed data transfers are generally used when a small amount of data is transferred with relatively slow I/O devices, e.g., A/D and D/A converters, peripheral multiplier, peripheral floating point arithmetic unit etc. In these cases, usually one word of data is transferred at a time Direct Memory Access (DMA) Transfer or Cycle Stealing Transfer In this mode, the data transfer is controlled by the peripheral device. The μp is forced to hold on by an I/O device until the data transfer between the device and the memory is complete. Since the data control transfer is controlled entirely by hardware, the interface is more complex than that required for a programmed data transfer. DMA transfer is used when a large block of data is to be transferred, for example, for transferring data from peripheral mass storage devices like the floppy disk and high-speed card reader Microprocessors vs microcontrollers Microprocessors: high performance, general purpose brains for PCs and workstations Instruction decode and control, arithmetic/logic operations, registers, timing, external control Microcontrollers: 34

35 devices with high levels of integration for embedded control Microprocessor functions plus on-chip memory and peripheral functions (e.g. ports, timers) Microprocessor Includes memory management unit, lots of cache Performance is the most important feature (cost is important, but secondary) Used mainly in desktop machines Microcontroller Integrated RAM and ROM, no cache Includes lots of peripherals Used mainly in embedded applications and often involves real-time control Important features include: low cost, low power consumption, number of integrated peripherals, interrupt response time, amount of RAM and ROM 35

36 1.7. ARCHITECTURAL ADVANCEMENT The first microprocessor was announced in 1971 by Intel Corporation, U.S.A. This was the Intel It was on a single chip and was a 4-bit microprocessor (i.e., operated on 4 bits of data at a time). Encouraged by the success of 4004, Intel Corp. introduced its enhanced version, the Intel Many other companies also announced 4-bit microprocessors, examples are Rockwell International s PPS4, NEC s μcom 4 and Toshiba s T3472. The first 8-bit microprocessor was announced in 1973, again by Intel Corp. This was the Intel An improved version, Intel 8030, followed. Several other companies followed the suit. Today the batter known 8-bit mps are Intel s 8085, Motorola s M6800, NEC s μcom85af, National * SC/MP, Zilog Corporation s Z80 and Fairchild s F8. Then followed 12-bit and 16-bit μps. Examples of 12-bit μps are Intersil s IM 6100 and Toshiba s T3190 and those of 16-bit μps Intel s 8086, Fairchild s 9440, Texas Instrument s TMS 9940 and TMS 9980, Zilog s Z8000, Motorola s M The developments in μp since 1971 have been in the direction of (a) improving architecture, (b) improving instruction set, (c) increasing speeds, (d) simplifying power requirements and (e) incorporating more and more memory space and I/O facilities in the same chip (thus giving use to single chip computers). The date is the year that the processor was first introduced. Many processors are reintroduced at higher clock speeds for many years after the original release date. Transistors is the number of transistors on the chip. You can see that the number of transistors on a single chip has risen steadily over the years. Microns is the width, in microns, of the smallest wire on the chip. For comparison, a human hair is 100 microns thick. As the feature size on the chip goes down, the number of transistors rises. Clock speed is the maximum rate that the chip can be clocked. Clock speed will make more sense in the next section. Data Width is the width of the ALU. An 8-bit ALU can add/subtract/multiply/etc. two 8-bit numbers, while a 32-bit ALU can manipulate 32-bit numbers. An 8-bit ALU would have to execute 4 instructions to add two 32- bit numbers, while a 32-bit ALU can do it in one instruction. In many cases the external data bus is the same width as the ALU, but not always. The 8088 had a 16-bit ALU and an 8-bit bus, while the modern Pentiums fetch data 64 bits at a time for their 32-bit ALUs. MIPS stands for Millions of Instructions Per Second, and is a rough measure of the performance of a CPU. Modern CPUs can do so many different things that MIPS ratings lose a lot of their meaning, but you can get a general sense of the relative power of the CPUs from this column. In general, there is a relationship between clock speed and MIPS. The maximum clock speed is a function of the manufacturing process and delays within the chip. There is also a relationship between the number of transistors and MIPS. For example, the 8088 clocked at 5 MHz but only executed at 0.33 MIPS (about 1 instruction per 15 clock cycles). Modern processors can often execute at a rate of 2 instructions per clock cycle. That improvement is directly related to the number of transistors on the chip Key Architectural Trends Increase performance at 1.6x per year (2X/1.5yr) True from 1985-present Combination of technology and architectural enhancements 36

37 Technology provides faster transistors ( 1/lithographic feature size) and more of them Faster transistors leads to high clock rates More transistors ( Moore s Law ): Architectural ideas turn transistors into performance Responsible for about half the yearly performance growth Two key architectural directions Sophisticated memory hierarchies Exploiting instruction level parallelism Memory Hierarchies Caches: hide latency of DRAM and increase BW CPU-DRAM access gap has grown by a factor of 30-50! Trend 1: Increasingly large caches On-chip: from 128 bytes (1984) to 100,000+ bytes Multilevel caches: add another level of caching First multilevel cache:1986 Secondary cache sizes today: 128,000 B to 16,000,000 B Third level caches: 1998 Trend 2: Advances in caching techniques: Reduce or hide cache miss latencies early restart after cache miss (1992) nonblocking caches: continue during a cache miss (1994) Cache aware combos: computers, compilers, code writers prefetching: instruction to bring data into cache early Exploiting Instruction Level Parallelism (ILP) ILP is the implicit parallelism among instructions (programmer not aware) Exploited by Overlapping execution in a pipeline Issuing multiple instruction per clock superscalar: uses dynamic issue decision (HW driven) VLIW: uses static issue decision (SW driven) 1985: simple microprocessor pipeline (1 instr/clock) 1990: first static multiple issue microprocessors 1995: sophisticated dynamic schemes determine parallelism dynamically execute instructions out-of-order speculative execution depending on branch prediction Off-the-shelf ILP techniques yielded 15 year path of 2X performance every 1.5 years => 1000X faster! ClusterOnaChip (CoC) Use several simple processors on a single chip: Performance goes up linearly in number of transistors Simpler processors can run at faster clocks Less design cost/time, Less time to market risk (reuse) 37

38 Inspiration: Google Search engine for world: 100M/day Economical, scalable build block: PC cluster today 8000 PCs, disks Advantages in fault tolerance, scalability, cost/performance 32-bit MPU as the new Transistor Cluster on a chip with 1000s of processors enable amazing MIPS/$, MIPS/watt for cluster applications MPUs combined with dense memory + system on a chip CAD 30 years ago Intel 4004 used 2300 transistors: when bit RISC processors on a single chip? VIRAM-1 Integrated Processor/Memory Microprocessor 256-bit media processor (vector) 14 MBytes DRAM billion operations per second 2W at MHz Industrial strength compiler 280 mm 2 die area x 15 mm ~200 mm 2 for memory/logic DRAM: ~140 mm 2 Vector lanes: ~50 mm 2 Technology: IBM SA-27E 0.18mm CMOS 6 metal layers (copper) Transistor count: >100M Implemented by 6 Berkeley graduate students given below) 38

39 Family of Microprocessors 1978: 8086 (16 bit architecture) 1980: 8087 Floating point coprocessor is added 1982: Increases address space to 24 bits 1985: 80386: 32 bits Add, Virtual Mem & new add modes Protected mode (OS support) : 80486/Pentium/Pro Added a few instructions of base MMX 1997: Pentium II 57 new MMX instructions are added, 1999: Pentium III: Out of Order, added another 70 Streaming SIMD Ext (SSE) 2001: Pentium 4 Net burst, another 144 instructions (SSE2) 2003: PI4 HT, Trace Cache 2005: Centrino, low power 2007: Core architecture, Duo 2008: Atom, Quad core with HT :Multi core (Large chip multiprocessor) 2010 core i core i5 Core i7.towards smaller technology(self check)reference Wikipedia MANUFACTURING TECHNOLOGIES Broadly two technologies have been used in the manufacturer of μps: MOS and Bipolar. The majority of μps available in the market use MOS technology because of its two distinct merits, namely, a higher component density and a lower manufacturing cost. The bipolar-technologybased μps are limited to special applications that call for high speeds in which respect MOS devices are inferior. Because of the size problem the bipolar μps are usually made in bit-slice configuration; examples being Intel s 3002 (2-bit slice, TTL), Transitron s 1601 (4-bit slice, TTL) and Texas Instrument s SBP 0400 (4-bit slice, TIL). The first few types of μps to be announced (e.g., 4004, 4040, 8008) were based on PMOS technology, which is now obsolete for μps because of its speed limitation. The NMOS is the main technology today in use for low cost μps (e.g., 8080, 8085, Z-80, , 6800, 8086, Z-8000, 68000). The CMOS technology based μps (e.g., RCA s COSMAC) have limited application because of lower packing density and higher cost. The exceptions are the less cost-sensitive military and aerospace applications, where low power dissipation (typical of the CMOS devices) is of prime importance SUMMARY The various concepts and terms discussed in this chapter are summarized below: 39

40 Computer Structure Digital Computer-a programmable machine that processes binary data. It includes four components: CPU (ALU plus control unit), memory, input, and output. CPU-the Central Processing Unit. The group of circuits that processes data and provides control signals and timing. It includes the arithmetic/logic unit, registers, instruction decoder, and the control unit. ALU-the group of circuits that performs arithmetic and logic operations. The ALU is a part of the CPU. Control Unit-The group of circuits that provides timing and signals to all operations in the computer and controls data flow. Memory-a medium that stores binary information (instructions and data). Input -a device that transfers information from the outside world to the computer. Output-a device that transfers information from the computer to the outside world Microprocessor-Based Systems Microprocessor-a semiconductor device (integrated circuit) that is manufactured by using the large-scale integration technique. It includes the ALU, register arrays, and control circuits on a single chip. Microcomputer-a computer that uses a microprocessor as its CPU. It includes four components: microprocessor, memory, input, and output. Bus---a group of lines used to transfer bits between the microprocessor and other components of the computer system. ROM-Read-Only Memory. A memory that stores binary information permanently. The information can be read from this memory but cannot be altered. R/WM-Read/Write Memory. A memory that stores binary information during the operation of the computer. This memory is used as a writing pad to write user programs and data. The information stored in this memory can be easily read and altered Computer Languages Machine Language-the binary medium of communication with a computer through a designed set of instructions specific to each computer. 40

41 Assembly Language-a medium of communication with a computer in which programs are written in mnemonics. An assembly language is specific to a given computer. Low-Level Language-a medium of communication that is machine-dependent, or specific to a given computer. The machine and the assembly languages of a computer are considered lowlevel languages. Programs written in these languages are not transferable to different types of machines. High-Level Language-a medium of communication independent of a given computer. Programs are written in English-like words, and they can be executed on a machine using a translator (a compiler or an interpreter). Compiler-a program that translates English-like words of a 'high-level language into the machine language of a computer. A compiler reads a given program, called a source code, in its entirety, and then translates the program into the machine language, which is called an object code. Interpreter-a program that translates the English-like statements of a high level language into the machine language of a computer. An interpreter translates one statement at a time from a source code to an object code. Assembler-a computer program that translates an assembly language program from mnemonics to the binary machine code of a computer. 41

42 CHAPTER 2 INTRODUCTION TO 16-BIT MICROPROCESSOR 42

43 2.1. INTRODUCTION Overview or features of 8086 It is a 16-bit Microprocessor (μp).it s ALU, internal registers works with 16bit binary word has a 20 bit address bus can access up to 2 20 = 1 MB memory locations has a 16bit data bus. It can read or write data to a memory/port either 16bits or 8 bit at a time. It can support up to 64K I/O ports. It provides 14, 16 -bit registers. Frequency range of 8086 is 6-10 MHz It has multiplexed address and data bus AD0- AD15 and A16 A19. It requires single phase clock with 33% duty cycle to provide internal timing. It can prefetch upto 6 instruction bytes from memory and queues them in order to speed up instruction execution. It requires +5V power supply. A 40 pin dual in line package is designed to operate in two modes, Minimum mode and Maximum mode. o The minimum mode is selected by applying logic 1 to the MN / MX# input pin. This is a single microprocessor configuration. o The maximum mode is selected by applying logic 0 to the MN / MX# input pin. This is a multi micro processors configuration Pin Diagram of 8086 and Pin description of 8086 Figure shows the Pin diagram of The description follows it. FIGURE 2.1. PINDIAGRAM OF

44 The Microprocessor 8086 is a 16-bit CPU available in different clock rates and packaged in a 40 pin CERDIP or plastic package. The 8086 operates in single processor or multiprocessor configuration to achieve high performance. The pins serve a particular function in minimum mode (single processor mode) and other function in maximum mode configuration (multiprocessor mode). The 8086 signals can be categorized in three groups. o The first are the signal having common functions in minimum as well as maximum mode. o The second are the signals which have special functions for minimum mode o The third are the signals having special functions for maximum mode. The following signal descriptions are common for both modes. AD15-AD0: These are the time multiplexed memory I/O address and data lines. o Address remains on the lines during T1 state, while the data is available on the data bus during T2, T3 and T4. These lines are active high and float to a tristate during interrupt acknowledge and local bus hold acknowledge cycles. A19/S6, A18/S5, A17/S4, and A16/S3: These are the time multiplexed address and status lines. o During T1 these are the most significant address lines for memory operations. o During I/O operations, these lines are low. o During memory or I/O operations, status information is available on those lines for T2, T3, Tw and T4. o The status of the interrupt enable flag bit is updated at the beginning of each clock cycle. o The S4 and S3 combinly indicate which segment registers is presently being used for memory accesses as in below fig. o These lines float to tri-state off during the local bus hold acknowledge. The status line S6 is always low. o The address bit is separated from the status bit using latches controlled by the ALE signal. S4 S3 Indication Alternate Data Stack Code or None Data Whole word Upper byte from or to even address Lower byte from or to even address BHE/S7: The bus high enable is used to indicate the transfer of data over the higher order (D15-D8) data bus as shown in table. It goes low for the data transfer over D15-D8 and is used to derive chip selects of odd address memory bank or peripherals. BHE is low during T1 for read, write and interrupt acknowledge cycles, whenever a byte is to be transferred on higher byte of data bus. The status information is available during T2, T3 and T4. The signal is active low and tristated during hold. It is low during T1 for the first pulse of the interrupt acknowledges cycle. 44

45 RD Read: This signal on low indicates the peripheral that the processor is performing memory or I/O read operation. RD is active low and shows the state for T2, T3, and Tw of any read cycle. The signal remains tristated during the hold acknowledge. READY: This is the acknowledgement from the slow device or memory that they have completed the data transfer. The signal made available by the devices is synchronized by the 8284A clock generator to provide ready input to the The signal is active high. INTR-Interrupt Request: This is a triggered input. This is sampled during the last clock cycles of each instruction to determine the availability of the request. If any interrupt request is pending, the processor enters the interrupt acknowledge cycle. This can be internally masked by resulting the interrupt enable flag. This signal is active high and internally synchronized. TEST: This input is examined by a WAIT instruction. If the TEST pin goes low, execution will continue, else the processor remains in an idle state. The input is synchronized internally during each clock cycle on leading edge of clock. CLK- Clock Input: The clock input provides the basic timing for processor operation and bus control activity. It s an asymmetric square wave with 33% duty cycle Pin description of 8086 Figure shows the Pin functions of FIGURE 2.2 Pin functions of The following pin functions are for the minimum mode operation of M/IO Memory/IO: This is a status line logically equivalent to S2 in maximum mode. When it is low, it indicates the CPU is having an I/O operation, and when it is high, it indicates that the CPU is 45

46 having a memory operation. This line becomes active high in the previous T4 and remains active till final T4 of the current cycle. It is tristated during local bus hold acknowledge. INTA Interrupt Acknowledge: This signal is used as a read strobe for interrupt acknowledge cycles. i.e. when it goes low, the processor has accepted the interrupt. ALE Address Latch Enable: This output signal indicates the availability of the valid address on the address/data lines, and is connected to latch enable input of latches. This signal is active high and is never tristated. DT/R Data Transmit/Receive: This output is used to decide the direction of data flow through the transreceivers (bidirectional buffers). When the processor sends out data, this signal is high and when the processor is receiving data, this signal is low. DEN Data Enable: This signal indicates the availability of valid data over the address/data lines. It is used to enable the transreceivers (bidirectional buffers) to separate the data from the multiplexed address/data signal. It is active from the middle of T2 until the middle of T4. This is tristated during hold acknowledge cycle. HOLD, HLDA- Acknowledge: When the HOLD line goes high, it indicates to the processor that another master is requesting the bus access. The processor, after receiving the HOLD request, issues the hold acknowledge signal on HLDA pin, in the middle of the next clock cycle after completing the current bus cycle. At the same time, the processor floats the local bus and control lines. When the processor detects the HOLD line low, it lowers the HLDA signal. HOLD is an asynchronous input, and is should be externally synchronized. If the DMA request is made while the CPU is performing a memory or I/O cycle, it will release the local bus during T4 provided : 1. The request occurs on or before T2 state of the current cycle. 2. The current cycle is not operating over the lower byte of a word. 3. The current cycle is not the first acknowledge of an interrupt acknowledge sequence. 4. A Lock instruction is not being executed. The following pin functions are applicable for maximum mode operation of S2, S1, and S0 Status Lines: These are the status lines which reflect the type of operation, being carried out by the processor. These become activity during T4 of the previous cycle and active during T1 and T2 of the current bus cycles. LOCK: This output pin indicates that other system bus master will be prevented from gaining the system bus, while the LOCK signal is low. The LOCK signal is activated by the LOCK prefix instruction and remains active until the completion of the next instruction. When the CPU is executing a critical instruction which requires the system bus, the LOCK prefix instruction ensures that other processors connected in the system will not gain the control of the bus. The 8086, while executing the prefixed instruction, asserts the bus lock signal output, which may be connected to an external bus controller. By prefetching the instruction, there is a considerable speeding up in instruction execution in This is known as instruction pipelining. 46

47 S2 S1 S0 Indication Interrupt Acknowledge Read I/O port Write I/O port Halt Code Access Read Memory Write Memory Passive At the starting the CS: IP is loaded with the required address from which the execution is to be started. Initially, the queue will be empty and the microprocessor starts a fetch operation to bring one byte (the first byte) of instruction code, if the CS: IP address is odd or two bytes at a time, if the CS: IP address is even. The first byte is a complete opcode in case of some instruction (one byte opcode instruction) and is a part of opcode, in case of some instructions (two byte opcode instructions), the remaining part of code lie in second byte. The second byte is then decoded in continuation with the first byte to decide the instruction length and the number of subsequent bytes to be treated as instruction data. The queue is updated after every byte is read from the queue but the fetch cycle is initiated by BIU only if at least two bytes of the queue are empty and the EU may be concurrently executing the fetched instructions. The next byte after the instruction is completed is again the first opcode byte of the next instruction. A similar procedure is repeated till the complete execution of the program. The fetch operation of the next instruction is overlapped with the execution of the current instruction. As in the architecture, there are two separate units, namely Execution unit and Bus interface unit. While the execution unit is busy in executing an instruction, after it is completely decoded, the bus interface unit may be fetching the bytes of the next instruction from memory, depending upon the queue status. QS1 QS0 Indication No Operation First Byte of the opcode from the queue 47

48 Empty Queue Subsequent Byte from the Queue RQ/GT0, RQ/GT1 Request/Grant: These pins are used by the other local bus master in maximum mode, to force the processor to release the local bus at the end of the processor current bus cycle. Each of the pin is bidirectional with RQ/GT0 having higher priority than RQ/GT1. RQ/GT pins have internal pull-up resistors and may be left unconnected. Request/Grant sequence is as follows: 1. A pulse of one clock wide from another bus master requests the bus access to During T4(current) or T1(next) clock cycle, a pulse one clock wide from 8086 to the requesting master, indicates that the 8086 has allowed the local bus to float and that it will enter the hold acknowledge state at next cycle. The CPU bus interface unit is likely to be disconnected from the local bus of the system. 3. A one clock wide pulse from the master indicates to the 8086 that the hold request is about to end and the 8086 may regain control of the local bus at the next clock cycle. Thus each master to master exchange of the local bus is a sequence of 3 pulses. There must be at least one dead clock cycle after each bus exchange. The request and grant pulses are active low. For the bus request those are received while 8086 is performing memory or I/O cycle, the granting of the bus is governed by the rules as in case of HOLD and HLDA in minimum mode ARCHITECTURE OF 8086 OR FUNCTIONAL BLOCK DIAGRAM OF has two blocks Bus Interfacing Unit (BIU) and Execution Unit (EU). The BIU performs all bus operations such as instruction fetching, reading and writing operands for memory and calculating the addresses of the memory operands. The instruction bytes are transferred to the instruction queue. EU executes instructions from the instruction system byte queue. Both units operate asynchronously to give the 8086 an overlapping instruction fetch and execution mechanism which is called as Pipelining. This results in efficient use of the system bus and system performance. BIU contains Instruction queue, Segment registers, Instruction pointer, and Address adder. EU contains Control circuitry, Instruction decoder, ALU, Pointer and Index register, Flag register BUS INTERFACE UNIT It provides a full 16 bit bidirectional data bus and 20 bit address bus. The bus interface unit is responsible for performing all external bus operations. 48

49 Specifically it has the following functions: Instruction fetches Instruction queuing, Operand fetch and storage, Address relocation and Bus control. The BIU uses a mechanism known as an instruction stream queue to implement pipeline architecture. This queue permits prefetch of up to six bytes of instruction code. When ever the queue of the BIU is not full, it has room for at least two more bytes and at the same time the EU is not requesting it to read or write operands from memory, the BIU is free to look ahead in the program by prefetching the next sequential instruction. FIGURE 2.3 Block diagram of These prefetching instructions are held in its FIFO queue. With its 16 bit data bus, the BIU fetches two instruction bytes in a single memory cycle. After a byte is loaded at the input end of the queue, it automatically shifts up through the FIFO to the empty location nearest the output. 49

50 The EU accesses the queue from the output end. It reads one instruction byte after the other from the output of the queue. If the queue is full and the EU is not requesting access to operand in memory. These intervals of no bus activity, which may occur between bus cycles, are known as Idle state. If the BIU is already in the process of fetching an instruction when the EU request it to read or write operands from memory or I/O, the BIU first completes the instruction fetch bus cycle before initiating the operand read / write cycle. The BIU also contains a dedicated adder which is used to generate the 20bit physical address that is output on the address bus. This address is formed by adding an appended 16 bit segment address and a 16 bit offset address. For example: The physical address of the next instruction to be fetched is formed by combining the current contents of the code segment CS register and the current contents of the instruction pointer IP register. The BIU is also responsible for generating bus control signals such as those for memory read or write and I/O read or write EXECUTION UNIT The Execution unit is responsible for decoding and executing all instructions. The EU extracts instructions from the top of the queue in the BIU, decodes them, generates operands if necessary, passes them to the BIU and requests it to perform the read or write bys cycles to memory or I/O and perform the operation specified by the instruction on the operands. During the execution of the instruction, the EU tests the status and control flags and updates them based on the results of executing the instruction. If the queue is empty, the EU waits for the next instruction byte to be fetched and shifted to top of the queue. When the EU executes a branch or jump instruction, it transfers control to a location corresponding to another set of sequential instructions. Whenever this happens, the BIU automatically resets the queue and then begins to fetch instructions from this new location to refill the queue. Self check 1: IS there any SFR in 8086, if yes name them? What is the advantage of having two different memories with same effective address? 50

51 REGISTERS The 8086 microprocessor has a total of fourteen registers that are accessible to the programmer. It is divided into four groups. They are: Four General purpose registers Four Index/Pointer registers Four Segment registers Two Other registers General Purpose Registers: Accumulator register consists of two 8-bit registers AL and AH, which can be combined together and used as a 16-bit register AX. AL in this case contains the low order byte of the word, and AH contains the high-order byte. Accumulator can be used for I/O operations and string manipulation. Base register consists of two 8-bit registers BL and BH, which can be combined together and used as a 16-bit register BX. BL in this case contains the low-order byte of the word, and BH contains the highorder byte. BX register usually contains a data pointer used for based, based indexed or register indirect addressing. Count register consists of two 8-bit registers CL and CH, which can be combined together and used as a 16-bit register CX. When combined, CL register contains the low order byte of the word, and CH contains the high-order byte. Count register can be used in Loop, shift/rotate instructions and as a counter in string manipulation Data register consists of two 8-bit registers DL and DH, which can be combined together and used as a 16-bit register DX. When combined, DL register contains the low order byte of the word, and DH contains the high-order byte. Data register can be used as a port number in I/O operations. In integer 32-bit multiply and divide instruction the DX register contains high-order word of the initial or resulting number Index or Pointer Registers These registers can also be called as Special Purpose registers. 51

52 Stack Pointer (SP) is a 16-bit register pointing to program stack, ie it is used to hold the address of the top of stack. The stack is maintained as a LIFO with its bottom at the start of the stack segment (specified by the SS segment register).unlike the SP register, the BP can be used to specify the offset of other program segments. Base Pointer (BP) is a 16-bit register pointing to data in stack segment. It is usually used by subroutines to locate variables that were passed on the stack by a calling program. BP register is usually used for based, based indexed or register indirect addressing. Source Index (SI) is a 16-bit register. SI is used for indexed, based indexed and register indirect addressing, as well as a source data address in string manipulation instructions. Used in conjunction with the DS register to point to data locations in the data segment. Destination Index (DI) is a 16-bit register. Used in conjunction with the ES register in string operations. DI is used for indexed, based indexed and register indirect addressing, as well as a destination data address in string manipulation instructions. In short, Destination Index and SI Source Index registers are used to hold address Segment Registers Most of the registers contain data/instruction offsets within 64 KB memory segment. There are four different 64 KB segments for instructions, stack, data and extra data. To specify where in 1 MB of processor memory these 4 segments are located the processor uses four segment registers. Code segment (CS) is a 16-bit register containing address of 64 KB segment with processor instructions. The processor uses CS segment for all accesses to instructions referenced by instruction pointer (IP) register. CS register cannot be changed directly. The CS register is automatically updated during far jump, far call and far return instructions. Stack segment (SS) is a 16-bit register containing address of 64KB segment with program stack. By default, the processor assumes that all data referenced by the stack pointer (SP) and base pointer (BP) registers is located in the stack segment. SS register can be changed directly using POP instruction. Data segment (DS) is a 16-bit register containing address of 64KB segment with program data. By default, the processor assumes that all data referenced by general registers (AX, BX, CX, DX) and index register (SI, DI) is located in the data segment. DS register can be changed directly using POP and LDS instructions. Extra segment (ES) used to hold the starting address of Extra segment. Extra segment is provided for programs that need to access a second data segment. Segment registers cannot be used in arithmetic operations. 52

53 Other registers of 8086 Instruction Pointer (IP) is a 16-bit register. This is a crucially important register which is used to control which instruction the CPU executes. The ip, or program counter, is used to store the memory location of the next instruction to be executed. The CPU checks the program counter to ascertain which instruction to carry out next. It then updates the program counter to point to the next instruction. Thus the program counter will always point to the next instruction to be executed. Flag Register contains a group of status bits called flags that indicate the status of the CPU or the result of arithmetic operations. There are two types of flags: 1. The status flags which reflect the result of executing an instruction. The programmer cannot set/reset these flags directly. 2. The control flags enable or disable certain CPU operations. The programmer can set/reset these bits to control the CPU's operation. Nine individual bits of the status register are used as control flags (3 of them) and status flags (6 of them).the remaining 7 are not used. A flag can only take on the values 0 and 1. We say a flag is set if it has the value 1.The status flags are used to record specific characteristics of arithmetic and of logical instructions. Control Flags: There are three control flags 1. The Direction Flag (D): Affects the direction of moving data blocks by such instructions as MOVS, CMPS and SCAS. The flag values are 0 = up and 1 = down and can be set/reset by the STD (set D) and CLD (clear D) instructions. 2. The Interrupt Flag (I): Dictates whether or not system interrupts can occur. Interrupts are actions initiated by hardware block such as input devices that will interrupt the normal execution of programs. The flag values are 0 = disable interrupts or 1 = enable interrupts and can be manipulated by the CLI (clear I) and STI (set I) instructions. 3. The Trap Flag (T): Determines whether or not the CPU is halted after the execution of each instruction. When this flag is set (i.e. = 1), the programmer can single step through his program to debug any errors. When this flag = 0 this feature is off. This flag can be set by the INT 3 instruction. 53

54 Status Flags: There are six status flags 1. The Carry Flag (C): This flag is set when the result of an unsigned arithmetic operation is too large to fit in the destination register. This happens when there is an end carry in an addition operation or there an end borrows in a subtraction operation. A value of 1 = carry and 0 = no carry. 2. The Overflow Flag (O): This flag is set when the result of a signed arithmetic operation is too large to fit in the destination register (i.e. when an overflow occurs). Overflow can occur when adding two numbers with the same sign (i.e. both positive or both negative). A value of 1 = overflow and 0 = no overflow. 3. The Sign Flag (S): This flag is set when the result of an arithmetic or logic operation is negative. This flag is a copy of the MSB of the result (i.e. the sign bit). A value of 1 means negative and 0 = positive. 4. The Zero Flag (Z): This flag is set when the result of an arithmetic or logic operation is equal to zero. A value of 1 means the result is zero and a value of 0 means the result is not zero. 5. The Auxiliary Carry Flag (A): This flag is set when an operation causes a carry from bit 3 to bit 4 (or a borrow from bit 4 to bit 3) of an operand. A value of 1 = carry and 0 = no carry. 6. The Parity Flag (P): This flags reflects the number of 1s in the result of an operation. If the number of 1s is even its value = 1 and if the number of 1s is odd then its value = PROGRAMING MODEL As a programmer of the 8086 or 8088 you must become familiar with the various registers in the EU and BIU. FIGURE 2.4 Programming model of

55 The data group consists of the accumulator and the BX, CX, and DX registers. Note that each can be accessed as a byte or a word. Thus BX refers to the 16-bit base register but BH refers only to the higher 8 bits of this register. The data registers are normally used for storing temporary results that will be acted on by subsequent instructions. The pointer and index group are all 16-bit registers (you cannot access the low or high bytes alone). These registers are used as memory pointers. Sometimes a pointer reg will be interpreted as pointing to a memory byte and at other times a memory word. As you will see, the 8086/88 always stores words with the high-order byte in the high-order word address. Register IP could be considered in the previous group, but this register has only one function -to point to the next instruction to be fetched to the BIU. Register IP is physically part of the BIU and not under direct control of the programmer as are the other pointer registers. Six of the flags are status indicators, reflecting properties of the result of the last arithmetic or logical instructions. The 8086/88 has several instructions that can be used to transfer program control to a new memory location based on the state of the flags. Three of the flags can be set or reset directly by the programmer and are used to control the operation of the processor. These are TF, IF, and DF. The final group of registers is called the segment group. These registers are used by the BIU to determine the memory address output by the CPU when it is reading or writing from the memory unit. To fully understand these registers, we must first study the way the 8086/88 divides its memory into segments MEMORY SEGMENTATION Even though the 8086 is considered a 16-bit processor, (it has a 16-bit data bus width) its memory is still thought of in bytes. At first this might seem a disadvantage: Why saddle a 16-bit microprocessor with an 8-bit memory? Actually, there are a couple of good reasons. First, it allows the processor to work on bytes as well as words. This is especially important with I/O devices such as printers, terminals, and modems, all of which are designed to transfer ASCII-encoded (7- or 8-bit) data. Second, many of the 8086's (and 8088's) operation codes are single bytes. Other instructions may require anywhere from two to seven bytes. By being able to access individual bytes, these odd-length instructions can be handled. We have already seen that the 8086/88 has a 20-bit address bus, allowing it to output 2 10, or 1' , different memory addresses. As you can see, words can also be visualized. As mentioned, the 8086 reads 16 bits from memory by simultaneously reading an odd-addressed byte and an even-addressed byte. For this reason the 8086 organizes its memory into an even-addressed bank and an odd-addressed bank. With regard to this, you might wonder if all words must begin at an even address. Well, the answer is yes. However, there is a penalty to be paid. The CPU must perform two memory read cycles: one to fetch the low-order byte and a second to fetch the high-order byte. This slows down the processor but is transparent to the programmer. 55

56 The last few paragraphs apply only to the The 8088 with its 8-bit data bus interfaces to the 1 MB of memory as a single bank. When it is necessary to access a word (whether on an even- or an odd-addressed boundary) two memory read (or write) cycles are performed. In effect, the 8088 pays a performance penalty with every word access. Fortunately for the programmer, except for the slightly slower performance of the 8088, there is no difference between the two processors MEMORY MAP Still another view of the 8086/88 memory space could be as 16 64K-byte blocks beginning at hex address h and ending at address 0FFFFFh. This division into 64K-byte blocks is an arbitrary but convenient choice. This is because the most significant hex digit increments by 1 with each additional block. That is, address 20000h is bytes higher in memory than address 10000h. Be sure to note that five hex digits are required to represent a memory address. The diagram is called a memory map. This is because, like a road map, it is a guide showing how the system memory is allocated. This type of information is vital to the programmer, who must know exactly where his or her programs can be safely loaded. Note that some memory locations are marked reserved and others dedicated. The dedicated locations are used for processing specific system interrupts and the reset function. Intel has also reserved several locations for future H/W and S/W products. If you make use of these memory locations, you risk incompatibility with these future products SEGMENT REGISTERS Within the 1 MB of memory space the 8086/88 defines four 64K-byte memory blocks called the code segment, stack segment, data segment, and extra segment. Each of these blocks of memory is used differently by the processor. The code segment holds the program instruction codes. The data segment stores data for the program. The extra segment is an extra data segment (often used for shared data). The stack segment is used to store interrupt and subroutine return addresses. 56

57 You should realize that the concept of the segmented memory is a unique one. Older-generation microprocessors such as the 8-bit 8086 or Z-80 could access only one 64K-byte segment. This mean that the programs instruction, data and subroutine stack all had to share the same memory. This limited the amount of memory available for the program itself and led to disaster if the stack should happen to overwrite the data or program areas. The four segment registers (CS, DS, ES, and SS) are used to "point" at location 0 (the base address) of each segment. This is a little "tricky" because the segment registers are only 16 bits wide, but the memory address is 20 bits wide. The BIU takes care of this problem by appending four 0's to the low-order bits of the segment register. In effect, this multiplies the segment register contents by 16. FIGURE 2.5 Memory segmentation in The point to note is that the beginning segment address is not arbitrary -it must begin at an address divisible by 16. Another way if saying this is that the low-order hex digit must be 0. Also note that the four segments need not be defined separately. Indeed, it is allowable for all four segments to completely overlap (CS = DS = ES = SS). 57

58 Memory locations not defined to be within one of the current segments cannot be accessed by the 8086/88 without first redefining one of the segment registers to include that location. Thus at any given instant a maximum of 256 K (64K * 4) bytes of memory can be utilized. As we will see, the contents of the segment registers can only be specified via S/W. As you might imagine, instructions to load these registers should be among the first given in any 8086/88 program LOGICAL AND PHYSICAL ADDRESS Addresses within a segment can range from address 00000h to address 0FFFFh. This corresponds to the 64K-byte length of the segment. An address within a segment is called an offset or logical address. A logical address gives the displacement from the address base of the segment to the desired location within it, as opposed to its "real" address, which maps directly anywhere into the 1 MB memory space. This "real" address is called the physical address. What is the difference between the physical and the logical address? The physical address is 20 bits long and corresponds to the actual binary code output by the BIU on the address bus lines. The logical address is an offset from location 0 of a given segment. FIGURE 2.6 address calculation. When two segments overlap it is certainly possible for two different logical addresses to map to the same physical address. This can have disastrous results when the data begins to overwrite the subroutine stack area, or vice versa. For this reason you must be very careful when segments are allowed to overlap. 58

59 You should also be careful when writing addresses on paper to do so clearly. To specify the logical address XXXX in the stack segment, use the convention SS:XXXX, which is equal to [SS] * 16 + XXXX ADVANTAGES OF SEGMENTED MEMORY Segmented memory can seem confusing at first. What you must remember is that the program op-codes will be fetched from the code segment, while program data variables will be stored in the data and extra segments. Stack operations use registers BP or SP and the stack segment. As we begin writing programs the consequences of these definitions will become clearer. An immediate advantage of having separate data and code segments is that one program can work on several different sets of data. This is done by reloading register DS to point to the new data. Perhaps the greatest advantage of segmented memory is that programs that reference logical addresses only can be loaded and run anywhere in memory. This is because the logical addresses always range from 00000h to 0FFFFh, independent of the code segment base. Such programs are said to be relocatable, meaning that they will run at any location in memory. The requirements for writing relocatable programs are that no references be made to physical addresses, and no changes to the segment registers are allowed INTERRUPTS Definition: The meaning of interrupts is to break the sequence of operation. While the cpu is executing a program, on interrupt breaks the normal sequence of execution of instructions, diverts its execution to some other program called Interrupt Service Routine (ISR).After executing ISR, the control is transferred back again to the main program. Interrupt processing is an alternative to polling. Need for Interrupt: Interrupts are particularly useful when interfacing I/O devices, that provide or require data at relatively low data transfer rate. Types of Interrupts: There are two types of Interrupts in They are: (i)hardware Interrupts and (ii)software Interrupts (i) Hardware Interrupts (External Interrupts). The Intel microprocessors support hardware interrupts through: Two pins that allow interrupt requests, INTR and NMI One pin that acknowledges, INTA, the interrupt requested on INTR. INTR and NMI INTR is a maskable hardware interrupt. The interrupt can be enabled/disabled using STI/CLI instructions or using more complicated method of updating the FLAGS register with the help of the POPF instruction. When an interrupt occurs, the processor stores FLAGS register into stack, disables further interrupts, fetches from the bus one byte representing interrupt type, and jumps to interrupt 59

60 processing routine address of which is stored in location 4 * <interrupt type>. Interrupt processing routine should return with the IRET instruction. NMI is a non-maskable interrupt. Interrupt is processed in the same way as the INTR interrupt. Interrupt type of the NMI is 2, i.e. the address of the NMI processing routine is stored in location 0008h. This interrupt has higher priority than the maskable interrupt. Ex: NMI, INTR. (ii) Software Interrupts (Internal Interrupts and Instructions).Software interrupts can be caused by: INT instruction - breakpoint interrupt. This is a type 3 interrupt. INT <interrupt number> instruction - any one interrupt from available 256 interrupts. INTO instruction - interrupt on overflow Single-step interrupt - generated if the TF flag is set. This is a type 1 interrupt. When the CPU processes this interrupt it clears TF flag before calling the interrupt processing routine. Processor exceptions: Divide Error (Type 0), Unused Opcode (type 6) and Escape opcode (type 7). Software interrupt processing is the same as for the hardware interrupts. - Ex: INT n (Software Instructions) Control is provided through: o IF and TF flag bits o IRET and IRETD Self check 2:8085 vs 8086 IS there any software interrupts in 8085, if yes name them? What is the advantage/disadvantage of 8086 interrupt system compared to 8085? Performance of Software Interrupts 1. It decrements SP by 2 and pushes the flag register on the stack. 2. Disables INTR by clearing the IF. 3. It resets the TF in the flag Register. 5. It decrements SP by 2 and pushes CS on the stack. 6. It decrements SP by 2 and pushes IP on the stack. 6. Fetch the ISR address from the interrupt vector table. 60

61 Interrupt Vector Table Functions associated with INT00 to INT04 INT 00 (divide error) INT 01 INT00 is invoked by the microprocessor whenever there is an attempt to divide a number by zero. ISR is responsible for displaying the message Divide Error on the screen For single stepping the trap flag must be 1 After execution of each instruction, 8086 automatically jumps to 00004H to fetch 4 bytes for CS: IP of the ISR. The job of ISR is to dump the registers on to the screen INT 02 (Non maskable Interrupt) When ever NMI pin of the 8086 is activated by a high signal (5v), the CPU Jumps to physical memory location to fetch CS:IP of the ISR assocaiated with NMI. INT 03 (break point) 61

62 A break point is used to examine the cpu and memory after the execution of a group of Instructions. It is one byte instruction whereas other instructions of the form INT nn are 2 byte instructions. INT 04 ( Signed number overflow) There is an instruction associated with this INT 0 (interrupt on overflow). If INT 0 is placed after a signed number arithmetic as IMUL or ADD the CPU will activate INT 04 if 0F = 1. In case where 0F = 0, the INT 0 is not executed but is bypassed and acts as a NOP Performance of Hardware Interrupts NMI : Non maskable interrupts - TYPE 2 Interrupt INTR : Interrupt request - Between 20H and FFH Interrupt Priority Structure General Bus Operation The 8086 has a combined address and data bus commonly referred as a time multiplexed address and data bus. The main reason behind multiplexing address and data over the same pins is the maximum utilization of processor pins and it facilitates the use of 40 pin standard DIP package. The bus can be demultiplexed using a few latches and transreceivers, when ever required. Basically, all the processor bus cycles consist of at least four clock cycles. These are referred to as T1, T2, T3, and T4. The address is transmitted by the processor during T1. It is present on the bus only for one cycle. 62

63 The negative edge of this ALE pulse is used to separate the address and the data or status information. In maximum mode, the status lines S0, S1 and S2 are used to indicate the type of operation. Status bits S3 to S7 are multiplexed with higher order address bits and the BHE signal. Address is valid during T1 while status bits S3 to S7 are valid during T2 through T4. Maximum mode FIGURE 2.7 bus operation signal. In the maximum mode, the 8086 is operated by strapping the MN/MX pin to ground. In this mode, the processor derives the status signal S2, S1, S0. Another chip called bus controller derives the control signal using this status information. In the maximum mode, there may be more than one microprocessor in the system configuration. Minimum mode In a minimum mode 8086 system, the microprocessor 8086 is operated in minimum mode by strapping its MN/MX pin to logic 1. In this mode, all the control signals are given out by the microprocessor chip itself. There is a single microprocessor in the minimum mode system MINIMUM MODE 8086 SYSTEM In a minimum mode 8086 system, the microprocessor 8086 is operated in minimum mode by strapping its MN/MX pin to logic 1. 63

64 In this mode, all the control signals are given out by the microprocessor chip itself. There is a single microprocessor in the minimum mode system. The remaining components in the system are latches, transreceivers, clock generator, memory and I/O devices. Some type of chip selection logic may be required for selecting memory or I/O devices, depending upon the address map of the system. Latches are generally buffered output D-type flip-flops like 74LS373 or They are used for separating the valid address from the multiplexed address/data signals and are controlled by the ALE signal generated by Transreceivers are the bidirectional buffers and some times they are called as data amplifiers. They are required to separate the valid data from the time multiplexed address/data signals. They are controlled by two signals namely, DEN and DT/R. The DEN signal indicates the direction of data, i.e. from or to the processor. The system contains memory for the monitor and users program storage. Usually, EPROM is used for monitor storage, while RAM for user s program storage. A system may contain I/O devices Write Cycle Timing Diagram for Minimum Mode The working of the minimum mode configuration system can be better described in terms of the timing diagrams rather than qualitatively describing the operations. The opcode fetch and read cycles are similar. Hence the timing diagram can be categorized in two parts, the first is the timing diagram for read cycle and the second is the timing diagram for write cycle. The read cycle begins in T1 with the assertion of address latch enable (ALE) signal and also M / IO signal. During the negative going edge of this signal, the valid address is latched on the local bus. The BHE and A0 signals address low, high or both bytes. From T1 to T4, the M/IO signal indicates a memory or I/O operation. At T2, the address is removed from the local bus and is sent to the output. The bus is then tristated. The read (RD) control signal is also activated in T2. The read (RD) signal causes the address device to enable its data bus drivers. After RD goes low, the valid data is available on the data bus. The addressed device will drive the READY line high. When the processor returns the read signal to high level, the addressed device will again tristate its bus drivers. A write cycle also begins with the assertion of ALE and the emission of the address. The M/IO signal is again asserted to indicate a memory or I/O operation. In T2, after sending the address in T1, the processor sends the data to be written to the addressed location. 64

65 The data remains on the bus until middle of T4 state. The WR becomes active at the beginning of T2 (unlike RD is somewhat delayed in T2 to provide time for floating). FIGURE 2.8. Write Cycle Timing Diagram for Minimum Mode The BHE and A0 signals are used to select the proper byte or bytes of memory or I/O word to be read or write. The M/IO, RD and WR signals indicate the type of data transfer as specified in table below Bus Request and Bus Grant Timings in Minimum Mode System of 8086 Hold Response sequence: The HOLD pin is checked at leading edge of each clock pulse. If it is received active by the processor before T4 of the previous cycle or during T1 state of the current cycle, the CPU activates HLDA in the next clock cycle and for succeeding bus cycles, the bus will be given to another requesting master. The control of the bus is not regained by the processor until the requesting master does not drop the HOLD pin low. When the request is dropped by the requesting master, the HLDA is dropped by the processor at the trailing edge of the next clock. 65

66 Minimum Mode Interface When the Minimum mode operation is selected, the 8086 provides all control signals needed to implement the memory and I/O interface. The minimum mode signal can be divided into the following basic groups : 1. Address/data bus 2. Status 3. Control 4. Interrupt and 5. DMA. Each and every group is explained clearly. Address/Data Bus: These lines serve two functions. As an address bus is 20 bits long and consists of signal lines A0 through A19. A19 represents the MSB and A0 LSB. A 20bit address gives the 8086 a 1Mbyte memory address space. More over it has an independent I/O address space which is 64K bytes in length. The 16 data bus lines D0 through D15 are actually multiplexed with address lines A0 through A15 respectively. By multiplexed we mean that the bus work as an address bus during first machine cycle and as a data bus during next machine cycles. D15 is the MSB and D0 LSB. When acting as a data bus, they carry read/write data for memory, input/output data for I/O devices, and interrupt type codes from an interrupt controller. Status signal: The four most significant address lines A19 through A16 are also multiplexed but in this case with status signals S6 through S3. These status bits are output on the bus at the same time that data are transferred over the other bus lines. 66

67 Bit S4 and S3 together from a 2 bit binary code that identifies which of the 8086 internal segment registers are used to generate the physical address that was output on the address bus during the current bus cycle. Code S4S3 = 00 identifies a register known as extra segment register as the source of the segment address. Status line S5 reflects the status of another internal characteristic of the It is the logic level of the internal enable flag. The last status bit S6 is always at the logic 0 level. S4 S3 Segment Register Extra Stack Code / none Data Memory segment status codes Control Signals: The control signals are provided to support the 8086 memory I/O interfaces. They control functions such as when the bus is to carry a valid address in which direction data are to be transferred over the bus, when valid write data are on the bus and when to put read data on the system bus. ALE is a pulse to logic 1 that signals external circuitry when a valid address word is on the bus. This address must be latched in external circuitry on the 1-to-0 edge of the pulse at ALE. Another control signal that is produced during the bus cycle is BHE bank high enable. Logic 0 on this used as a memory enable signal for the most significant byte half of the data bus D8 through D1. These lines also serves a second function, which is as the S7 status line. Using the M/IO and DT/R lines, the 8086 signals which type of bus cycle is in progress and in which direction data are to be transferred over the bus. The logic level of M/IO tells external circuitry whether a memory or I/O transfer is taking place over the bus. Logic 1 at this output signals a memory operation and logic 0 an I/O operation. The direction of data transfer over the bus is signaled by the logic level output at DT/R. When this line is logic 1 during the data transfer part of a bus cycle, the bus is in the transmit mode. Therefore, data are either written into memory or output to an I/O device. On the other hand, logic 0 at DT/R signals that the bus is in the receive mode. This corresponds to reading data from memory or input of data from an input port. The signal read RD and write WR indicates that a read bus cycle or a write bus cycle is in progress. The 8086 switches WR to logic 0 to signal external device that valid write or output data are on the bus. 67

68 On the other hand, RD indicates that the 8086 is performing a read of data of the bus. During read operations, one other control signal is also supplied. This is DEN (data enable) and it signals external devices when they should put data on the bus. There is one other control signal that is involved with the memory and I/O interface. This is the READY signal. READY signal is used to insert wait states into the bus cycle such that it is extended by a number of clock periods. This signal is provided by an external clock generator device and can be supplied by the memory or I/O sub-system to signal the 8086 when they are ready to permit the data transfer to be completed. Interrupt signals: The key interrupt interface signals are interrupt request (INTR) and interrupt acknowledge (INTA). INTR is an input to the 8086 that can be used by an external device to signal that it need to be serviced. Logic 1 at INTR represents an active interrupt request. When an interrupt request has been recognized by the 8086, it indicates this fact to external circuit with pulse to logic 0 at the INTA output. The TEST input is also related to the external interrupt interface. Execution of a WAIT instruction causes the 8086 to check the logic level at the TEST input. If the logic 1 is found, the MPU suspend operation and goes into the idle state. The 8086 no longer executes instructions; instead it repeatedly checks the logic level of the TEST input waiting for its transition back to logic 0. As TEST switches to 0, execution resume with the next instruction in the program. This feature can be used to synchronize the operation of the 8086 to an event in external hardware. There are two more inputs in the interrupt interface: the nonmaskable interrupt NMI and the reset interrupt RESET. On the 0-to-1 transition of NMI control is passed to a nonmaskable interrupt service routine. The RESET input is used to provide a hardware reset for the Switching RESET to logic 0 initializes the internal register of the 8086 and initiates a reset service routine. DMA Interface signals: The direct memory access DMA interface of the 8086 minimum mode consist of the HOLD and HLDA signals. When an external device wants to take control of the system bus, it signals to the 8086 by switching HOLD to the logic 1 level. At the completion of the current bus cycle, the 8086 enters the hold state. In the hold state, signal lines AD0 through AD15, A16/S3 through A19/S6, BHE, M/IO, DT/R, RD, WR, DEN and INTR are all in the high Z state. The 8086 signals external device that it is in this state by switching its HLDA output to logic 1 level. 68

69 2.13. MAXIMUM MODE 8086 SYSTEM Figure 2.9 Minimum Mode Interface In the maximum mode, the 8086 is operated by strapping the MN/MX pin to ground. In this mode, the processor derives the status signal S2, S1, S0. Another chip called bus controller derives the control signal using this status information. In the maximum mode, there may be more than one microprocessor in the system configuration. The components in the system are same as in the minimum mode system. The basic function of the bus controller chip IC8288 is to derive control signals like RD and WR (for memory and I/O devices), DEN, DT/R, ALE etc. using the information by the processor on the status lines. The bus controller chip has input lines S2, S1, S0 and CLK. These inputs to 8288 are driven by CPU. It derives the outputs ALE, DEN, DT/R, MRDC, MWTC, AMWC, IORC, IOWC and AIOWC. The AEN, IOB and CEN pins are especially useful for multiprocessor systems. 69

70 Figure Maximum mode of operation AEN and IOB are generally grounded. CEN pin is usually tied to +5V. The significance of the MCE/PDEN output depends upon the status of the IOB pin. If IOB is grounded, it acts as master cascade enable to control cascade 8259A, else it acts as peripheral data enable used in the multiple bus configurations. INTA pin used to issue two interrupt acknowledge pulses to the interrupt controller or to an interrupting device. IORC, IOWC are I/O read command and I/O write command signals respectively. These signals enable an IO interface to read or write the data from or to the address port. The MRDC, MWTC are memory read command and memory write command signals respectively and may be used as memory read or write signals. All these command signals instructs the memory to accept or send data from or to the bus. For both of these write command signals, the advanced signals namely AIOWC and AMWTC are available. Here the only difference between in timing diagram between minimum mode and maximum mode is the status signals used and the available control and advanced command signals. R0, S1, S2 are set at the beginning of bus cycle.8288 bus controller will output a pulse as on the ALE and apply a required signal to its DT / R pin during T1. In T2, 8288 will set DEN=1 thus enabling transceivers, and for an input it will activate MRDC or IORC. These signals are activated until T4. For an output, the AMWC or AIOWC is activated from T2 to T4 and MWTC or IOWC is activated from T3 to T4. The status bit S0 to S2 remains active until T3 and become passive during T3 and T4. If reader input is not activated before T3, wait state will be inserted between T3 and T4. When the 8086 is set for the maximum-mode configuration, it provides signals for implementing a multiprocessor / coprocessor system environment. By multiprocessor environment we mean that one microprocessor exists in the system and that each processor is executing its own program. 70

71 Usually in this type of system environment, there are some system resources that are common to all processors. They are called as global resources. There are also other resources that are assigned to specific processors. These are known as local or private resources. Coprocessor also means that there is a second processor in the system. In this two processor does not access the bus at the same time. One passes the control of the system bus to the other and then may suspend its operation. In the maximum-mode 8086 system, facilities are provided for implementing allocation of global resources and passing bus control to other microprocessor or coprocessor Memory Read Timing Diagram in Maximum Mode of 8086 FIGURE Memory Read Timing Diagram in Maximum Mode of

72 Memory Write Timing in Maximum mode of 8086 Figure Memory Write Timing in Maximum mode of RQ/GT Timings in Maximum Mode Figure RQ/GT Timings in Maximum Mode 72

73 Figure Interface between MPU and Memory in maximum mode Bus Controller Bus Command and Control Signals 8086 does not directly provide all the signals that are required to control the memory, I/O and interrupt interfaces. Specially the WR, M/IO, DT/R, DEN, ALE and INTA, signals are no longer produced by the Instead it outputs three status signals S0, S1, S2 prior to the initiation of each bus cycle. This 3- bit bus status code identifies which type of bus cycle is to follow. S2S1S0 are input to the external bus controller device, the bus controller generates the appropriately timed command and control signals. S2 S1 S0 Indication 8288 Command Interrupt Acknowledge INTA Read I/O port Write I/O port IORC 73

74 0 1 1 Halt Instruction Fetch Read Memory Write Memory Passive IOWC, AIOWC None MRDC MRDC MWTC, AMWC None The 8288 produces one or two of these eight command signals for each bus cycles. For instance, when the 8086 outputs the code S2S1S0 equals 001; it indicates that an I/O read cycle is to be performed. In the code 111 is output by the 8086, it is signaling that no bus activity is to take place. The control outputs produced by the 8288 are DEN, DT/R and ALE. These 3 signals provide the same functions as those described for the minimum system mode. This set of bus commands and control signals is compatible with the Multibus and industry standard for interfacing microprocessor systems. The output of 8289 are bus arbitration signals: Bus busy (BUSY), common bus request (CBRQ), bus priority out (BPRO), bus priority in (BPRN), bus request (BREQ) and bus clock (BCLK). They correspond to the bus exchange signals of the Multibus and are used to lock other processor off the system bus during the execution of an instruction by the In this way the processor can be assured of uninterrupted access to common system resources such as global memory. Queue Status Signals: Two new signals that are produced by the 8086 in the maximum-mode system are queue status outputs QS0 and QS1. Together they form a 2-bit queue status code, QS1QS0. Following table shows the four different queue status. QS1 QS0 Queue Status 0 (low) 0 Queue Empty. The queue has been reinitialized as a result of the execution of a transfer instruction. 0 1 First Byte. The byte taken from the queue was the first byte of the instruction. 74

75 1 0 Queue Empty. The queue has been reinitialized as a result of the execution of a transfer instruction. 1 1 Subsequent Byte. The byte taken from the queue was a subsequent byte of the instruction. Table - Queue status codes Local Bus Control Signal Request / Grant Signals: In a maximum mode configuration, the minimum mode HOLD, HLDA interface is also changed. These two are replaced by request/grant lines RQ/ GT0 and RQ/ GT1, respectively. They provide a prioritized bus access mechanism for accessing the local bus DIRECT MEMORY ACCESS DMA is a type of I/O technique in which data can be transferred between the micro computer memory and an external device without utilising the microprocessor. The DMA is typically used to transfer blocks of data between the memory Subsystem and an external device. A DMA write operation transfers data from an external device to memory. Since the main purpose of DMA operation is to transfer data between external devices and memory without involving the MPU, another device is required. This device is called a DMA controller. The DMA controller must be capable of performing read and write operations in the same manner as the MPU. Therefore, the DMA controller is actually a special- purpose microprocessor whose only task is to perform high-speed data transfer between memory and an external device. The major difference between an I/O program controlled transfer and DMA is that data transfer does not employ the registers of the CPU. The primary advantage of the DMA data transfer technique is that it provides an efficient transfer of large amount of data between storage devices and the main memory without involving the CPU. Several DMA transfer combinations are possible. o Memory to peripheral. o Peripheral to memory. o Memory to memory. o Peripheral to peripheral DMA request takes precedence over all other bus activities, including interrupts. In fact, no interrupt- maskable or non-maskable- will be recognised during a DMA operation. 75

76 DMA Controller The DMA controller can issue commands to the memory that behave exactly like the commands issued by the CPU. The DMA controller in a sense is a second processor in the system but is dedicated to an I/O function. The DMA controller as shown below connects one or more I/O ports directly to memory, where the I/O data stream passes through the DMA controller faster and more efficiently than through the processor as the DMA channel is specialized to the data transfer task. Figure The DMA interface The DMA adds one more level of complexity to the I/O interface because a DMA controller has independent access to memory. One set of wires (bus) can carry at most one transaction at a time. If the DMA and a microprocessor share the signal wire to memory there must be a mechanism to arbitrate which shall have access to memory when both attempt to at the same time Functional behaviour of a DMA transaction 1. The processor transmits the following information to a DMA controller: (a) beginning address in memory (b) block length (number of words to transfer) (c) direction (memory-to-device or device-to-memory) (d) port ID (e) end of block action (interrupt request or no interrupt request). 2. The processor returns to other activities while the DMA controller starts the data transfer. 3. Each time the DMA controller accesses memory, it synchronises this memory request with an idle period of the processor--to do this the possibilities are: (a) force an immediate disabling of the processor, or (b) request a halt of the processor, and await an acknowledgement, or 76

77 (c) time the DMA access to a clock interval or status signal of the processor that signals an idle cycle. 4. When the DMA controller accesses an I/O port or memory, it uses the same functional control signals as used by the processor. I/O port activity can be performed on dedicated lines that do not have to be synchronised with the processor. 5. At the completion of the block transfer, the DMA controller raises an interrupt request if the interrupts are "armed" and otherwise indicates completion in its status register. 6. The processor recognises I/O completion (either by interrupt or by reading the status register); thereafter the activity between the processor and the DMA controller follows the normal postcompletion activity of any I/O port. This shows that the controller is treated as a standard port before and after block transfer and during transfer the DMA must be able to synchronise with the processor. The controller improves performance especially with a built-in program for moving a stream of data between memory and an I/O port--thereby not requiring to access the instruction from memory and executing them one by one. Some elementary actions can be performed in parallel instead of sequentially when implemented with software in the processor. For example, the controller decrements a counter each time it moves a datum. The controller can overlap the subtraction with memory access and avoid the time penalty for the arithmetic instruction. Because of the ability to achieve higher performance for block transfers, the DMA controller is used most frequently for high speed I/O, especially disk. Fast disks move blocks of data at speeds much greater than any program can control and therefore must be interfaced to computers through DMA controllers DMA interface operation The figure below indicates a typical direct memory-access controller interface. The I/O ports in this example under DMA control are attached only to the DMA controller. Signal lines are the same ones that normally interface the ports to the processor. Memory lines are the conventional lines except that both the processor and the DMA controller exercise the lines. The new lines are the HALT and HALT ACKNOWLEDGE lines. These lines synchronise the DMA controller to the processor. When the DMA controller needs to access the memory it requests the processor to halt by asserting the HALT signal. The processor responds with HALT ACKNOWLEDGE at a later time and then the DMA controller takes control of memory. On completion of its task the DMA controller removes its HALT request, the processor continues from its suspension and removes iths ALT ACKNOWLEDGE.. Figure 2.15 DMA interface with microprocessor 77

78 The dotted IMMEDIATE HALT is a different type of DMA request. The HALT request may take several clock cycles for the processor to acknowledge due to the time taken for the processor reaching a state where it can suspend processing. Data held in dynamic registers that are refreshed during normal processing must be moved to status registers, or execution has moved to a point where the data is no longer necessary. TheIM MEDIATE HALT line avoids this delay but has associated severe restrictions. The IMMEDIATE HALT can be used only briefly one or at most two accesses otherwise the processor may not be able to recover its state correctly and return to the suspended activity. The IDLE status line can be used by the DMA controllers that can delay data transfers until an IDLE point is reached. The IDLE in some systems can occur frequently, that is, 20 to 30% of the memory cycles. In this situation there is no need to halt the processor and the DMA can achieve high data rates with virtually no impact on processor performance. Figure 2.16 A typical direct memory-access controller interface DMA interface with I/O Interfacing with the I/O port requires two signals per port-- TRANSFER REQUEST and TRANSFER ACK plus the ability to generate I/O READ/WRITE L to indicate to the port the direction of the transfer. The DMA controller accepts a TRANSFER REQUEST from the port when the port has data ready to write into memory or has an empty buffer that can accept data from memory. When a transfer is to take place, the DMA outputs the control signal TRANSFER ACK, which indicates the port should receive data from or write data into memory Controller accessing memory As described before the DMA controller has a HALT request O/P signal and a HALT ACKNOWLEDGE I/P. During the byte-by-byte transfer of a block of data, the controller watches for a TRANSFER EQUEST on a channel. Then the controller asserts HALT and waits for HALT ACKNOWLEDGE. This instructs the processor to relinquish the memory bus. When the processor relinquishes the bus it asserts HALT ACKNOWLEDGE and the DMA controller has access to memory. The controller simultaneously: 1. places an address on the bus 2. sends TRANSFER ACK to the requesting I/O port and 3. sends the proper polarity of READ/WRITE L to memory and the complement of this signal to the I/O system. The I/O port and memory respond in opposite ways so that data moves from one to the other depending on the polarity of READ/WRITE L. At the completion of the memory cycle the DMA controller removes all 78

79 of the signals placed on the bus and places its bus drivers in high impedance mode. With the HALT deasserted the processor can continue its operation from the point of suspension. In the DMA shown above there are three channels making it possible for the above operations to be multiplexed among the three separate I/O ports. SELF CHECK 3 WHAT IS THE NEED OF 8086 WHEN 8085 IS AVAILABLE?!! 1.A 8086 deals with only 8 bit data,,,true/false 2.Mn/MX refers to 3.what is the clock frequency of 8086? 4.What is the maximum number of I/O devices can be connected with MULTIPLE CHOICE FOR SELF CHECK 1) The 8086 is a bit microprocessor (a)8 (b)16 (c)32 (d)64 (Ans)16 2) BIU stands for (a)bus indication unit (b)bus Interface Unit (c)binary Interrupt Unit (d)bus Interconnection unit (Ans)Bus Interface Unit 3) The pointer and index group are bit (a)8 (b)16 (c)32 (d)64 (Ans)16 4) Stack Pointer (SP) is a -bit register pointing to program stack. (a)8 (b)16 (c)32 (d)64 (Ans)16 5) Flags is a bit register containing flags (a)16,5 (b)8,5 (c)16,7 (d)16,9 (Ans)16,9 6) The total addressable memory size by 8086 is (a)64k (b)128k (c)1m (d)64m (Ans)1M 7) The physical address is bits long and corresponds to the actual binary code output by the BIU on the address bus lines. (a)16 (b)20 (c)24 (d)32 (Ans)20 8) The addresing mode of MOV CL,DL (a)immediate (b)data (c)register (d)direct (Ans)register 9) The addresing mode of MOV DX,1234 is (a)data (b)direct (c)in-direct (d)immediate (Ans)immediate 10) The addresing mode of MOV [DI],BX IS (a)direct (b)indirect (c)register- DIRECT (d)register-indirect (Ans)REGISTER-INDIRECT 11) The Hardware interrupts of 8086 are (a)intr,int 0 (b)int0,nmi (c)nmi,intr (d)nmi,int (Ans)NMI,INTR 12) the interrupt which has high Priority is (a)divide by Zero error (b)nmi (c)intr (d)single Step interrupt (Ans)Divide by Zero error 13) Instruction Pointer (IP) is a bit register (a)8 (b)16 (c)32 (d)64 (Ans)16 14) Interrupt-enable Flag (IF) - setting this bit enables interrupts. (a)all interrupts (b)maskable (c)non-maskable (d)software interrupts (Ans)maskable 79

80 Review Questions 2 MARKS 1. How many bits does 8086 microprocessor have? 2. What is the size of data bus in 8086? 3. What is the size of address bus in 8086? 4. What is the max memory addressing capacity of 8086? 5. Which are the basic parts of 8086? 6. What are the functions of BIU? 7. What are the functions of EU? 8. How many pin IC 8086 is? 9. What IC8086 is? 10. What is the size of instruction queue in 8086? 11. What is the size of instruction queue in 8088? 12. Which are the registers present in 8086? 13. What is pipelining in 8086? 14. How many 16 bit registers are available in 8086? 15. Specify addressing modes for any instruction? 16. What is assembler directives? 17. What.model small stands for? 18. What is the supply requirement of 8086? 19. What is the relation between 8086 processor frequency & crystal frequency? 20. Functions of Accumulator or AX register? 21. Functions of BX register? 22. Functions of CX register? 23. Functions of DX register? 24. How Physical address is generated? 25. Which are pointers present in this 8086? 26. Which is by default pointer for CS/ES? 27. How many segments present in it? 28. What is the size of each segment? 29. Basic difference between 8085 and 8086? 30. Which operations are not available in 8085? 31. What is the difference between min mode and max mode of 8086? 32. What is the difference between near and far procedure? 33. What is the difference between Macro and procedure? 34. What is the difference between instructions RET & IRET? 35. What is the difference between instructions MUL & IMUL? 36. What is the difference between instructions DIV & IDIV? 37. What is difference between shifts and rotate instructions? 38. Which are strings related instructions? 39. Which are addressing modes and their examples in 8086? 40. What does u mean by directives? 41. What does u mean by Prefix? 42. What.model small means? 43. Difference between small, medium, tiny, huge? 44. What is dd, dw, db? 45. Interrupts in 8086 and there function. 46. What is the function of 01h of Int 21h? 47. What is the function of 02h of Int 21h? 48. What is the function of 09h of Int 21h? 49. What is the function of 0Ah of Int 21h? 80

81 50. What is the function of 4ch of Int 21h? 51. What is the reset address of 8086? 52. What is the size of flag register in 8086? Explain all. 53. What is the difference between 08H and 01H functions of INT 21H? 54. Which is faster- Reading word size data whose starting address is at even or at odd address of memory in 8086? 55. Which are the default segment base: offset pairs? 56. Can we use SP as offset address holder with CS? 57. Which are the base registers in 8086? 58. Which is the index registers in 8086? 59. What is segment override prefix? 60. Whether micro reduces memory requirements? 61. What is macro? 62. What is diff between macro and procedure? 63. Types of procedure? 64. What TASM is? 65. What TLINK is? 66. What TD is? 67. What do u mean by assembler? 68. What do u mean by linker? 69. What do u mean by loader? 70. What do u mean by compiler? 71. What do u mean by emulator? 72. Stack related instruction? 73..stack 100 means? 74. What is 20 dup (0)? 75. Which flags of 8086 are not present in 8085? 76. What is the size of flag register? 77. Can you perform 32 bit operation with 8086? How? 78. Whether 8086 is compatible with Pentium processor? 79. What is 8087? How it is different from 8086? 80. While accepting no. from user why u need to subtract 30 from that? 81. While displaying no. from user why u need to add 30 to that? 82. What are ASCII codes for nos. 0 to F? 83. How does U differentiate between positive and negative numbers? 84. What is range for these numbers? 85. Which no. representation system you have used? 86. What is LEA? 87. What indicates in instruction- MOV 88. What is maximum size of the instruction in 8086? 89. Why we indicate FF as 0FF in program? 90. What is mul BX and div BX? Where result goes? 91. Where queue is present? 92. What is the advantage of using internal registers? 93. What is SI, DI and their functions? 94. Which are the pointers used in 8086 and their functions? 95. What is a type of queue in 8086? 96. What is minimum mode of 8086? 97. What is maximum mode of 8086? 98. Which are string instructions? 99. In string operations which is by default string source pointer? 100. In string operations which is by default string destination pointer? 81

82 Big Question 1. a. Explain the interrupts of 8086 with ISR Table? (12) 2. a.describe the action taken by 8086 when NMI pin is activated?what are the hardware interrupts (8) b. Explain memory organization in 8086? (8) 3. With the neat sketch explain the architecture of 8086 processor? (12) 4. a.give the significance of O flag, T flag, I flag & D flag of 8086? (8) b.discuss the interrupt system of Intel What is interrupt pointer? What is 'type' ofan interrupt? (8) 5. a)what is the difference between minimum and maximum modes of 8086? How are these modes selected? (6) b)draw and explain the BIU of 8086.(6) 6)Draw the maximum mode module of 8086 clearly showing address latches, transreceivers, clock generator. neatly label the diagram. terminate unused pins properly.(12) 7.Draw the interfacing diagram for 8086 based system(minimum mode)with the following specification. -16 KB RAM -8 KB EPROM PPI in I/O address space also show the required latches, buffers and decoder.draw the memory map for the above interface. (12) 8.a)Explain the following 8086 signals:(6) -INTR -DT/(R bar) -RESET -TEST (bar ) b)how does 8086 convert a logical address to physical address? explain with an example.(6) 9. a).explain with the suitable diagram how 8086 access a byte or word from EVEN and ODD memory banks. b. Explain the Maximum mode of operation of (12) 82

83 10.Explain the minimum mode of operation of (12) 11. Design an 8086 based system in minimum mode containing 64kb of EPROM and 64kb of RAM (12) 12.Draw the Timing diagram for 8086 based system(minimum mode and maximum mode ) with the example (12) 83

84 3 CHAPTER 8086 INSTRUCTIONS SET AND PROGRAMMING 84

85 3.1. INSTRUCTION FORMAT The instruction format of 8086 has one or more number of fields associated with it. The first filled is called operation code field or opcode field, which indicates the type of operation. The instruction format also contains other fields known as operand fields. There are six general formats of instructions in 8086 instruction set. The length of an instruction may vary from one byte to sic bytes. a) One byte Instruction : This format is only one byte long and may have the implied data or register operands. The least significant 3 bits of the opcode are used for specifying the register operand, if any. Otherwise, all the eight bits form an opcode and the operands are implied. For example: F 8 H CLC : clear carry This is an operation without any operand, which clear the carry flag bit. Exchange register with accumulator reg Depending on the register (reg = RRR), the contents of the specified register will be exchanged with the accumulator. This operation is having one operand which is specified in a register. ASC Adjust for addition AAA H Here the operand to this instruction is implicit and it take the contents of register AL. b) Register to Register : This format is 2 bytes long. The first byte of the code specifies the operation code and the width of the operand specifies by w bit. The second byte of the opcode shows the register operands and RIM field. D 7 D 1 D 0 D 7 D 6 D 5 D 4 D 3 D 2 D 1 D 0 OP CODE d w 1 1 REG R/M The register represented by the REG field is one of the operands. The RIM field specifies another register or memory location, ie., the other operand. The register specified by REG is a source operand if D 0, else it is a destination operand. For example: MOV : data transfer operation from Register to Register. Op-code is d w 1 1 R E G C 1 H H 85

86 REG = REG = indicates Register AL indicates Register CL w 0 indicates it is a byte operation (8 bit) d 0 indicates AL is a source register. This instruction indicates MOV CL, AL, i.e CL AL C) Register to/from memory with no displacement : This format is also 2 bytes long and similar to the register to register format except for the MOD field. D 7 D 1 D 0 D 7 D 6 D 5 D 4 D 3 D 2 D 1 D 0 OP CODE d w MOD REG R/M The MOD field shows the MOD of addressing. In case of no displacement. MOD = 00 For example : MOV : Data transfer Register/memory to/from register d w mod reg rim This format is similar to register to register transfer. The difference is in mood field. For register to register, mod = 11 For register to/from memory with no displacement, mod = 00. When mod = 0 0, the r/m fields indicates the address to memory location. As for example r/m = indicates (Bx) The instruction indicates the instruction MOV AX, [BX] In hexadecimal, the instruction is 8AO 7 H H Here the data is present in a memory location in DS whose offset address is in BX. The effective address of the data is given as 10H DS BX There d 1 indicates AX is a destination register so it moves the data from memory to register. d) Register to/from Memory with Displacement : This type of instruction format contains one or two additional bytes for displacement along with 2-byte the format of the register to/from memory without displacement. 86

87 D 7 D 0 D 7 D 6 D 5 D4 D 3 D 2 D 1 D 0 D 7 D 0 opcode D 7 D 0 High byte of displacement MOD REG R/M Low byte of displacement MOD = 0 1 indicates displacement of 8 bytes (instruction is of size 3 bytes) MOD = 1 0 indicates displacement of 16 bytes. (instruction is of size 4 bytes) Already we have seen the other two options of MOD MOD = 1 1 indicates register to register transfer MOD = 0 0 indicates memory without displacement In this case, R/M fields indicates a memory when MOD is not 1 1 R/M = indicates (BX) When MOD = 0 1, the offset address is BX D 8 When MOD = 1 0, the offset address is BX D 16 e) Immediate operand to register In this format, the first byte as well as the 3 bites from the second byte which are used for REG field in case of register to register format are used for opcode. It also contains one or two bytes of immediate data. D 7 D 0 D 7 D 6 D 5 D 4 D 3 D 2 D 1 D 0 Op code w 1 1 op code R/M D 7 D 0 D 7 D 0 Lower byte DATA Higher byte DATA When w 0, the size of immediate data is 8 bits and the size of instruction is 3 bytes. When w 1, the size of immediate data is 16 bits and the size of instruction is 4 bytes. f) immediate operand to memory with 16-bit displacement : This type of instruction format requires 5 to 6 bytes for coding. The first two bytes contain the information regarding OPCODE, MOD and R/M fields. The remaining 4 bytes contain 2 bytes of displacement and 2 bytes of data. 87

88 D 7 D 0 D 7 D 6 D 5 D 4 D 3 D 2 D 1 D 0 Op code w MOD op code R/M D 7 D 0 D 7 D 0 D 7 D 0 Higher byte of displacement The REG code of the different registers (either a source or destination operands) in the opcode byte are assigned with binary code. - w bit Register code (3 bit) Registers Segment register code (2 bit) Segment register A L E S CL 0 1 C S DL 1 0 S S BL 1 1 D S AH CH DH BH AX CX DX BX SP BP SI DI Coding of different registers. Addressing Modes of 8086 : Lower byte of DATA Higher byte of DATA The different addressing modes of the 8086 instructions along with corresponding MOD, REG and R/M field are given in the table. operands Memory operands Register operands No Displacement Displacement 8 bits Displacement 16 bits MOD RIM w 0 w BX SI BX SI D 8 BX SI D 16 - AL AX BX DI BX DI D 8 BX DI D 16 CL CX 88

89 0 1 0 BP SI BP SI D 8 BP SI D 16 DL DX BP DI BP DI D 8 BP DI D 16 BL BX SI SI D 8 SI D 16 AH SP DI DI D 8 DI D 16 CH BP D 16 BP D 8 BP D 16 DH SS BX BX D 8 BX D 16 BH DI D8 and D16 represent 8 and 16 bit displacement respectively. The default segment for the addressing modes using BP and SP is SS. For all other addressing modes the default segments are DS or ES ADDRESSING MODES Definition: An instruction acts on any number of operands. The way an instruction accesses its operands is called its Addressing modes. Operands may be of three types: o o o Implicit Explicit Both Implicit and Explicit. Implicit operands mean that the instruction by definition has some specific operands. The programmers do NOT select these operands. Example: Implicit operands XLAT; automatically takes AL and BX as operands AAM; it operates on the contents of AX. Explicit operands mean the instruction operates on the operands specified by the programmer. Example: Explicit operands MOV AX, BX; it takes AX and BX as operands XCHG SI, DI; it takes SI and DI as operands 89

90 Implicit and explicit operands Example: Implicit/Explicit operands MUL BX; automatically multiply BX explicitly times AX The location of an operand value in memory space is called the Effective Address (EA) We can classify the addressing modes of 8086 into four groups: Immediate addressing Register addressing Memory addressing I/O port addressing The first three Addressing modes are clearly explained Immediate Addressing Mode In this addressing mode, the operand is stored as part of the instruction. The immediate operand, which is stored along with the instruction, resides in the code segment -- not in the data segment. This addressing mode is also faster to execute an instruction because the operand is read with the instruction from memory. Here are some examples: Register addressing mode In this addressing mode, the operands may be: Example: Immediate Operands MOV AL, 20 ; move the constant 20 into register AL ADD AX, 5 ; add constant 5 to register EAX MOV DX, offset msg ; move the address of message to register DX reg16: 16-bit general registers: AX, BX, CX, DX, SI, DI, SP or BP. reg8 : 8-bit general registers: AH, BH, CH, DH, AL, BL, CL, or DL. Sreg : segment registers: CS, DS, ES, or SS. There is an exception: CS cannot be a destination. For register addressing modes, there is no need to compute the effective address. The operand is in a register and to get the operand there is no memory access involved. Example: Operands Register 90

91 Some rules in register addressing modes: MOV AX, BX ; mov reg16, reg16 ADD AX, SI ; add reg16, reg16 MOV DS, AX ; mov Sreg, reg16 1. You may not specify CS as the destination operand. Example: mov CS, 02h > wrong 2. Only one of the operands can be a segment register. You cannot move data from one segment register to another with a single mov instruction. To copy the value of cs to ds, you would have to use some sequence like: Movds,cs->wrong movax,cs mov ds, ax -> the way we do it You should never use the segment registers as data registers to hold arbitrary values. They should only contain segment addresses Memory Addressing Modes Memory (RAM) is the main component of a computer to store temporary data and machine instructions. In a program, programmers many times need to read from and write into memory locations. There are different forms of memory addressing modes 1. Direct Addressing 2. Register indirect addressing 3. Based addressing 4. Indexed addressing 5. Based indexed addressing 6. Based indexed with displacement 7. Direct Addressing Mode & Register Indirect Addressing Mode Direct Addressing Mode The instruction mov al,ds:[8088h] loads the AL register with a copy of the byte at memory location 8088h. Likewise, the instruction mov ds:[1234h],dl stores the value in the dl register to memory location 1234h. By default, all displacement-only values provide offsets into the data segment. If you want to provide an offset into a different segment, you must use a segment override prefix before your address. For example, to access location 1234h in the extra segment (es) you would use an instruction of the form mov ax,es:[1234h]. Likewise, to access this location in the code segment you would use the instruction mov ax, cs:[1234h]. The ds: prefix in the previous examples is not a segment override. 91

92 The instruction mov al,ds:[8088h] is same as mov al, [8088h]. If not mentioned DS register is taken by default Register Indirect Addressing Mode The 80x86 CPUs let you access memory indirectly through a register using the register indirect addressing modes. There are four forms of this addressing mode on the 8086, best demonstrated by the following instructions: mov al, [bx] mov al, [bp] mov al, [si] mov al, [di] Code Example MOV BX, 100H MOV AL, [BX] The [bx], [si], and [di] modes use the ds segment by default. The [bp] addressing mode uses the stack segment (ss) by default. You can use the segment override prefix symbols if you wish to access data in different segments. The following instructions demonstrate the use of these overrides: mov al, cs:[bx] mov al, ds:[bp] mov al, ss:[si] mov al, es:[di] 92

93 Intel refers to [bx] and [bp] as base addressing modes and bx and bp as base registers (in fact, bp stands for base pointer). Intel refers to the [si] and [di] addressing modes as indexed addressing modes (si stands for source index, di stands for destination index). However, these addressing modes are functionally equivalent. This text will call these forms register indirect modes to be consistent Based Addressing Mode 8-bit or 16-bit instruction operand is added to the contents of a base register (BX or BP), the resulting value is a pointer to location where data resides. Mov al, [bx],[si] Mov bl, [bp],[di] Mov cl, [bp],[di] Code Example If bx=1000h si=0880h Mov AL, [ ] Mov AL,[1880] Indexed Addressing Modes The indexed addressing modes use the following syntax: mov al, [bx+disp] mov al, [bp+disp] mov al, [si+disp] mov al, [di+disp] Code Example MOV BX, 100H MOV AL, [BX + 15] MOV AL, [BX + 16] If bx contains 1000h, then the instruction mov cl, [bx+20h] will load cl from memory location ds:1020h. Likewise, if bp contains 2020h, mov dh, [bp+1000h] will load dh from location ss:3020. The offsets generated by these addressing modes are the sum of the constant and the specified register. The addressing modes involving bx, si, and di all use the data segment, the [bp+disp] addressing mode uses the stack segment by default. As with the register indirect addressing modes, you can use the segment override prefixes to specify a different segment: mov al, ss:[bx+disp] mov al, es:[bp+disp] mov al, cs:[si+disp] mov al, ss:[di+disp] Example: MOV AX, [DI + 100] 93

94 8. ased Indexed Addressing Modes & Based Indexed Plus Displacement Addressing Mode Based Indexed Addressing Modes The based indexed addressing modes are simply combinations of the register indirect addressing modes. These addressing modes form the offset by adding together a base register (bx or bp) and an index register (si or di). The allowable forms for these addressing modes are: mov al, [bx+si] mov al, [bx+di] mov al, [bp+si] mov al, [bp+di] Code Example MOV BX, 100H MOV SI, 200H MOV AL, [BX + SI] INC BX INC SI Suppose that bx contains 1000h and si contains 880h. Then the instruction mov al,[bx][si] would load al from location DS:1880h. Likewise, if bp contains 1598h and di contains 1004, mov ax,[bp+di] will load the 16 bits in ax from locations SS:259C and SS:259D. The addressing modes that do not involve bp use the data segment by default. Those that have bp as an operand use the stack segment by default Based Indexed Plus Displacement Addressing Mode These addressing modes are a slight modification of the base/indexed addressing modes with the addition of an eight bit or sixteen bit constant. The following are some examples of these addressing modes mov al, disp[bx][si] mov al, disp[bx+di] mov al, [bp+si+disp] mov al, [bp][di][disp] 94

95 Code Example MOV BX, 100H MOV SI, 200H MOV AL, [BX + SI +100H] INC BX INC SI 3.3. INSTRUCTION SET Here are the most important instructions (in my opinion) that have been available on all Intel processors since the Different assemblers may have minor variations in how these instructions are represented in assembly code; I give the NASM form here. Throughout this section, when specifying the valid forms of operands, I will write reg8 to stand for any 8-bit register, reg16 for any of the eight general- and special-purpose 16-bit registers, mem8 for a memory reference to a single byte, mem16 for a memory reference to a word (with the low-order byte at the given address), imm8 for an 8-bit immediate value, and imm16 for a 16-bit immediate value. If an operand may be either a register or memory reference, I will write r/m8 or r/m16; if it may also be an immediate value, then I will write r/m/i8 or r/m/i16. A segment register as an operand will be written segreg Data Transfer Group The fundamental data movement operation is MOV dest, source, which copies a byte or a word from the source location to the destination. In general, either the source or the destination must be a register (you can't copy directly from one memory location to another with MOV); the only exception is that an immediate value may be moved straight to memory (however, there is no way to put an immediate value into a segment register in one operation). Here are the accepted forms: MOV MOV MOV reg8, r/m/i8 mem8, reg8 mem8, BYTE imm8 MOV MOV MOV reg16, r/m/i16 mem16, reg16 mem16, WORD imm16 MOV MOV r/m16, segreg segreg, r/m16 95

96 The CS segment register may not be used as a destination (you wouldn't want to do this anyway, since it would change where the next instruction comes from; to get this effect, you need to use a proper flow control instruction such as JMP). To perform a swap of two locations instead of a one-way copy, there is also an exchange operation: XCHG reg8, r/m8 XCHG reg16, r/m16 As a special case of this that does nothing except occupy space and take up processor time, the instruction to exchange the accumulator with itself (XCHG AX, AX) is given the special "no-operation'' mnemonic: NOP For the special purpose of copying a far pointer (that is, a pointer that includes a segment address, so that it can refer to a location outside the current segment) from memory into registers, there are the LDS and LES instructions. Here are the accepted forms: LDS reg16, mem32 LES reg16, mem32 For example, the instruction LDS SI, [200h] is equivalent to the pair of instructions MOV SI, [200h] and MOV DS, [202h]. The 8086 only supports loading the pointer into the DS or ES segment register. An operation that is frequently useful when setting up pointers is to load the "effective address'' of a memory reference. That is, this instruction does the displacement plus base plus index calculation, but just stores the resulting address in the destination register, rather than actually fetching the data from the address. Here is the only form allowed on the 8086: LEA reg16, mem To push and pop data from the stack, the 8086 provides the following instructions. The top of stack is located at offset SP within the stack segment, so PUSH AX, for example, is equivalent to SUB SP, 2 (recall that the stack grows downward) followed by MOV [SS:SP], AX (except that [SS:SP] isn't a valid form of memory reference). PUSH r/m16 PUSH segreg POP r/m16 POP segreg As with MOV, you are not allowed to POP into the CS register (although you may PUSH CS). Although they were not provided on the original 8086, the instructions to push and pop the FLAGS register (as mentioned earlier) are available in Virtual-8086 mode on the Pentium (they were actually introduced in the 80186): PUSHF POPF 96

97 Here are the other ways of reading or modifying the FLAGS register (apart from setting flags as the result of an arithmetic operation, or testing them with a conditional branch, of course). The Carry, Direction, and Interrupt Enable flags may be cleared and set: CLC CLD CLI STC STD STI The Carry flag may also be complemented, or "toggled'' between 0 and 1: CMC Finally, the bottom eight bits of the FLAGS register (containing the Carry, Parity, Auxiliary Carry, Zero, and Sign flags, as described above) may be transferred to and from the AH register: LAHF SAHF Arithmetic and Logical Instructions All of the two-operand arithmetic and logical instructions offer the same range of addressing modes. For example, here are the valid forms of the ADD operation: ADD ADD ADD reg8, r/m/i8 mem8, reg8 mem8, BYTE imm8 ADD reg16, r/m/i16 ADD mem16, reg16 ADD mem16, WORD imm16 Just as with the MOV instruction, the first operand is the destination and the second is the source; the result of performing the operation on the two operands is stored in the destination (if it gets stored anywhere). Unlike MOV, most of these instructions also set or clear the appropriate status flags to reflect the result of the operation (for some of the instructions, this is their only effect). To add two numbers, use the ADD instruction. To continue adding further bytes or words of a multi-part number, use the ADC instruction to also add one if the Carry flag is set (indicating a carry-over from the previous byte or word). For example, to add the 32-bit immediate value h to the 32-bit double word stored at location 500h, do ADD [500h], 5678h followed by ADC [502h], 1234h. Subtraction is analogous: use the SUB instruction to subtract a single pair of bytes or words, and then use the SBB ("Subtract with Borrow'') instruction to take the Carry into account for further bytes or words. An important use of subtraction is in comparing two numbers; in this case, we are not interested in the exact value of their difference, only in whether it is zero or negative, or whether there was a carry or overflow. The CMP ("Compare'') instruction performs this task; it subtracts the source from the destination and adjusts the status flags accordingly, but throws away the result. This is exactly what is needed to get 97

98 conditions such as LE to work; after doing CMP AX, 10, for example, the status flags will be set in such a way that the LE condition is true precisely when the value in AX (treated as a signed integer) is less than or equal to 10. The two-operand logical instructions are AND, OR, XOR, and TEST. The first three perform the expected bitwise operations; for example, the nth bit of the destination after the AND operation will be 1 (set, true) if the nth bit of both the source and the destination were 1 before the operation, otherwise it will be 0 (clear, false). The TEST instruction is to AND as CMP is to SUB; it performs a bitwise and operation, but the result is only reflected in the flags. For example, after the instruction TEST [321h], BYTE 12h, the Zero flag will be set if neither bit 1 nor bit 4 (12h is in binary, indicating that bits 1 and 4 are to be tested) of the byte at address 321h were 1, otherwise it will be clear. Multiplication and division are also binary operations, but the corresponding instructions on the 8086 only allow one of the operands to be specified (and it can only be a register or memory reference, not an immediate value). The other operand is implicitly contained in the accumulator (and sometimes also the DX register). The MUL and DIV instructions operate on unsigned numbers, while IMUL and IDIV operate on two's-complement signed numbers. Here are the valid forms for MUL; the others are analogous: MUL MUL reg8 BYTE mem8 MUL reg16 MUL WORD mem16 For 8-bit multiplication, the quantity in AL is multiplied by the given operand and the 16-bit result is placed in AX. For 16-bit multiplication, the 32-bit product of AX and the operand is split, with the low word in AX and the high word in DX. In both cases, if the result spills into the high-order byte/word, then the Carry and Overflow flags will be set, otherwise they will be clear. The other flags will have garbage in them; in particular, you will not get correct information from the Zero or Sign flags (if you want that information, follow the multiplication with CMP AX, 0, for example). For division, the process is reversed. An 8-bit operand will be divided into the number in AX, with the quotient stored in AL and the remainder left in AH. A 16-bit operand will be divided into the 32-bit quantity whose high word is in DX and whose low word is in AX; the quotient will be in AX and the remainder will be in DX after the operation. None of the status flags are defined after a division. Also, if the division results in an error (division by zero, or a quotient that is too large), the processor will trigger interrupt zero (as if it had executed INT 0). The CBW and CWD instructions, which take no operands, will sign-extend AL into AX or AX into DX, respectively, just as needed before performing a signed division. For example, if AL contains , then after CBW the AH register will contain (and AL will be unchanged). Multiplication and division by powers of two are frequently performed by shifting the bits to the left or right. There are several varieties of shift and rotate instructions, all of which allow the following forms: RCL reg8, 1 RCL reg8, CL RCL BYTE mem8, 1 RCL BYTE mem8, CL 98

99 RCL reg16, 1 RCL reg16, CL RCL WORD mem16, 1 RCL WORD mem16, CL The second operand specifies how many bit positions the result should be shifted by: either one or the number in the CL register. For example, the accumulator may be multiplied by 2 with SHL AX, 1; if CL contains the number 4, the accumulator may be multiplied by 16 with SHL AX, CL. There are three shift instructions---sar, SHR, and SHL. The "shift-left'' instruction, SHL, shifts the highest bit of the operand into the Carry flag and fills in the lowest bit with zero. The "shift-right'' instruction, SHR, does the opposite, moving zero in from the top and shifting the lowest bit out into the Carry; this is appropriate for an unsigned division, with the Carry flag giving a 1-bit remainder. On the other hand, the "shift-arithmetic-right'' instruction, SAR, leaves a copy of the highest bit in place as it shifts; this is appropriate for a signed division, since it preserves the sign bit. For example, -53 is represented in 8-bit two's-complement by the binary number After a SHL by one position, it will be , which represents After a SAR, it will be , which represents -27. After a SHR, it will be , which represents +101 in decimal; this corresponds to the interpretation of the original bits as the unsigned number 203 (which yields 101 when divided by 2). When shifting multiple words by one bit, the Carry can serve as the bridge from one word to the next. For example, suppose we want to multiply the double word (4 bytes) starting at address 1230h by 2; the instruction SHL WORD [1230], 1 will shift the low-order word, putting its highest bit into the Carry flag. Now we need an instruction that will shift the Carry into the lowest bit of the word at 1232h; if we wanted to continue the process, we would also need it to shift the highest bit of that word back out into the Carry. The effect here is that the bits in the operand plus the Carry have been rotated one position to the left. The desired instruction is RCL WORD [1232], 1 ("rotate-carry-left''). There is a corresponding "rotate-carryright'' instruction, RCR; there are also two rotate instructions which directly shift the highest bit down to the lowest and vice versa, called ROL and ROR. There are four unary arithmetic and logical instructions. The increment and decrement operations, INC and DEC, add or subtract one from their operand; they do not affect the Carry bit. The negation instruction, NEG, takes the two's-complement of its operand, while the NOT instruction takes the one's-complement (flip each bit from 1 to 0 or 0 to 1). NEG affects all the usual flags, but NOT does not affect any of them. The valid forms of operand are the same for all of these instructions; here are the forms for INC: INC INC reg8 BYTE mem8 INC INC reg16 WORD mem String Instructions The string instructions facilitate operations on sequences of bytes or words. None of them take an explicit operand; instead, they all work implicitly on the source and/or destination strings. The current element 99

100 (byte or word) of the source string is at DS:SI, and the current element of the destination string is at ES:DI. Each instruction works on one element and then automatically adjusts SI and/or DI; if the Direction flag is clear, then the index is incremented, otherwise it is decremented (when working with overlapping strings it is sometimes necessary to work from back to front, but usually you should leave the Direction flag clear and work on strings from front to back). To work on an entire string at a time, each string instruction can be accompanied by a repeat prefix, either REP or one of REPE and REPNE (or their synonyms REPZ and REPNZ). These cause the instruction to be repeated the number of times in the count register, CX; for REPE and REPNE, the Zero flag is tested at the end of each operation and the loop is stopped if the condition (Equal or Not Equal to zero) fails. The MOVSB and MOVSW instructions have the following forms: MOVSB REP MOVSB MOVSW REP MOVSW The first form copies a single byte from the source string, at address DS:SI, to the destination string, at address ES:DI, then increments (or decrements, if the Direction flag is set) both SI and DI. The second form performs this operation and then decrements CX; if CX is not zero, the operation is repeated. The effect is equivalent to the following pseudo-c code: while (CX!= 0) { *(ES*16 + DI) = *(DS*16 + SI); SI++; DI++; CX--; } (recall that ES*16 + DI is the physical address corresponding to the segment and offset ES:DI). The remaining two forms move a word at a time, instead of a single byte; correspondingly, SI and DI are incremented or decremented by 2 each time through the loop. The STOSB and STOSW instructions are similar to MOVSB and MOVSW, except the source byte or word comes from AL or AX instead of the memory address in DS:SI. For example, the following is a very fast way to initialize the block of memory from ES:1000h to ES:4FFFh with zeroes: MOV DI, 1000h ;Starting address MOV CX, 2000h ;Number of words MOV AX, 0 ;Word to store at each location CLD ;Make sure direction is increasing REP STOSW ;Perform the initialization Correspondingly, the LODSB and LODSW instructions are variations on the move instructions where the destination is the accumulator (instead of the memory address in ES:DI). These are not very useful operations with the repeat prefix; instead, they are used as part of larger loops to perform more complex string processing. For example, here is a program fragment that will convert the NUL-terminated string 100

101 starting at the address in DX to be all lower-case (there is a faster way to do the conversion of each character, using the XLATB instruction, but that is not the point here): MOV SI, DX ;Initialize source MOV DI, DX ; and destination indices MOV AX, DS ;Copy DS (source segment) MOV ES, AX ; into ES (destination segment) CLD NextCh LODSB ;Load next character into AL CMP AL, 'A' JB NotUC ;Jump if below 'A' CMP AL, 'Z' JA NotUC ; or above 'Z' ADD AL, 'a' - 'A' ;Convert UC to lc NotUC STOSB ;Store modified character back CMP AL, 0 JNE NextCh ;Do next character if not at end of string None of the preceding string operations have any effect on the status flags. By contrast, the remaining two string operations are executed solely for their effect on the status flags, just like the CMP operation on numbers. The CMPSB and CMPSW operations compare the current bytes or words of the source and destination strings by subtracting the destination from the source and recording the properties of the result in FLAGS. The SCASB and SCASW operations are the variants of this that use the accumulator (AL or AX) for the source. Each of these may be preceded by either of the repeat prefixes REPE or REPNE, which cause the operation to be repeated up to CX times, as long as the condition holds true after each iteration. Here is the corresponding pseudo-c for REPE CMPSB: while (CX!= 0) { SetFlags(*(DS*16 + SI) - *(ES*16 + DI)); SI++; DI++; CX--; if (!ZeroFlag) break; } A common use of the REPNE SCASB instruction is to find the length of a NUL-terminated string. Here is an example: MOV DI, DX ;Starting address in DX (assume ES = DS) MOV AL, 0 ;Byte to search for (NUL) MOV CX, -1 ;Start count at FFFFh CLD ;Increment DI after each character REPNE SCASB ;Scan string for NUL, decrementing CX for each char MOV AX, -2 ;CX will be -2 for length 0, -3 for length 1,... SUB AX, CX ;Length in AX 101

102 Program Flow Instructions All of the previous instructions execute sequentially; that is, when one instruction finishes, the next instruction is taken from the very next memory location. This is the default operation for the instruction pointer, IP---after each byte of instruction is fetched, the IP is incremented in preparation for the next fetch. The program flow instructions provide the facilities to modify the course of execution, allowing conditional execution (by jumping over parts of the code if certain conditions are met) and looping (by jumping backwards in the code). The unconditional jump instruction, JMP, causes IP (and sometimes CS) to be modified so that the next instruction is fetched from the location given in the operand (the target). Here are the valid forms: JMP SHORT imm8 JMP imm16 JMP imm16:imm16 JMP r/m16 JMP FAR mem32 The short version saves space when the target of the jump is within a few dozen instructions forward or backward; the assembler computes the difference between the new address and the next address sequentially, and just stores this difference as one (signed) byte. The second (and most common) version allows a jump to any location in the current code segment, while the third allows a jump to any location in memory by also specifying an immediate value to be loaded into CS. The fourth version will take the target address from a register or memory location; since this address is only 16 bits, the target has to be within the segment. Finally, the far version fetches both the offset and the segment from four consecutive bytes in memory (compare to the LDS and LES instructions; JMP FAR mem32 could have been called "LCS IP, mem32''). The conditional jump instructions, Jcc, where cc is one of the condition codes listed earlier (E, NE,...), perform a short jump if the condition is true, based on the current contents of the status flags. For example, the code sample that was given in the discussion of LODSB, to convert a string to lower-case, used the JA and JB instructions; these made their jump if the result of the previous comparison found that the current character was above 'Z' or below 'A'. Since a conditional jump can only be to a nearby target, it is sometimes necessary to combine conditional and unconditional jumps as follows: JNLE NoJLE JMP target NoJLE: This will have the same effect as JLE target, except there is no restriction on how far away the target may be (within the code segment). There are two specialized versions of conditional jump that are particularly useful when executing a loop a fixed number of times. The looping statements LOOP imm8 LOOPE imm8 LOOPNE imm8 (as usual, the synonyms LOOPZ and LOOPNZ are also available) are very similar to the REP, REPE, and REPNE prefixes from the string instructions. The LOOP instruction decrements CX and makes a short 102

103 jump if the count has not reached zero. The LOOPE instruction adds the condition that it will only take the jump if the Zero flag is set (usually indicating that the last comparison had equal operands); the LOOPNE will only take the jump if the Zero flag is clear. The string operation REP MOVSB, for example, could have been performed with Repeat MOVSB LOOP Repeat (except this would have been considerably slower, since it requires repeatedly fetching and decoding the two instructions instead of just fetching and decoding the single REP MOVSB instruction once). After looping or repetitive string operations, it is occasionally necessary to test whether the count register reached zero (to check whether the loop ran for the full count or whether it exited early because the Zero flag changed). The instruction JCXZ imm8 serves exactly this purpose; it takes a short jump if the CX register contains zero. It is short for performing CMP CX, 0 followed by JZ imm8. All of the above branching instructions are variations on the infamous GOTO statement; they cause a permanent change in the course of execution. To perform an operation more like a function or subroutine call, where the flow of control will eventually return to pick up with the next instruction, the 8086 provides two mechanisms: CALL/RET and INT/IRET. The CALL instruction offers a similar range of addressing modes to the JMP instruction, except there is no "short'' call: CALL imm16 CALL imm16:imm16 CALL r/m16 CALL FAR mem32 A call is the same as a jump, except the instruction pointer is first pushed onto the stack (in the second and fourth versions, which include a new segment, the current CS register is also pushed). To reverse the effect of a CALL, when the subroutine is done it should execute a RET or RETF instruction; this pops the return address off of the stack and back into IP (and RETF also pops the saved value of CS, to return from a far call). After the return, the next instruction that will be fetched will be from the next location after the CALL. There is an optional 16-bit immediate operand that may be specified with a return instruction; this value is added to the stack pointer after popping off the return address, to recover however many bytes had been pushed onto the stack with parameters before the call. For example, here is one way to implement a subroutine to print a character, where the calling code first pushes the character (as the low byte of a word, since there is no option to push a single byte) before making the call: PutChar PUSH BP ;Save current values of registers that we'll modify PUSH AX PUSH DX MOV BP, SP ;Copy stack pointer to BP MOV AH, 2 ;DOS function code for printing a character MOV DL, [BP + 8] ;Fetch character parameter from stack ;Stack contains (from tos) DX, AX, BP, return address, and parameter 103

104 INT 21h ;Call DOS function POP DX ;Restore modified registers POP AX POP BP RET 2 ;Return and pop 2 byte parameter For completeness, here is what a typical call might look like (in fact, this is a complete routine to print a NUL-terminated string, assuming that the string starts at DS:SI): NextCh LODSB ;Load next character into AL CMP AL, 0 JE Done ;Quit if NUL PUSH AX ;Set up parameter for call CALL PutChar JMP NextCh ;Continue with next character Done: This is just one of several common conventions for passing parameters to subroutines; even more common is to just specify that, for example, the character will be passed directly in the DL register. The other function-call-like mechanism is the interrupt. We have been using this all along to call the standard DOS services, such as printing a character or a '$'-terminated string. The INT instruction behaves much like the CALL FAR instruction except for two things: it pushes the FLAGS register before pushing CS and IP (the idea is that an interrupt should be able to completely restore the state of the processor when it is finished, since this is also the mechanism used for handling hardware interrupts from the rest of the system---they can happen at any time, independent of what the processor might be working on, and they should occur as transparently to the current process as possible), and it gets the target address from a standard table of interrupt handler vectors kept at the bottom of memory. When the processor executes INT n, where n is an 8-bit immediate value, it fetches a far pointer (that is, a 4-byte combination of segment and offset) from the memory address 0000:4n; this is the target address for the interrupt call. For example, the address of the DOS interrupt handler, the routine called when INT 21h is executed, is stored at locations 0000:0084 through 0000:0087; the first two bytes give the offset, to load into IP, and the second two bytes give the segment, to load into CS ASSEMBLER DIRECTIVES ASSUME Directive - The ASSUME directive is used to tell the assembler that the name of the logical segment should be used for a specified segment. The 8086 works directly with only 4 physical segments: a Code segment, a data segment, a stack segment, and an extra segment. Example: ASUME CS:CODE ;This tells the assembler that the logical segment named CODE contains the instruction statements for the program and should be treated as a code segment. ASUME DS:DATA ;This tells the assembler that for any instruction which refers to a data in the data segment, data will found in the logical segment DATA. DB - DB directive is used to declare a bytetype variable or to store a byte in memory location. Example: a. PRICE DB 49h, 98h, 29h ;Declare an array of 3 bytes, named as PRICE and initialize. b. NAME DB ABCDEF ;Declare an array of 6 bytes and initialize with ASCII code for letters 104

105 c. TEMP DB 100 DUP(?) ;Set 100 bytes of storage in memory and give it the name as TEMP, but leave the 100 bytes uninitialized. Program instructions will load values into these locations. DW - The DW directive is used to define a variable of type word or to reserve storage location of type word in memory. Example: 1. MULTIPLIER DW 437Ah ; this declares a variable of type word and named it as MULTIPLIER. This variable is initialized with the value 437Ah when it is loaded into memory to run. 2. EXP1 DW 1234h, 3456h, 5678h ; this declares an array of 3 words and initialized with specified values. 3. STOR1 DW 100 DUP(0); Reserve an array of 100 words of memory and initialize all words with Array is named as STOR1. END - END directive is placed after the last statement of a program to tell the assembler that this is the end of the program module. The assembler will ignore any statement after an END directive. Carriage return is required after the END directive. ENDP - ENDP directive is used along with the name of the procedure to indicate the end of a procedure to the assembler Example: SQUARE_NUM PROCE ; It start the procedure ;Some steps to find the square root of a number SQUARE_NUM ENDP ;Hear it is the End for the procedure ENDS - This ENDS directive is used with name of the segment to indicate the end of that logic segment. Example: CODE SEGMENT ;Hear it Start the logic ;segment containing code ; Some instructions statements to perform the logical ;operation CODE ENDS ;End of segment named as ;CODE EQU - This EQU directive is used to give a name to some value or to a symbol. Each time the assembler finds the name in the program, it will replace the name with the value or symbol you given to that name. Example: FACTOR EQU 03H ; you has to write this statement at the starting of your program and later in the program you can use this as follows ADD AL, FACTOR ; When it codes this instruction the assembler will code it as ADDAL, 03H ;The advantage of using EQU in this manner is, if FACTOR is used many no of times in a program and you want to change the value, all you had to do is change the EQU statement at beginning, it will changes the rest of all. 105

106 EVEN - This EVEN directive instructs the assembler to increment the location of the counter to the next even address if it is not already in the even address. If the word is at even address 8086 can read a memory in 1 bus cycle. If the word starts at an odd address, the 8086 will take 2 bus cycles to get the data. A series of words can be read much more quickly if they are at even address. When EVEN is used the location counter will simply incremented to next address and NOP instruction is inserted in that incremented location. Example: DATA1 SEGMENT ; Location counter will point to 0009 after assembler reads ;next statement SALES DB 9 DUP(?) ;declare an array of 9 bytes EVEN ; increment location counter to 000AH RECORD DW 100 DUP( 0 ) ;Array of 100 words will start ;from an even address for quicker read DATA1 ENDS GROUP - The GROUP directive is used to group the logical segments named after the directive into one logical group segment. INCLUDE - This INCLUDE directive is used to insert a block of source code from the named file into the current source module. PROC - The PROC directive is used to identify the start of a procedure. The term near or far is used to specify the type of the procedure. Example: SMART PROC FAR ; This identifies that the start of a procedure named as SMART and instructs the assembler that the procedure is far. SMART ENDP This PROC is used with ENDP to indicate the break of the procedure PTR - This PTR operator is used to assign a specific type of a variable or to a label. Example: INC [BX] ; This instruction will not know whether to increment the byte pointed to by BX or a word pointed to by BX. INC BYTE PTR [BX] ;increment the byte ;pointed to by BX This PTR operator can also be used to override the declared type of variable. If we want to access the a byte in an array WORDS DW 437Ah, 0B97h, MOV AL, BYTE PTR WORDS PUBLIC - The PUBLIC directive is used to instruct the assembler that a specified name or label will be accessed from other modules. Example: 106

107 PUBLIC DIVISOR, DIVIDEND ;these two variables are public so these are available to all modules. If an instruction in a module refers to a variable in another assembly module, we can access that module by declaring as EXTRN directive TYPE - TYPE operator instructs the assembler to determine the type of a variable and determines the number of bytes specified to that variable. Example: Byte type variable assembler will give a value 1 Word type variable assembler will give a value 2 Double word type variable assembler will give a value 4 ADD BX, TYPE WORD_ ARRAY ; hear we want to increment BX to point to next word in an array of words. DOS Function Calls AH 00H : Terminate a Program AH 01H : Read the Keyboard AH 02H : Write to a Standard Output Device AH 08H : Read a Standard Input without Echo AH 09H : Display a Character String AH 0AH : Buffered keyboard Input INT 21H : Call DOS Function 107

108 4 CHAPTER PERIPHERALS AND INTERFACING 108

109 4.3. INTRODUCTION Peripheral Interfacing is considered to be a main part of Microprocessor, as it is the only way to interact with the external world. The interfacing happens with the ports of the Microprocessor. The main IC's which are to be interfaced with 8085 or 8086 are: PPI PIC USART Key board display controller Timer/ Counter DMA controller 6. A/D and D/A converter interfacing. 7.CRT Interface 8.Printer Interface I/O devices such as keyboards and displays establish communication of computer with outside world. Devices can be interfaced in two ways I/O MAPPED I/O and Memory mapped I/O. In I/O mapped I/O, device is identified with a unique device number and data are transferred thru IN/OUT instruction. Memory mapped I/O each device is identified with 16 bit address. I/O devices are considered to be a part of memory and memory related instruction is used for data transfer. An I/O interface must be able to _ Determine whether or not it is being interfaced _ Determine whether it has to send data to CPU or receive data from CPU _ Send ready signal informing CPU that transfer is over _ Send interrupt Requests to CPU and receive interrupt acknowledgement and send an interrupt type. An Interface can be divided into two parts. A part that interfaces to the I/O device and a part that interfaces to the system bus. There must be drivers and receivers to maintain signal quality, logic for translating the interface control signals to proper handshaking signals, logic for decoding address that appear on the bus. Handshaking signals are used to determine in which direction transfer has to take place whether from CPU or to CPU. It should determine whether it is a READ or WRITE operation. Interrupt signals also must be handled here. Address decoder determine whether it is I/O mapped I/O or Memory mapped I/O from one of the bits. If the decoder finds that an interface is referenced it sends signal to the appropriate device. Interfaces can be categorized according to the way I/O devices transfer data either in serial or parallel form. 109

110 4.4. THE 8255 PROGRAMMABLE PERIPHERAL INTERFACE (PPI) Pin Diagram Figure 4.1. Pin doagram of Block diagram of 8255 General The 8255A is a programmable peripheral interface (PPI) device designed for use in Intel microcomputer systems. Its function is that of a general purposes I/O component to Interface peripheral equipment to the microcomputer system bush. The functional configuration of the 8255A is programmed by the systems software so that normally no external logic is necessary to interface peripheral devices or structures. Data Bus Buffer This 3-stable bi-directional 8-bit buffer is used to interface the 8255A to the systems data bus. Data is transmitted or received by the buffer upon execution of input or output instructions by the CPU. Control words and status information are also transferred through the data bus buffer. Read/Write and Control Logic The function of this block is to manage all of the Internal and External transfers of both Data and Control or Status words. It accepts inputs from the CPU Address and Control business and in turn, issues commands to both of the Control Groups. 110

111 Figure A Block Diagram Showing Data Bus Buffer and Read/Write Control Logic Functions (CS) Chip Select. A low on this input pin enables the communication between the 8255A, and the CPU. (RD) Read. A low on this Input pin enables the 8255A to send the data or status information to the CPU on the data bus. In essence, it allows the CPU to read from the 8255A. (WR) Write. A. low on the input pin enables the CPU to write data or control words into the 8255A. (A0 and A1) Port Select 0 and Port Select 1. The Input signals, in conjunction with the RD and WR Inputs, controls the selection of one of the three ports or the control word registers. They are normally connected to the least significant bits of the address bus (A0 and A1). 111

112 8255A BASIC OPERATION A 1 A 0 RD WR CS INPUT OPERATION (READ) PORT A DATA BUS PORT B DATA BUS PORT C DATA BUS OUTPUT OPERATION (WRITE) DATA BUS PORT A DATA BUS -- PORT B DATA BUS PORT C DATA BUS CONTROL DISABLE FUNCTION X X X X 1 DATA BUS 3 STATE ILLEGAL CONDITION X X DATA BUS 3 STATE (RESET) Reset. A high on this Input clears the control register and all ports (A,B,C) are set to the Input mode. Group A and Group B Controls The functional configuration of each port is programmed by the systems software. In essence, the CPU output a control word to the 8255A. The control word contains information such as mode, bit set, bit reset, etc. that Initializes the functional configuration of the 8255A. Each of the Control blocks (Group A and Group B) accepts commands from the Read/Write Control Logic, receives control words from the internal data bus and issues the proper commands to its associated ports. Control Group A Port A and Port C upper (C7 C4) Control Group B Port B and Port C lower (C3 C0) The Control Word Register can only be written into. No. Read operation of the Control Word Register is allowed. 112

113 Ports A, B, and C. The 8255A contains three 8-bit ports (A, B, and C). All can be configured in a wide variety of functional characteristics by the system software but each has its own special features or personally to further enhance the power and flexibility of the 8255A. Port A. One 8 bit data output latch/buffer and one 8-bit data input latch. Port B. One 8-bit data output latch/buffer and one 8-bit data input buffer. Port C. One 8-bit data output latch/buffer and one 8-bit data input buffer (no latch for input). This port can be divided into two 4-bit ports under the mode control. Each 4-bit port contains a 4-bit latch and it can be used for the controls signal outputs and status signal inputs in conjunction with ports A and B Control word Figure 4.3. Control word format of 8255 D 7 D 0 RESET CS RD DATA BUS DIRECTIONAL RESET INPUT CHIP SELECT READ INPUT 113

114 WR A0 A1 PA 7 PA 0 PB 7 PB 0 PC 7 PC 0 Vcc GND WRITE INPUT PORT ADDRESS PORT A (BIT) PORT B (BIT) PORT C (BIT) 5 VOLTS 0 VOLTS Mode Selection There are three basic modes of operation that can be selected by the systems software: Mode O Basic Input/Output Mode 1 Strobed Input/Output Mode 2 Bi-Directional Bus When the reset Input goes high all ports will be set to the Input mode (i.e., all 24 lines will be in the high Impedance state). After the reset is removed the 8255A can remain in the input mode with no additional Initialization required. During the execution of the systems program any of the other modes may be selected using a single output Instruction. This allows a single 8255A to service a variety of peripheral devices with a simple software maintenance routine. The modes for Ports A and Port B can be separately defined, while Port C is divided into two portions as required by the Port A and Port B definitions. All of the output registers, including the status flip-flops, will be reset whenever the mode is changed. Modes may be combined so that their functional definition can be tailored to almost any I/O stricture. For instance; Group B can be programmed in Mode 0 to monitor simple switch closing or display computational results, Group A could be programmed in Mode 1 to monitor a keyboard or tape reader on an interrupt-driven basis. The Mode definitions and possible mode combinations may seem confusing at first but after a cursory review of the complete device operation a simple, logical I/O approach will surface. The design of the 8255A has taken into account things such as efficient PC board layout, control signal definition vs PC layout and complete functional flexibility to support almost any peripheral device with no use of the available pints Interrupt Control Functions When the 8255A is programmed to operate in mode 1 or mode 2, control signals are provided that can used as interrupt request input to the CPU. The interrupt request signal generated from port C, can be inhibited or enabled by setting or resetting the associated INTE flip-flop, using the bit set/reset function of port C. 114

115 This function allows the Programmer to disallow or allow a specific I/O device to interrupt the CPU without affecting any other device in the interrupt structure. Figure Mode Definition Format INTE flip-flop definition (BIT-SET) INTE is SET Interrupt enable (BIT-RESET) INTE is RESET Interrupt disable Note: All Mask flip-flops are automatically reset during mode selection and device reset Modes of operation BIT/RESET Mode,BSR mode Single Bit Set/Reset Feature Any of the eight bits of Port C can be Set or Reset using a single OUT put Instruction. This feature reduces software requirements in Control-based applications. 115

116 Figure BSR Mode Definition Format When Port C is being used as status/control for Port A or B these Bits can be set or reset by using the Bit set/reset operation just as if they were data output port MODE 0: Simple input or Output Mode 0 (Basic Input/Output). This functional configuration provides simple input operations for each of the three ports. No handshaking is required data is simply written to or read from a specified port. Mode O Basic Functional Definitions: Two 8-bit ports and two 4-bit port Any port can be input or output. Outputs are not latched. Inputs are not latched. 16 different Input/output configurations are not possible in this Mode. Mode 0 Configuration examples 116

117 MODE1: input or Output with handshake. MODE 1 (Strobed Input/Output). This functional configuration provides a means for transferring I/O data to or from a specified port in conjunction with strobes or handshaking signals. In mode 1, port A and Port B use the lines on port C to generate or accept these handshaking signals. Mode 1 Basic Functional Definitions: Two groups (Group A and Group B) Each group contains one 8-bit data port and one 4-bit control/data port. The 8-bit data port can be either Inputs or output Both inputs and outputs are latched. The 4-bit port is used for control and status of the 8-bit data port. 3. Input Control Signal Definition STB (Strobe Input). A low on the input loads data into the input latch. IBF (Input Buffer Full F/F) A high on this output indicates that the data has been loaded into the input latch. In essence, an acknowledgement. IBF is set by STB input being low and is reset by the rising edge of the RD input. INTR (Interrupt Request) A high on this output can be used to interrupt the CPU when an input device is requesting service, INTR is set by the STB is a one, IBF is a one and INTE is one. It is reset by the falling edge of RD. This procedure allows an input device to request service from the CPU by simply strobing its data into port. INTE A Controlled by bit set/reset of PC 4 INTE B Controlled by set/reset PC 2 Output Control Signal Definition OBF (Output Buffer Full F/F). The OBF output will go low to indicate that the CPU has written data out to the specified port. The OBF F/F will be set by rising edge of the WR input being low. ACK (Acknowledge Input). A low on this input informs the 8255A that the data from port A or port B has been accepted. In essence, a response from the peripheral device indicating that it has received the data output by CPU. INTR (Interrupt Request). A high on the output can be used to interrupt the CPU when an output device has accepted data transmitted by the CPU. INTR is set when ACK is a one, OBF is a one, and INTE is a one. It is reset by the falling edge of WR. 117

118 INTE A Controlled by bit set/reset of PC 6. INTE B Controlled by bit set/reset of PC

119 Combination of MODE 1 Port A and B can be Individually defined as Input or output in Mode 1 to support a wide varlety of strobed I/O application. 119

120 Figure 4.6. Combination of Modes MODE 2: Bidirectional Data Transfer Mode 2 (Strobed Bidirectional Bus I/O). This functional configuration provides a means for communicating with a peripheral device or structure on a single 8-bit bus for both transmitting and receiving data (bi-directional bus I/O). Handshaking signals are provided to maintain proper bus flow discipline in a similar manner to MODE. 1. Interrupt generation and enable/disable functions are also available. MODE 2 Basic Functional Definitions: Used in Group A only. One 8-bit, bi-directional bus Port (Port A) and a 5-bit control Port (Port C). Both Inputs and Outputs are latched. The 5-bit control port (Port C) is used for control and status for the 8-bit,bi-directional bus port (Port A). Bi-directional Bus I/O Control Signal Definition INTR (Interrupt Request). A high on this output can be used to interrupt the CPU for both input or output operations. Output Operations OBF (Output Buffer Full). The OBF output will go low to indicate that the CPU has written data out to port A. ACK (Acknowledge). A low on this input enables the iri-state output buffer of port A to send out the data. Otherwise, the output buffer will be in the high impedance state. INTE 1 (The INTE Flip-Flop Associated with OBF). Controlled by bit set/reset of PC6 120

121 Input Operations STB (Strobe Interrupt) STB (Strobed Input). A low on this input loads data into the input latch. IBF (Input Buffer Full F/F). A high on this output indicates that data has been loaded into the input latch. INTE 2 (The INTE Flip-Flop Associated with IBF). Controlled by bit set/reset of PC4. INPUT CONFIGURATION D 7 D 6 D 5 D 4 D 3 D 2 D 1 D 0 I/O I/O IBF A INTE A INTR A INTE B IBF B INTR B GROUP A GROUP B OUTPUT CONFIGURATION D 7 D 6 D 5 D 4 D 3 D 2 D 1 D 0 OBF A INTE A I/O I/O INTR A INTE B OBF B INTER B Figure 4.7. MODE 1 STATUS WORD FORMAT D 7 D 6 D 5 D 4 D 3 D 2 D 1 D 0 OBF A INTE 1 IBF A INTE 2 INTR A Figure 4.8. Mode 2 Status Word Format INTERFACING WITH MICROPROCESSOR The 8255 can be either memory mapped or I/O mapped in the system. In the schematic shown in above is I/O mapped in the system. Using a 3-to-8 decoder generates the chip select signals for I/O mapped devices. The address lines A4, A5 and A6 are decoded to generate eight chip select signals (IOCS-0 to IOCS-7) and in this, the chip select IOCS- 1 is used to select The address line A7 and the control signal IO/M (low) are used as enable for the decoder. The address line A0 of 8085 is connected to A0 of 8255 and A1 of 8085 is connected to A1 of 8255 to provide the internal addresses. The data lines D0-D7 are connected to D0-D7 of the processor to achieve parallel data transfer. The I/O addresses allotted to the internal devices of 8255 are listed in table. 121

122 Figure 4.9. Interfacing with 8086 Figure Interfacing with

123 Programs Examples Example: Mode 1 Input Example: Mode 1 output 123

124 Keyboard example Figure Interfacing 8255 with matrix keyboard 124

125 Figure Circuit diagram to interface led with

126 4.5. Interfacing with intel 8251(USART Features of 8251 The 8251A is a programmable serial communication interface chip designed for synchronous and asynchronous serial data communication. It supports the serial transmission of data. It is packed in a 28 pin DIP block diagram of 8251 The functional block diagram of 825 1A consists five sections. They are: Read/Write control logic Transmitter Receiver Data bus buffer Modem control. The functional block diagram is shown in fig: 126

127 figure Block diagram of Read/Write control logic: The Read/Write Control logic interfaces the 8251A with CPU, determines the functions of the 8251A according to the control word written into its control register. It monitors the data flow. This section has three registers and they are control register, status register and data buffer. The active low signals RD, WR, CS and C/D(Low) are used for read/write operations with these three registers. When C/D(low) is high, the control register is selected for writing control word or reading status word. When C/D(low) is low, the data buffer is selected for read/write operation. When the reset is high, it forces 8251A into the idle mode. The clock input is necessary for 8251A for communication with CPU and this clock does not control either the serial transmission or the reception rate Transmitter Section The transmitter section accepts parallel data from CPU and converts them into serial data. The transmitter section is double buffered, i.e., it has a buffer register to hold an 8-bit parallel data and another register called output register to convert the parallel data into serial bits. When output register is empty, the data is transferred from buffer to output register. Now the processor can again load another data in buffer register. If buffer register is empty, then TxRDY is goes to high. If output register is empty then TxEMPTY goes to high. The clock signal, TxC (low) controls the rate at which the bits are transmitted by the USART. The clock frequency can be 1,16 or 64 times the baud rate. 127

128 Receiver section The receiver section accepts serial data and convert them into parallel data The receiver section is double buffered, i.e., it has an input register to receive serial data and convert to parallel, and a buffer register to hold the parallel data. When the RxD line goes low, the control logic assumes it as a START bit, waits for half a bit time and samples the line again. If the line is still low, then the input register accepts the following bits, forms a character and loads it into the buffer register. The CPU reads the parallel data from the buffer register. When the input register loads a parallel data to buffer register, the RxRDY line goes high. The clock signal RxC (low) controls the rate at which bits are received by the USART. During asynchronous mode, the signal SYNDET/BRKDET will indicate the break in the data transmission. During synchronous mode, the signal SYNDET/BRKDET will indicate the reception of synchronous character Interfacing with microprocessor The 825 1A can be either memory mapped or I/O mapped in the system. 8251A in I/O mapped in the system is shown in the figure. Using a 3-to-8 decoder generates the chip select signals for I/O mapped devices. The address lines A4, A5 and A6 are decoded to generate eight chip select signals (IOCS-0 to IOCS-7) and in this, the chip select signal IOCS-2 is used to select 8251A. The address line A7 and the control signal IO / M(low) are used as enable for decoder. The address line A0 of 8086 is connected to C/D(low) of 8251A to provide the internal addresses. The data lines D0 - D7 are connected to D0 - D7 of the processor to achieve parallel data transfer. The RESET and clock signals are supplied by the processor. Here the processor clock is directly connected to 8251A. This clock controls the parallel data transfer between the processor and 8251A. The output clock signal of 8086 is divided by suitable clock dividers like programmable timer 8254 and then used as clock for serial transmission and reception. The TTL logic levels of the serial data lines and the control signals necessary for serial transmission and reception are converted to RS232 logic levels using MAX232 and then terminated on a standard 9-pin D-.type connector. In 8251A the transmission and reception baud rates can be different or same. The device which requires serial communication with processor can be connected to this 9-pin D- type connector using 9-core cable. The signals TxEMPTY, TxRDY and RxRDY can be used as interrupt signals to initiate interrupt driven data transfer scheme between processor and 8251 A. 128

129 Figure Interfacing 8251 with 8086 Figure Interfacing 8251 with

130 130

131 4.6. KEYBOARD/DISPLAY CONTROLLER Features of 8279 The INTEL 8279 is specially developed for interfacing keyboard and display devices to 8085/8086/8088 microprocessor based system. The important features of 8279 are, Simultaneous keyboard and display operations. Scanned keyboard mode. Scanned sensor mode. 8-character keyboard FIFO. 1 6-character display. Right or left entry 1 6-byte display RAM Pin Diagram Figure Pin diagram of 8279 DB 0 -DB 7 : These are bidirectional data bus lines. The data and command words to and from the CPU are transferred on these lines. RD, WR ( Input / Output ) READ/WRITE :These input pins enable the data buffers to receive or send data over the data bus. A0(Address lines) : A high on this line indicates the transfer of a command or status information. A low on this line indicates the transfer of data. This is used to select one of the internal registers of CS : Chip Select A low on this line enables 8279 for normal read or write operations. Other wise, this pin should remain high. 131

132 RESET : This pin is used to reset A high on this line reset After resetting 8279, its in sixteen 8-bit display, left entry encoded scan, 2-key lock out mode. The clock prescaler is set to 31. CLK : This is a clock input used to generate internal timing required by IRQ : This interrupt output lines goes high when there is a data in the FIFO sensor RAM. The interrupt lines goes low with each FIFO RAM read operation but if the FIFO RAM further contains any key-code entry to be read by the CPU, this pin again goes high to generate an interrupt to the CPU. Vss, Vcc : These are the ground and power supply lines for the circuit. SL0-SL3-Scan Lines : These lines are used to scan the key board matrix and display digits. These lines can be programmed as encoded or decoded, using the mode control register. RL0 - RL7 - Return Lines : These are the input lines which are connected to one terminal of keys, while the other terminal of the keys are connected to the decoded scan lines. These are normally high, but pulled low when a key is pressed. SHIFT : The status of the shift input lines is stored along with each key code in FIFO, in scanned keyboard mode. It is pulled up internally to keep it high, till it is pulled low with a key closure. CNTL/STB- CONTROL/STROBED I/P Mode : In keyboard mode, this lines is used as a control input and stored in FIFO on a key closure. The line is a strobed lines that enters the data into FIFO RAM, in strobed input mode. It has an interrupt pull up. The lines is pulled down with a key closer. OUT A0 OUT A3 and OUT B0 OUT B3 : These are the output ports for two 16*4 or 16*8 internal display refresh registers. The data from these lines is synchronized with the scan lines to scan the display and keyboard. The two 4-bit ports may also as one 8-bit port. BD Blank Display : This output pin is used to blank the display during digit switching or by a blanking closure Block diagram of Keyboard Section The keyboard section consists of eight return lines RL0 - RL7 that can be used to form the columns of a keyboard matrix. It has two additional input : shift and control/strobe. The keys are automatically debounced. The two operating modes of keyboard section are 2-key lockout and N-key rollover. In the 2-key lockout mode, if two keys are pressed simultaneously, only the first key is recognized. In the N-key rollover mode simultaneous keys are recognized and their codes are stored in FIFO. The keyboard section also has an 8 x 8 FIFO (First In First Out) RAM. The FIFO can store eight key codes in the scan keyboard mode. The status of the loving valentine day screen saver for loving people from and get new tips and tricks for lovers URL... An interrupt signal when there is an entry in FIFO. The format of key code entry in FIFO for scan keyboard mode is, 132

133 Display section Figure Block diagram of 8279 The display section has eight output lines divided into two groups A0-A3 and B0-B3. The output lines can be used either as a single group of eight lines or as two groups of four lines, in conjunction with the scan lines for a multiplexed display. The output lines are connected to the anodes through driver transistor in case of common cathode 7- segment LEDs. The cathodes are connected to scan lines through driver transistors. The display can be blanked by BD (low) line. The display section consists of 16 x 8 display RAM. The CPU can read from or write into any location of the display RAM Scan section: The scan section has a scan counter and four scan lines, SL0 to SL3. In decoded scan mode, the output of scan lines will be similar to a 2-to-4 decoder. 133

134 In encoded scan mode, the output of scan lines will be binary count, and so an external decoder should be used to convert the binary count to decoded output. The scan lines are common for keyboard and display. The scan lines are used to form the rows of a matrix keyboard and also connected to digit drivers of a multiplexed display, to turn ON/OFF CPU interface section: The CPU interface section takes care of data transfer between 8279 and the processor. This section has eight bidirectional data lines DB0 to DB7 for data transfer between 8279 and CPU. It requires two internal address A =0 for selecting data buffer and A = 1 for selecting control register of8279. The control signals WR (low), RD (low), CS (low) and A0 are used for read/write to It has an interrupt request line IRQ, for interrupt driven data transfer with processor. The 8279 require an internal clock frequency of 100 khz. This can be obtained by dividing the input clock by an internal prescaler. The RESET signal sets the 8279 in 16-character display with two -key lockout keyboard modes Modes of operation The keyboard matrix can be any size from 2x2 to 8x8. Pins SL2-SL0 sequentially scan each column through a counting operation. The 74LS138 drives 0's on one line at a time. The 8279 scans RL pins synchronously with the scan. RL pins incorporate internal pull-ups, no need for external resistor pull-ups. The 8279 must be programmed first. The first 3 bits of the byte sent to control port selects one of 8 control words. First three bits given below select one of 8 control registers (opcode). 000DDMMM Mode set: Opcode 000. DD sets displays mode. MMM sets keyboard mode. DD field selects either: 8- or 16-digit display Whether new data are entered to the rightmost or leftmost display position. 134

135 MMM field: Encoded: SL outputs are active-high, follow binary bit pattern 0-7 or Decoded: SL outputs are active-low (only one low at any time). Pattern output: 1110, 1101, 1011, Strobed: An active high pulse on the CN/ST input pin strobes data from the RL pins into an internal FIFO for reading by micro later. 2-key lockout/n-key rollover: Prevents 2 keys from being recognized if pressed simultaneously/accepts all keys pressed from 1st to last. 001PPPPP The clock command word programs the internal clock driver. The code PPPPP divides the clock input pin (CLK) to achieve the desired operating frequency, e.g. 100KHz requires for a 1 MHz CLK input. 010Z0AAA The read FIFO control word selects the address (AAA) of a keystroke from the FIFO buffer (000 to 111). Z selects auto-increment for the address. 011ZAAAA The display read control word selects the read address of one of the display RAM positions for reading through the data port. 100ZAAAA Selects write address -- Z selects auto-increment so subsequent writes go to subsequent display positions. 1010WWBB The display write inhibit control word inhibits writing to either the leftmost 4 bits of the display (left W) or rightmost 4 bits. BB works similarly except that they blank (turn off) half of the output pins. 1100CCFA 135

136 The clear control word clears the display, FIFO or both Bit F clears FIFO and the display RAM status, and sets address pointer to 000. If CC are 00 or 01, all display RAM locations become If CC is 10, --> , if CC is 11, --> E000 End of Interrupt control word is issued to clear IRQ pin in sensor matrix mode Clock must be programmed first. If 3.0 MHz drives CLK input, PPPPP is programmed to 30 or Keyboard type is programmed next. The previous example illustrates an encoded keyboard, external decoder used to drive matrix. Program the FIFO. Once done, a procedure is needed to read data from the keyboard. To determine if a character has been typed, the FIFO status register is checked. When the control port is addressed by the IN instruction, the contents of the FIFO status word is copied into register AL: FIFO Status Register Code given in text for reading keyboard. Data returned from 8279 contains raw data that need to be translated to ASCII: Row and column number are given the rightmost 6 bits (scan/return). This can be converted to ASCII using the XLAT instruction with an ASCII code lookup table. The CT and SH indicate whether the control or shift keys were pressed. The Strobed Keyboard code is just the state of the RLx bits at the time a 1 was 'strobed' on the strobe input pin Interfacing with microprocessor A typical Hexa keyboard and 7-segment LED display interfacing circuit using 8279 is shown. The circuit can be used in 8085 microprocessor system and consist of 16 numbers of hexa-keys and 6 numbers of 7-segment LEDs. The 7-segment LEDs can be used to display six digit alphanumeric character. 136

137 The 8279 can be either memory mapped or I/O mapped in the system. In the circuit shown is the 8279 is I/O mapped. The address line A0 of the system is used as A0 of The clock signal for 8279 is obtained by dividing the output clock signal of 8085 by a clock divider circuit. The chip select signal is obtained from the I/O address decoder of the 8085 system. The chip select signals for I/O mapped devices are generated by using a 3-to-8 decoder. The address lines A4, A5 and A6 are used as input to decoder. The address line A7 and the control signal IO/M (low) are used as enable for decoder. The chip select signal IOCS-3 is used to select The I/O address of the internal devices of 8279 are shown in table. 137

138 The circuit has 6 numbers of 7-segment LEDs and so the 8279 has to be programmed in encoded scan. (Because in decoded scan, only 4 numbers of 7-segment LEDs can be interfaced) In encoded scan the output of scan lines will be binary count. Therefore an external, 3-to-8 decoder is used to decode the scan lines SL0, SL1 and SL2 of 8279 to produce eight scan lines S0 to S7. The decoded scan lines S0 and S1 are common for keyboard and display. The decoded scan lines S2 to S5 are used only for display and the decoded scan lines S6 and S7 are not used in the system. Anode and Cathode drivers are provided to take care of the current requirement of LEDs. The PNP transistors, BC 158 are used as driver transistors. The anode drivers are called segment drivers and cathode drivers are called digit drivers. The 8279 output the display code for one digit through its output lines (OUT A0 to OUT A3 and OUT B0 to OUT B3) and send a scan code through, SL0- SL3. The display code is inverted by segment drivers and sent to segment bus. The scan code is decoded by the decoder and turns ON the corresponding digit driver. Now one digit of the display character is displayed. After a small interval (10 milli-second, typical), the display is turned OFF (i.e., display is blanked) and the above process is repeated for next digit. Thus multiplexed display is performed by The keyboard matrix is- formed using the return lines, RL0 to RL3 of 8279 as columns and decoded scan lines S0 and S1 as rows. A hexa key is placed at the crossing point of each row and column. A key press will short the row and column. Normally the column and row line will be high. During scanning the 8279 will output binary count on SL0 to SL3, which is decoded by decoder to make a row as zero. When a row is zero the 8279 reads the columns. If there is a key press then the corresponding column will be zero. If 8279 detects a key press then it wait for debounce time and again read the columns to generate key code. In encoded scan keyboard mode, the 8279 stores an 8-bit code for each valid key press. The keycode consist of the binary value of the column and row in which the key is found and the status of shift and control key. After a scan time, the next row is made zero and the above process is repeated and so on. Thus 8279 continuously scan the keyboard. 138

139 Figure Interfacing 8279 with 8086 Figure Interfacing 8279 with keyboard 139

140 Figure Interfacing 8279 with seven segment displaykeyboard 4.7. PROGRAMMABLE TIMER 8253 The 8253 is a programmable Interval timer/counter specifically designed for use with the Intel Micro computer systems. Its function is that of a general purpose, multi-timing element that can be treated as an array of I/O ports in the system software. The 8253 solves one of the most common problems any microcomputer system. The generation of accurate time delay under software control. Instead of selling up timing loops in systems software. The programmer configures the 8253 to match his requirements. Initializes one of the counters of the 8253 with the desired quantity, then upon command the 8253 will count-out the delay and interrupt the CPU when it has completed its tasks. It is easy to see that the software overhead is minimal and that multiple delays can easily be maintained by assignment of priority levels. Other counter/timer functions that are non-delay in nature but also common to most microcomputers can be implemented with the Programmable Rate Generator Event Counter Binary Rate Multiplier Real Time Clock Digital One-Shot Complex Motor Controller 140

141 Pin Diagram Block diagram of Data Bus Buffer This 3-state, be directional,8-bit buffer is used to interface the 8253 to the systems data bus. Data is transmitted or received by the buffer upon execution of Input and Output CPU instructions. The Data Bus Buffer has three basic functions. Programming the MODES of the 8253 Loading the count registers Reading the count values Read/Write Logic: The Read/Write Logic accepts inputs from the system bus and in turn generates control signals for overall device operation. It is enabled by CS so that no operation can occur to change the function unless the device has been selected by the system logic. RD (Read) A low on this input informs the 8253 that the CPU is inputting data in the form of a counters value. WR (Write) A low on this input informs the 8253 that the CPU is outputting data in the form of mode information or loading counters. AO,A1 This inputs are normally connected to the address bus. Their function is to select one of the three counters to be operated on and to address the control word register for mode selection. CS (Chip Select) 141

142 A low on this input enables the No reading or writing will occur unless the device is selected. The CS Input has no elect upon the actual operation of the counters. Figure Block diagram of 8253 CS RD WR A 1 A Load Counter No Load Counter No Load Counter No Write Mode Word Read Counter No Read Counter No Read Counter No No Operation 3-State 1 X X X X Disable 3 State X X No Operation 3-State 142

143 Control Word Register The Control Word Register is selected when AO.AI are 11 then accepts information from the data bus buffer and stores it in a register. The information stored in this register controls the operational NODE of each counter, selection of binary or BCD counting and the loading of each count register. The Control Word Register can only be written into no. read operation of its contents is available Counter #0, Counter #1, Counter #2 These three functional blocks are identical in operation so only a single Counter will be described. Each Counter consists of a single 16.bit,pre-sellable DOWN counter. The counter can operate in either binary or BCD and its input, gate and output are configured by the selection of MODES stored in the Control Word Register.The counters are fully independent and each can have separate Mode configuration and counting operation, binary or BCD. Also there are special features in the control word that handle the loading lf the count value so that software overhead can be minimized for these functions. The reading of the contents of each counter is available to the programmer with simple READ operations for event counting applications and special commands and logic are included in the 8253 so that the contents of each counter can be read on the fly without having to inhibit the clock input SYSTEMS INTERFACE The 8253 is a component of the Intel-Microcomputer Systems and Interfaces in the same manner as all other peripherals of the family. It is treated by the systems software as an array of peripheral I/O ports: three are counters and the fourth is a control register for MODE programming.basically, the select Inputs AO, A1 connect to the AO, A1 connect to the A0, A1 address bus signals of the CPU. The CS can be derived directly from the address bus using a linear select method or it can be connected to the output of a decoder, such as an Intel 8205 for larger systems Control Word Block Diagram Showing Control Word and Register and Counter Functions Figure Block Diagram Showing Control Word and Register and Counter Functions 143

144 OPERATIONAL DESCRIPTION The complete functional definition of the 8253 is programmed by the systems software. A set of control words must be sent out by CPU to initialize each counter of the 8253 with the desired MODE and quantity Information. Prior to Initialization. The MODE count, and output of all counters is undefined. These control words program the MODE, Loading sequence and selection of binary or BCD counting. Once programmed, the 8253 is ready to perform whatever timing tasks it is assigned to accomplish. The actual counting operation of each counter is on-chip so that the usual problems associated with efficient monitoring and management of external asynchronous events or rates 10 the microcomputer systems have been eliminated Programming the 8253 All of the MODES for each counter are programmed by the systems software by simple I/O operations. Each counter of the 8253 is individually programmed by writing a control word into the Control Word Register. (A0,A1=1I) Control World Format D7 D6 D5 D4 D3 D2 D1 D0 SC1 SC0 RL1 RL0 M2 M1 M0 BCD Definition of Control SC Select Counter SC1 SC0 0 0 Select Counter Select Counter Select Counter Illegal RL Read/Load RL1 RL0 0 0 Counter Latching operation (see READ/WRITE Procedure section) 1 0 Read / Load most significant byte only 0 1 Read / Load least significant byte only 1 1 Read / Load least significant byte first, then most significant byte 144

145 M MODE Mode 1 X 1 0 Mode 2 X 1 1 Mode Mode Mode 5 BCD: 0 Binary Counter 16 bits Mode 0 1 Binary Coded Decimal (BCD) Counter (4 decade) Counter Loading The count register is not loaded until the count value is written (one or two bytes, depending on the mode selected by the RL bits), followed by a rising edge and a falling clock edge may yield Invalid data Modes of operation MODE O: Interrupt on Terminal Count. The output will be initially low after the mode set operation. After the counts is loaded into the selected count register, the output will remain low and the counter will count. When terminal count is reached the output will go high and remain until the selected count register is reloaded with mode or a new count is loaded. The counter continues to decrement after terminal count has been reached. Rewriting a counter register during counting results in the following: (1) Write 1 st byte stops the current counting (2) Write 2 nd byte starts the new count. MODE 1: Programmable One-Shot. The output will go low on the count following the rising edge of the gate input.the output will go high on the terminal count. If a new count value is loaded while the output is low it will not affect the duration of the one-shot pulse until the succeeding trigger. The current count can be read at any time without affecting the one-shot pulse.the one-shot is retriggerable, hence the output. It remain low for the full count after any rising edge of the gate input. MODE 2: Rate Generator. Divide by N counter. The output will be low for one period of the Input clock. The period from one output pulse to the next equals the number of input counts in the count register. If the count register is reloaded between output pulses the present period will not be affected, but the subsequent 145

146 period will reflect the new value.the gate Input, when low, will force the output high. When the gate Input goes high, the counter will start from the Initial count. Thus, the gate Input can be used to synchronize the counter. MODE 3: Square Wave Rate Generator. Similar to MODE 2 except that the output will remain high until one half the count has been completed (for even numbers) and go low for the other half of the count. This is accomplished by decrementing the counter by two on the falling edge of each clock pulse. When the counter reaches terminal count, the state of the output is changed and the counter is reloaded with the full count and the whole process is repeated.if the count is odd and output is high, the first clock pulse (after the count is loaded) decrements the count by 1. Subsequent clock pulses decrement the clock by 2. After timeout, the output goes low and the full count is reloaded. The first clock pulse (following the reload decrements the counter by 3. Subsequent clock pulses decrement the count by 2 until timeout. Then the whole process is repeated. In this way. If the count is odd, the output will be high for (N + 1)/2 counts and low for (N-1)/2 counts. MODE 4: Software Triggered 8trobe. After the mode is set, the output will be high. When the count is loaded, the counter will begin counting. On terminal count, the output will go low for one input clock period, then will go high again.if the count register is reloaded during counting, the new count will be loaded on the next CLK pulse. The count will be inhibited while the GATE input is low. MODE 5: Hardware Triggered Strobe. The counter will start counting after the rising edge of the trigger input and will go low for one clock period when the terminal count is reached. The counter is retriggerable. The output will not go low until the full count after the rising edge of any trigger. Summary modes of 8253 Each counter may be programmed with a count of 1 to FFFFH. Minimum count is 1 all modes except 2 and 3 with minimum count of 2. Each counter has a program control word used to select the way the counter operates. If two bytes are programmed, then the first byte (LSB) stops the count, and the second byte (MSB) starts the counter with the new count. There are 6 modes of operation for each counter: Mode 0: An events counter enabled with G. The output becomes a logic 0 when the control word is written and remains there until N plus the number of programmed counts. 146

147 8254 Modes Mode 1: One-shot mode. The G input triggers the counter to output a 0 pulse for ÔcountÕ clocks. Counter reloaded if G is pulsed again. Mode 2: Counter generates a series of pulses 1 clock pulse wide. The separation between pulses is determined by the count. The cycle is repeated until reprogrammed or G pin set to 0. Mode 3: Generates a continuous square-wave with G set to 1. If count is even, 50% duty cycle otherwise OUT is high 1 cycle longer. Mode 4: Software triggered one-shot (G must be 1). 147

148 Mode 5: Hardware triggered one-shot. G controls similar to Mode 1. CONTROL REGISTER OF 8253(TIMER) To interface 8253 with 8086 using Mode 0 - Interrupt On Terminal Count: To interface 8253 with 8086 using Mode 1 - Programmable One-Shot: 148

149 To interface 8253 with 8086 using Mode 2 - Rate Generator: To interface 8253 with 8086 using mode 3 - square waves generator: To generate a square wave of frequency 270 KHz at OUT2, CLK 0 of 8253 is connected to PCLK of frequency 3 MHz Square wave frequency = PCLK/COUNT=3/11= MHz=280KHz Where,PCLK 3.1 MHz Count 0x0B [(11)10] 4.8. Programmable DMA controller - intel 8257 It is a device to transfer the data directly between IO device and memory without through the CPU. So it performs a high-speed data transfer between memory and I/O device The features of 8257 The 8257 has four channels and so it can be used to provide DMA to four I/O devices Each channel can be independently programmable to transfer up to 64kb of data by DMA. Each channel can be independently perform read transfer, write transfer and verify transfer. The functional blocks of 8257 are data bus buffer, read/write logic, control logic, priority resolver and four numbers of DMA channels. 149

150 Pin Diagram figure Pin diagram of Block diagram of Modes of operation two programmable 16-bit registers named as address register and count register. Address register is used to store the starting address of memory location for DMA data transfer. The address in the address register is automatically incremented after every read/write/verify transfer. The count register is used to count the number of byte or word transferred by DMA. The format of count register is, 14-bits B0-B13 is used to count value and a 2-bits is used for indicate the type of DMA transfer (Read/Write/Veri1 transfer). 150

151 In read transfer the data is transferred from memory to I/O device. figure Block diagram of 8251 In write transfer the data is transferred from I/O device to memory. Verification operations generate the DMA addresses without generating the DMA memory and I/O control signals. The 8257 has two eight bit registers called mode set register and status register. The format of mode set register is given below, The use of mode set register is, 1. Enable/disable a channel. 2. Fixed/rotating priority 3. Stop DMA on terminal count. 151

152 4. Extended/normal write time. 5. Auto reloading of channel-2. The bits B0, B1, B2, and B3 of mode set register are used to enable/disable channel -0, 1, 2 and 3 respectively. A one in these bit position will enable a particular channel and a zero will disable it. If the bit B4 is set to one, then the channels will have rotating priority and if it zero then the channels wilt have fixed priority. 1. In rotating priority after servicing a channel its priority is made as lowest. 2. In fixed priority the channel-0 has highest priority and channel-2 has lowest priority. If the bit B5 is set to one, then the timing of low write signals (MEMW and IOW) will be extended. If the bit B6 is set to one then the DMA operation is stopped at the terminal count. The bit B7 is used to select the auto load feature for DMA channel-2. When bit B7 is set to one, then the content of channel-3 count and address registers are loaded in channel-2 count and address registers respectively whenever the channel-2 reaches terminal count. When this mode is activated the number of channels available for DMA reduces from four to three. The format of status register of 8257 is shown in fig. 152

153 The bit B0, B1, B2, and B3 of status register indicates the terminal count status of channel-0, 1,2 and 3 respectively. A one in these bit positions indicates that the particular channel has reached terminal count. These status bits are cleared after a read operation by microprocessor. The bit B4 of status register is called update flag and a one in this bit position indicates that the channel-2 register has been reloaded from channel-3 registers in the auto load mode of operation. The internal addresses of the registers of 8257 are listed in table Interfacing with microprocessor A simple schematic for interfacing the 8257 with 8085 processor is shown. The 8257 can be either memory mapped or I/O mapped in the system. In the schematic shown in figure is I/O mapped in the system. Using a 3-to-8 decoder generates the chip select signals for I/O mapped devices. The address lines A4, A5 and A6 are decoded to generate eight chip select signals (IOCS-0 to IOCS-7) and in this the chip select signal IOCS-6 is used to select The address line A7 and the control signal IO/M (low) are used as enable for decoder. The D0-D7 lines of 8257 are connected to data bus lines D0-D7 for data transfer with processor during programming mode. These lines (D0-D7) are also used by 8257 to supply the memory address A8-A15 during the DMA mode. The 8257 also supply two control signals ADSTB and AEN to latch the address supplied by it during DMA mode on external latches. 153

154 Two 8-bit latches are provided to hold the 16-bit memory address during DMA mode. During DMA mode, the AEN signal is also used to disable the buffers and latches used for address, data and control signals of the processor. The 8257 provide separate read and write control signals for memory and I/O devices during DMA. Therefore the RD (low), WR (low) and IO/M (low) of the 8085 processor are decoded by a suitable logic circuit to generate separate read and write control signals f memory and I/O devices. The output clock of 8085 processor should be inverted and supplied to 8257 clock input for proper operation. The HRQ output of 8257 is connected to HOLD input of 8085 in order to make a HOLD request to the processor. The HLDA output of 8085 is connected to HLDA input of 8257, in order to receive the acknowledge signal from the processor once the HOLD request is accepted. The RESET OUT of 8085 processor is connected to RESET of The I/O addresses of the internal registers of 8257 are listed in table. Figure Interfacing 8257/37 with 8085/

155 DMA controller Interfacing to an 8086/8085 based maximum mode system. For 8088 in maximum mode: The RQ/GT1 and RQ/GT0 pins are utilized to issue DMA signals of request and receive acknowledge. Sequence of events of a usual DMA process 1. Peripheral asserts one of the request pins, for example: RQ/GT1 or RQ/GT0 (has higher priority) finishes its current bus cycle and enters in a HOLD state grants the right of bus control through asserting a grant signal via similar pin as the request signal. 4. DMA operation starts 5. Upon end of the DMA operation, there peripheral asserts the request/grant pin again to relinquish bus control. Figure Interfacing 8257/37 with

156 Building a System To build a usable system you obviously need more than just the processor. For a minimum embedded system you would need: An Interrupt Controller. Interrupts are an essential part of any system. The 8088 is normally paired with an 8259A Programmable Interrupt Controller. Although this device is as old as the 8088 due to legacy issues you will still find it on any modern PC. Note that you can not simply connect an device IRQ to the 8088 INTR input without additional glue logic. The reason for this is that an 8088 expects an interrupt vector to be pushed onto the databus during the second Interrupt ACKnowledge cycle. A Timer unit. Any embedded application even the simplest one needs timers to generate periodic interrupts (e.g. OS task switching, time keeping functions, DRAM refresh etc). The obvious choice is an 8254/8253 Programmable Timer. Parallel I/O Port. For any Parallel I/O operations an 8255 Programmable Peripheral Interface (PPI) can be used. This is a versatile device that can be configure in simple I/O, strobed I/O or fully bidirectional I/O Interfacing Digital-to-Analog Converter (DAC) To convert the digital signal to analog signal a Digital-to-Analog Converter (DAC) has to be employed. The DAC will accept a digital (binary) input and convert to analog voltage or current. Every DAC will have "n" input lines and an analog output. The DAC require a reference analog voltage (Vref) or current (Iref) source. The smallest possible analog value that can be represented by the n-bit binary code is called resolution. The resolution of DAC with n-bit binary input is 1/2nof reference analog value. Every analog output will be a multiple of the resolution. 156

157 Pin Configuration Figure Pin diagram of DAC Interfacing with microprocessor The DAC0800 can be interfaced to 8085 system bus by using an 8-bit latch and the latch can be enabled by using one of the chip select signal generated for I/O devices. A simple schematic for interfacing DAC0800 with 8085 is, In this schematic the DAC0800 is interfaced using an 8-bit latch 74LS273 to the system bus. The 3-to-8 decoder 74LS 138 is used to generate chip select signals for I/O devices. The address lines A4, A5 and A6 are used as input to decoder. The address line A7 and the control signal IO/M (low) are used as enable for decoder. The decoder will generate eight chip select signals and in this the signal IOCS-7 is used as enable for latch of DAC. The I/O address of the DAC is shown in table. Figure Interfacing DAC with

158 In order to convert a digital data to analog value, the processor has to load the data to latch. The latch will hold the previous data until next data is loaded. The DAC will take definite time to convert the data. The software should take care of loading successive data only after the conversion time. The DAC 0800 produces a current output, which is converted to voltage output using Ito V converter Example 1 Interfacing DAC 0800 Fig 1 shows DAC0800 series are monolithic 8-bit high-speed current output digital-to-analog converters (DAC) featuring typical settling times of 100 ns.. The noise immune inputs will accept variety of logic levels. The performance and characteristics of the device are essentially unchanged over the ±4.5V to ±18V power supply range and power consumption at only 33 mw with ±5V supplies is independent of logic input levels. 158

159 EXAMPLE 2 Interfacing DAC 7523 The digital to analog converters convert binary number into their equivalent voltages. The DAC find applications in areas like digitally controlled gains, motors speed controls, programmable gain amplifiers etc. AD bit Multiplying DAC : This is a 16 pin DIP, multiplying digital to analog converter, containing R-2R ladder for D-A conversion along with single pole double thrown NMOS switches to connect the digital inputs to the ladder. The pin diagram of AD7523 is shown in fig the supply range is from +5V to +15V, while Vref may be any where between -10V to +10V. The maximum analog output voltage will be any where between -10V to +10V, when all the digital inputs are at logic high state. 159

160 Usually a zener is connected between OUT1 and OUT2 to save the DAC from negative transients. An operational amplifier is used as a current to voltage converter at the output of AD to convert the current out put of AD to a proportional output voltage. It also offers additional drive capability to the DAC output. An external feedback resistor acts to control the gain. One may not connect any external feedback resistor, if no gain control is required. EXAMPLE: Interfacing DAC AD7523 with an 8086 CPU running at 8MHZ and write an assembly language program to generate a sawtooth waveform of period 1ms with Vmax 5V. Solution: Fig shows the interfacing circuit of AD with 8086 using program gives an ALP to generate a sawtooth waveform using circuit. ASSUME CS:CODE CODE SEGMENT START: MOV AL,80h ;make all ports output OUT CW, AL AGAIN: MOV AL,00h ;start voltage for ramp BACK : OUT PA, AL INC AL CMP AL, 0FFh JB BACK JMP AGAIN CODE ENDS END START 160

161 In the above program, port A is initialized as the output port for sending the digital data as input to DAC. The ramp starts from the 0V (analog), hence AL starts with 00H. To increment the ramp, the content of AL is increased during each execution of loop till it reaches F2H. After that the saw tooth wave again starts from 00H, i.e. 0V(analog) and the procedure is repeated. The ramp period given by this program is precisely ms. Here the count F2H has been calculated by dividing the required delay of 1ms by the time required for the execution of the loop once. The ramp slope can be controlled by calling a controllable delay after the OUT instruction INTERFACING ANALOG TO-DIGITAL (ADC) ADC0809 is an 8-bit successive approximation type ADC with inbuilt 8-channel multiplexer. The ADC0809 is suitable for interface with 8086 microprocessor. The ADC0809 is available as a 28 pin IC in DIP (Dual Inline Package). The ADC0809 has a total unadjusted error of ±1 LSD (Least Significant Digit). The ADC0808 is also same as ADC0809 except the error. The total unadjusted error in ADC0808 is ± 1/2 LSD Pin Configuration 161

162 Interfacing with microprocessor The internal block diagram of ADC0809/ADC0808 is, The various functional blocks of ADC are 8- channel multiplexer, comparator, 256R resistor ladder, switch tree, successive approximation register, output buffer, address latch and decoder. The 8-channel multiplexer can accept eight analog inputs in the range of 0 to 5V and allow one by one for conversion depending on the 3-bit address input. The channel selection logic is, 162

163 The successive approximation register (SAR) performs eight iterations to determine the digital code for input value. The SAR is reset on the positive edge of START pulse and start the conversion process on the falling edge of START pulse. A conversion process will be interrupted on receipt of new START pulse. The End-Of-Conversion (EOC) will go low between 0 and 8 clock pulses after the positive edge of START pulse. The ADC can be used in continuous conversion mode by tying the EOC output to START input. In this mode an external START pulse should be applied whenever power is switched ON. The 256'R resistor network and the switch tree is shown in fig. The 256R ladder network has been provided instead of conventional R/2R ladder because of its inherent monotonic, which guarantees no missing digital codes. 163

164 Also the 256R resistor network does not cause load variations on the reference voltage. The comparator in ADC0809/ADC0808 is a chopper- stabilized comparator. It converts the DC input signal into an AC signal, and amplifies the AC sign using high gain AC amplifier. Then it converts AC signal to DC signal. This technique limits the drift component of the amplifier, because the drift is a DC component and it is not amplified/passed by the AC amp1ifier. This makes the ADC extremely insensitive to temperature, long term drift and input offset errors. In ADC conversion process the input analog value is quantized and each quantized analog value will have a unique binary equivalent. The quantization step in ADC0809/ADC0808 is given by, 164

165 ADC 0809 The ADC0808, ADC0809 data acquisition component is a Monolithic CMOS device with an 8-bit analogto-digital converter,8-channel multiplexer and microprocessor compatible control logic. The 8-bit A/D converter uses successive approximations the conversion technique. The converter features a high impedance chopper stabilized comparator, a 256R voltage divider with analog switch tree and a successive approximation register INTERFACING ADC 0809 WITH microprocessor it doesn t have an On chip ADC to accept the digital input, it will not accept analog input, so we need a ADC to process the analog signal. For interfacing ADC 0809 we require 8 data lines. So ADC 0809 is an 8 bit ADC has 8 channels works on successive approximation conversion technique 165

166 ASSEMBLY PROGRAM TO INTERFACE ADC 0809 WITH

167 167

168 ASSIGNMENT(DONE IN LABORATORY ) Interface ADC 0809 with Objective:- To write an 8086 ALP to convert an analog signal in the range of 0v to 5v. to its corresponding digital signal using successive approximation ADC 0809 and displaying same on 8086 kits display Apparatus : DYNA Kit, ADC card, Single variable power supply, 26 pin FRC, Logic Probe, etc. Theory : - Block Diagram of ADC 0809 Signals of ADC 0809 Vcc Supply pins +5V GND Ground Vref + Reference voltage positive +5 Volts maximum. Vref_ Reference voltage negative 0Volts minimum. I/P0 I/P7 Analog inputs 168

169 ADD A,B,C Address lines for selecting analog inputs. D7 D0 Digital 8-bit output with D7 MSB and D0 LSB SOC Start of conversion signal pin EOC End of conversion signal pin OE Output latch enable pin, if low enables output CLK Clock input for ADC If one needs a sample and hold circuit for the conversion of fast signal into equivalent digital quantities, it has to be externally connected at each of the analog inputs. ADC 0809 is a n 8 bit successive approximation ADC. This chip has 8 channels along with multiplexer. The channel select has address lines A, B,C. We can use channel 0 as input thus. Address lines A, B, C will be grounded for channel 0. The ALE pin is connected to the clock input. ADC 0809 has an START on Conversion pin. A positive going pulse of short duration, is applied to this pin this pin starts the A/D conversion process. After the conversion, EOC is driven high, indicating end of conversion. The OE should always be low, when data is to be read.. FEATURES of ADC 0809 :- 1.Resolution 8 bits. 2.Total unadjusted error I ½ LLSB. 169

170 3.No missing codes 4.Single supply 5 V DC 5.8 channel multiplexer with latched control logic 6.Easy interface to all i/p 7.(0 5) V analog i/p voltage range with supply. 8.No zero or full scale adjust required 9.Standard 28 pin o/p package. 10.Temperature range 400C to 850C or 550C to 1250C 11.Low power consumption. 12.Latched TRI-STATE o/p. Interfacing Diagram : - PROCEDURE :- 1.Keep 0809 to left side of 8086 kit. 2.Connect the ADC card to 8086 by 26 pin FRC. 3.Do not connect or remove the 0809 card to form 8086 kit while power is on. 4.Connect the output of single power supply to input channel of ADC using probe. 5.Before switching ON the power supply, check direction of 26 pin connector. Then connect 9 pin power connector to the 8086 & through that it is connected to ADC. 6.All supply connections +5V, +12V, -12V must be supplied simultaneously through ADC 0809 card. 170

171 7.Before switching ON the power supply, ensure that voltages are minimum. If the supply is above 5 V, it may damage 0809 card. 8.Execute the program. 9.Check the output on LCD display of 8086 kit corresponding to given i/p. 10.Change analog input & observe corresponding digital output on LCD display. ALGORITHM :- 1. Initialise 8255 in mode O. Port A as input, Port B as output and Port C as input. 2. Enable the Oscillation (PB2) & Send start of conversion (SOC) (PB0)pulse by applying 11 & then 10 through PB2 and PB0 respectively. 3.After this Check whether EOC is high through PC0 or PC7. 1.If EOC = 1, the conversion is over output buffer is enabled (OE) by applying 1 through PB1 and then converted digital data read through port A (PA0 to PA7) 2. If EOC = 0 wait for end of conversion(eoc) signal. return to step 4. 4.Read data & display. 5.Goto step 3 PROGRAM :- 171

172 Example 2: Interfacing ADC 0808 with 8086 using 8255 ports. Use port A of 8255 for transferring digital data output of ADC to the CPU and port C for control signals. Assume that an analog input is present at I/P2 of the ADC and a clock input of suitable frequency is available for ADC. Solution: The analog input I/P2 is used and therefore address pins A,B,C should be 0,1,0 respectively to select I/P2. The OE and ALE pins are already kept at +5V to select the ADC and enable the outputs. Port C upper acts as the input port to receive the EOC signal while port C lower acts as the output port to send SOC to the ADC. Port A acts as a 8-bit input data port to receive the digital data output from the ADC. The 8255 control word is written as follows: D7 D6 D5 D4 D3 D2 D1 D The required ALP is as follows: I/O interfacing MOV AL, 98h ;initialise 8255 as OUT CWR, AL ;discussed above. MOV AL, 02h ;Select I/P2 as analog OUT Port B, AL ;input. OUT Port C, AL ; pulse to the ADC MOV AL, 01h OUT Port C, AL MOV AL, 00h OUT Port C, AL WAIT: IN AL, Port C ;Check for EOC by RCR ; reading port C upper and JNC WAIT ;rotating through carry. IN AL, Port A ;If EOC, read digital equivalent ;in AL HLT ;Stop. I/O Structure of a Typical Microcomputer: There are three major types of data transfer between the microcomputer and art I/O device. They are, Programmed I/O: In programmed I/O the data transfer is accomplished through an I/O port and controlled by software. Interrupt driven I/O: In interrupt driven I/O, the I/O device will interrupt the processor, and initiate data transfer. Direct memory access (DMA): In DMA, the data transfer between memory and I/O can be performed by bypassing the microprocessor INTERFACING I/O AND PERIPHERAL DEVICES 1. For data transfer from input device to processor the following operations are performed. 172

173 The input device will load the data to the port. When the port receives a data, it sends message to the processor to read the data. The processor will read the data from the port. After a data have been read by the processor the input device will load the next data into the port. 2. For data transfer from processor to output device the following operations are performed. The processor will load the data to the port. The port will send a message to the output device to read the data. The output device will read the data from the port. After the data have been read by the output device the processor can load the next data to the port. The various INTEL 110 port devices are 8212, 8155/8156, 8255, 8355 and The 8212 is a 24 pin IC. It consists of eight number of D-type latches. It has 8-input lines DI1 to DI8 and 8-output lines DO1 to DO8 The 8212 can be used as an input or output device It has two selecting device DS1 (low) and DS : 8156: Fig Types of data transfer It has two numbers of 8-bit parallel I/O port (port-a and B) One number of 6-bit parallel I/O port (port-c). It has 14 bit timer (operating in 4 modes). It has six internal addresses. It has one chip select pin CS (low). It has two numbers of 8-bit parallel I/O port (port-a and B) One number of 6-bit parallel 1 ports (port-c). It has 14 bit timer (operating in 4 modes). 173

174 It has six internal addresses. It has one chip select pin CS (low). Fig - Internal address of : It has 3 numbers of 8-bit parallel I/O ports (port A, B and C). Port-A can be programmed in mode-0 mode-1 or mode-2 as input or output port. Port-B can be programmed in mode-1 and mode-2 as 1/Oport. When ports A and B are in mode-0, the port-c can be used as I/O port. One logic low chip select (CS) pin. It requires four internal addresses 8355: It has 2KB ROM. It has two number of 8 bit port (A, B). It has one CS (low). It has four internal addresses. 8755: It has 2Kb EPROM. It has two number of 8 bit port (A, B). It has one CS (low). It has four internal addresses. Fig - Internal address of

175 Fig - Internal address of 8355 Fig - Internal address of 8755 There are two types for interfacing I/O devices: 1. Memory mapped I/O device. 175

176 2. Standard I/O mapped I/O device or isolated I/O mapping Solved Examples I/O interfacing Example 1 SAME FOR 8086 REPLACE THE BLOCK 8085 WITH 8086) A system requires 16kb EPROM and 16kb RAM. Also the system has 2 numbers of 8255, one number of 8279, one number of 8251 and one number of ( Programmable peripheral interface; Keyboard/display controller, USART and Timer). Draw the Interface diagram. Allocate addresses to all the devices. The peripheral IC should be I/O mapped. The I/O devices in the system should be mapped by standard I/O mapping. Hence separate decoders can be used to generate chip select signals for memory IC and peripheral IC's. For 16kb EPROM, we can provide 2 numbers of 2764(8k x 8) EPROM. For 16kb RAM we can provide 2 numbers of 6264 (8k x 8) RAM. The 8kb memories require 13 address lines. Hence the address lines A0 - A12 are used for selecting the memory locations. The unused address lines A13, A14 and A15 are used as input to decoder 74LS138 (3-to-8-deeoder) of memory IC. The logic low enables of this decoder are tied to IO/ M (low) of 8085, so that this decoder is enabled for memory read/write operation. The other enable pins of decoder are tied to appropriate logic levels permanently. The 4-outputs of the decoder are used to select memory lcs and the remaining 4 are kept for future expansion. The EPROM is mapped in the beginning of memory space from 0000H to 3FFF. The RAM is mapped at the end of memory space from C000 to FFFFH. There are five peripheral IC's to be interfaced to the system. The chip-select signals for these IC's are given through another 3-to-8 decoder 74LS138 (I/O decoder). The input to this decoder is A11, A12 and A13 The address lines A13, A14 and A15 are logically ORed and applied to low enable of I/O decoder. The logic high enable of I/O decoder is tied to IO / M (low) signal of 8085, so that this decoder is enabled for I/O read/write operation. 176

177 Fig - Internal address of 8255 Fig - Memory and I/O Port Interfacing with

178 Example 2: The 16 bit address for the memory and 8255 devices are, A system requires 16kb EPROM and 16kb RAM. Also the system has 2 numbers of 8255, one number of 8279, one number of 8251 and one number of ( Programmable peripheral interface; 8279-Keyboard/display controller, USART and Timer). Draw the Interface diagram. Allocate addresses to all the devices. The peripheral IC should be I/O mapped. The I/O devices in the system should be mapped by standard I/O mapping. Hence separate decoders can be used to generate chip select signals for memory IC and peripheral IC's. For 16kb EPROM, we can provide 2 numbers of 2764(8k x 8) EPROM. For 16kb RAM we can provide 2 numbers of 6264 (8k x 8) RAM. The 8kb memories require 13 address lines. Hence the address lines A0 - A12 are used for selecting the memory locations. The unused address lines A13, A14 and A15 are used as input to decoder 74LS138 (3-to-8-deeoder) of memory IC. The logic low enables of this decoder are tied to IO/ M (low) of 8085, so that this decoder is enabled for memory read/write operation. The other enable pins of decoder are tied to appropriate logic levels permanently. The 4-outputs of the decoder are used to select memory lcs and the remaining 4 are kept for future expansion. The EPROM is mapped in the beginning of memory space from 0000H to 3FFF. The RAM is mapped at the end of memory space from C000 to FFFFH. There are five peripheral IC's to be interfaced to the system. The chip-select signals for these IC's are given through another 3-to-8 decoder 74LS138 (I/O decoder). The input to this decoder is A11, A12 and A13 The address lines A13, A14 and A15 are logically ORed and applied to low enable of I/O decoder. The logic high enable of I/O decoder is tied to IO / M (low) signal of 8085, so that this decoder is enabled for I/O read/write operation. 178

179 179

180 Fig - Memory and I/O Port Interfacing with 8085 The 16 bit address for the memory and IO devices are, 180

181 Example 3: A system requires 8kb EPROM and 8kb RAM. Also the system has 2 numbers of Draw the Interface diagram. Allocate addresses to all the devices. The peripheral IC should be I/O mapped. The IC 2764 (8k x 8) is selected for EPROM memory and IC 6264 (8k x 8) is selected for RAM memory. Both the memory IC has time compatibility with 8085 processor. The 8kb memory requires 13 address lines. Hence the address lines A0 - A12 are used to select memory locations. The RAM locations of 8155 are selected by address lines A0 to A7. 3-to-8 decoder, 74LS138 is used for generating chip select signals by decoding the address lines A13, A14 and A15. Eight bit addresses are allotted to ports of 8l55 and sixteen bit addresses are allotted to RAM memory locations of The 16 bit address for the memory and IO devices are, 181

182 Examples of memory interfacing EXAMPLE 1 Fig - Memory and I/O Port Interfacing with 8085 Consider a system in which the full memory space 64kb is utilized for EPROM memory. Interface the EPROM with 8085 processor. The memory capacity is 64 Kbytes. i.e 2^n = 64 x 1000 bytes where n = address lines. So, n =

183 In this system the entire 16 address lines of the processor are connected to address input pins of memory IC in order to address the internal locations of memory. The chip select (CS) pin of EPROM is permanently tied to logic low (i.e., tied to ground). Since the processor is connected to EPROM, the active low RD pin is connected to active low output enable pin of EPROM. The range of address for EPROM is 0000H to FFFFH. EXAMPLE-2 Consider a system in which the available 64kb memory space is equally divided between EPROM and RAM. Interface the EPROM and RAM with 8085 processor. EXAMPLE-3 Implement 32kb memory capacity of EPROM using single IC kb RAM capacity is implemented using single IC The 32kb memory requires 15 address lines and so the address lines A0 - A14 of the processor are connected to 15 address pins of both EPROM and RAM. The unused address line A15 is used as to chip select. If A15 is 1, it select RAM and If A15 is 0, it select EPROM. Inverter is used for selecting the memory. The memory used is both Ram and EPROM, so the low RD and WR pins of processor are connected to low WE and OE pins of memory respectively. The address range of EPROM will be 0000H to 7FFFH and that of RAM will be 7FFFH to FFFFH. Consider a system in which 32kb memory space is implemented using four numbers of 8kb memory. Interface the EPROM and RAM with 8085 processor. The total memory capacity is 32Kb. So, let two number of 8kb n memory be EPROM and the remaining two numbers be RAM. Each 8kb memory requires 13 address lines and so the address lines A0- A12 of the processor are connected to 13 address pins of all the memory. The address lines and A13 - A14 can be decoded using a 2-to-4 decoder to generate four chip select signals. These four chip select signals can be used to select one of the four memory IC at any one time. 183

184 The address line A15 is used as enable for decoder. The simplified schematic memory organization is shown Memory Address Decoding The processor can usually address a memory space that is much larger than the memory space covered by an individual memory chip. In order to splice a memory device into the address space of the processor, decoding is necessary. For example, the 8088 issues 20-bit addresses for a total of 1MB of memory address space. However, the BIOS on a 2716 EPROM has only 2KB of memory and 11 address pins. A decoder can be used to decode the additional 9 address pins and allow the EPROM to be placed in any 2KB section of the 1MB address space. 184

185 To determine the address range that a device is mapped into: This 2KB memory segment maps into the reset location of the 8086/8088 (FFFF0H). NAND gate decoders are not often used. Rather the 3-to-8 Line Decoder (74LS138) is more common. 185

186 Note that all three Enables (G2A, G2B, and G1) must be active, e.g. low, low and high, respectively. Each output of the decoder can be attached to an 2764 EPROM ( 8K X 8 ) CRT INTERFACE Development of the CRT terminal as an alternative to the teletype was hampered by several technological and economic stumbling blocks. The generation of alphanumeric characters was a major problem requiring the use of complex discrete circuitry to actually draw the characters on the screen by deflecting the electron beam of the CRT. Another major problem was presented by the refresh memory requirements of the display. Early CRT terminals used acoustic delay lines configured as high-speed shift registers to store the bit patterns for each character to be displayed on the screen. A third obstacle in the development of an economical CRT terminal was the lack of acceptable keyboards. The mechanical keyboards used in teletypes and typewriters had many features which could not be economically duplicated in an all-electronic keyboard. Among these features were tactile feedback, protection from inadvertent multiple entry of keys, and rollover-i.e., the ability to enter several keys in succession without releasing the preceding keys and without, error. The reliability of mechanical keyboards 186

187 was also generally far beyond that of electronic keyboards. Among the byproducts of the development of LSI and memory technology that has led to today's microprocessors have been the long-sought solutions to most of the CRT terminal problems. The MOS read only memory eliminated them character generation problem. Today almost all CRT terminals use what is basically a TV set with a standard TV raster. Characters are generated as a dot matrix by the read only memory with the output applied directly to the TV set video amplifier. Refresh memories are of course now made up of standard MOS read/write memory devices. Keyboard companies have developed new technologies such as Hall effect and magnetic or capacitive coupled keys to achieve the required reliability for terminal operation. They have also made extensive use of read only memories and other LSI devices to produce keyboards with N key rollover and alternate key codes controlled by the use of shift keys. Smart Terminals The introduction of microprocessors has made possible the development of so-called "smart CRT terminals" at costs competitive with teletypes. The increased capabilities of the new CRT terminals to handle complex text editing functions, communications error detection and correction, and a variety of line protocols in both synchronous and asynchronous systems have led to the development of data communications systems for an enormous range of new applications.- CRT communications terminals fall into two categories: Teletype-compatible terminals and polled terminals. Teletype Compatible terminals are characterized by the Following: 1. Asynchronous transmission; 2. Transmission of single characters as they are entered from the keyboard; 3. use of 7-bit ASCII codes as defined for teletype operation including functions such as carriage return, line feed, bell, etc. Polled terminals are usually characterized by the following: 1. Synchronous transmission; 2. Transmission of blocks of characters rather than single characters; 3. Controlled transmission by a system of line protocol sin which a terminal never transmits except in response to a polling message; 4. Use of message formats in which status, identifier, and error check characters are attached to each message in precisely defied header and trailer data. In designing a microprocessor-based CRT 187

188 system the first task is to determine which parts of the system can best be handled by software and which will require special-purpose hardware. The two factors which must be considered in any such determination are cost and speed. The cost of special-purpose hardware must be weighed against the costs of the memory needed to store the program for an alternative software solution. The speed considerations are generally more crucial than cost questions because speed requirements may rule out software solutions absolutely. Thus the first task is to identify those functions, if any, which cannot be handled by software under any circumstances. Examples of such functions may be found in consideration of the requirements for a CRT display. The output of a CRT display interface consists of a vertical and horizontal sync pulse plus a video signal. (See Figure ) If the microprocessor were used to generate the sync signals this would dictate that all applications software must be partitioned into segments each requiring precisely one horizontal sync pulse time (63.5,sec) to execute. This is an intolerable and unnecessary burden to place on the software. The sync pulses can easily and cheaply be generated by simple MSI counting circuits. Figure Microprocessor generation of all CRT signals In the case of the generation of video signals the situation is even clearer. If the microprocessor were used to provide the video bit pattems (assuming at the very least a hardware shift register to convert from parallel bit patterns to serial video), it would have to output one bit pattern for each character time. (See Figure ) If one line is assumed to be 63.5,sec long and if 13.5,sec are reserved for sweep retrace time and margins, that leaves 50,sec to display a line of characters. If there are 80 alphanumeric characters to the line, that puts a requirement on the processor to output a bit pattern every 625 nsec. If it is assumed that each video bit pattern for the entire screen is stored in read/write memory (a ridiculous assumption which would require a 14K byte memory to display 2000 characters), 188

189 Figure Microprocessor generation of characters The microprocessor would have to execute the following sequence for each 625 nsec interval: 1. Fetch the bit pattern from memory. 2. Output the bit pattern to a video shift register. VERT SYNC HORIZ SYNC VIDEO 3. Increment a pointer to address the next bit pattern location. 4. Test the pointer to determine if the end of the screen had been reached. 5. Branch back to step 1 if the end of the screen has not been reached. To execute five instructions in 625 nsec requires an instruction execution time of 125 nsec. It is obvious that even with a bipolar microprocessor no time would be available to perform any other function, and with a MOS microprocessor the whole task is clearly an impossibility. Hardware generation of CRT signals with DMA. The next possibility to consider is the use of a direct memory access (DMA) channel to permit the CRT system to supply itself with data without imposing on the microprocessor. (See Figure ) Even with a ROM for a character generator and with hardwire address counters the CRT would require one memory access every 625 nsec. Even assuming the 189

190 use of very fast memories, not much time is left for the microprocessor to squeeze in its own memory access requirements. Figure Hardware generation of CRT signals with DMA PRINTER INTERFACE This simple unidirectional interface is used to drive printers. There are 8 data lines and two important data transfer control lines, STROBE* and BUSY. BUSY is an output from the printer that is high when the printer cannot accept data. STROBE* is a an output from the PC which is strobed (brought low and then high again) to transfer the data on the data lines to the printer. This interface uses TTL signal levels. To write a character to the printer the computer waits until busy is low, puts the character on data lines and brings STROBE* low and then high again. The minimum width of the strobe is half a microsecond and the data setup and hold times should also be at least half a microsecond. In addition, there is an ACK* strobe from the printer which goes low temporarily to acknowledge that the byte has been transferred. This strobe is often used to drive an interrupt but it s high/low state cannot be relied up to indicate the status of the printer. 190

191 There are additional handshaking lines to control various printer features (e.g. auto line feed) and to indicate various printer status conditions (e.g. out of paper). The original IBM PCs parallel port was an output only Centronics-compatible interfaces but in recent designs the port can also be configured as an input. The maximum speed usually depends on the software use but is typically 50 to 100 KB/s. 2 Software Details The PC printer interface is through a data register at offset 0 from the base I/O address, a status register at offset 1 and a control register at offset 2. Since the PC can have several printer interfaces installed, the actual base address of the main printer interface will depend on the configured hardware. When MS-DOS boots up it stores the (I/O) address of the first interface ( LPT1 ) in the word at memory location 0408H. Setting the bits 7 to 0 in the data register drive the data pins (9 to 2 respectively) on the interface connector. The bits in the status register are connected to the printer s status outputs and have the following meanings: The bits in the control register drive individual pins on the printer interface and have the following functions: 1 191

192 CHAPTER 5 INTEL 8051 MICROCONTROLLER ARCHITECTURE AND PROGRAMMING 192

193 INTEL 8051 MICROCONTROLLER ARCHITECTURE AND PROGRAMMING 5.4. Introduction Microcontroller manufacturers have been competing for a long time for attracting choosy customers and every couple of days a new chip with a higher operating frequency, more memory and upgraded A/D converters appeared on the market. However, most of them had the same or at least very similar architecture known in the world of microcontrollers as 8051 compatible. What is all this about? The whole story has its beginnings in the far 80s when Intel launched the first series of microcontrollers called the MCS 051. Even though these microcontrollers had quite modest features in comparison to the new ones, they conquered the world very soon and became a standard for what nowadays is called the microcontroller. The main reason for their great success and popularity is a skillfully chosen configuration which satisfies different needs of a large number of users allowing at the same time constant expansions (refers to the new types of microcontrollers). Besides, the software has been developed in great extend in the meantime, and it simply was not profitable to change anything in the microcontroller s basic core. This is the reason for having a great number of various microcontrollers which basically are solely upgraded versions of the 8051 family. What makes this microcontroller so special and universal so that almost all manufacturers all over the world manufacture it today under different name? 5.5. Programming model of 8051 The 8051 microcontroller actually includes a whole family of microcontrollers that have numbers ranging from 8031 to 8751 and are available in N-Channel Metal Oxide Silicon (NMOS) and Complementary Metal Oxide Silicon (CMOS) construction in a variety of package types. An enhanced version of the The 8052, also exists with its own family of variations and even includes one member that can be programmed in BASIC. An inspection of Appendix E shows that there are dozens of other variations on the core 8051 architecture.this galaxy of parts, the result of desires by the manufacturers to leave no market niche unfilled would require many topics to cover. In this topic, we will study a "generic" Housed in a 40-pin DIP and direct the investigation of a particular type to the data books. The block diagram of the 8051 in Figure l a shows all of the features unique to microcontrollers: Internal ROM and RAM I/O ports with programmable pins Timers and counters Serial data communication The figure also shows the usual CPU components: program counter, ALU, working registers, and clock circuits. 193

194 Fig architecture The 8051 architecture consists of these specific features: Eight-bit CPU with registers A (the accumulator) and B Sixteen-bit program counter (PC) and data pointer (DPTR) Eight-bit program status word (PSW) Eight-bit stack pointer (SP) Internal ROM or EPROM (8751) of 0 (8031) to 4K (8051) Internal RAM of 128 bytes: 194

195 Four register banks, each containing eight registers Sixteen bytes, which may be addressed at the bit level Eighty bytes of general-purpose data memory Thirty-two input/output pins arranged as four 8-bit ports: PO-P3 Two 16-bit timer/counters: TO and TI Full duplex serial data receiver/transmitter: SBUF Control registers: TCON, TMOD, SCON, PCON, IP, and IE Two external and three internal interrupt sources Oscillator and clock circuits. Knowledge of the details of circuit operation that cannot be affected by any instruction or external data. while intellectually stimulating. Tends to confuse the student new to the For this reason. this text will concentrate on the essential features of the R051: the more advanced student may wish to refer to manufacturers' data books for additional information. The programming model of the 8051 in Figure 1 b shows the 8051 as a collection of 8- and 16-bit registers and 8-bit memory locations. These registers and memory locations can be made to operate using the software instructions that are incorporated as part of the design. The program instructions have to do with the control of the registers and digital data paths that are physically contained inside the 8051, as well as memory locations that are physically located outside the The model is complicated by the number of special-purpose registers that must be present to make a microcomputer a microcontroller. A cursory inspection of the model is recommended for the first-time viewer; return to the model as needed while progressing through the 'remainder of the text. Most of the registers have a specific function; those that do occupy an individual block with a symbolic name, such as A or TH0 or PC. Others, which are generally indistinguishable from each other, are grouped in a larger block, such as internal ROM or RAM memory. Each register, with the exception of the program counter, has an internal l-byte address assigned to it. Some registers (marked with an asterisk * in Figure 1b) are both byte and bit addressable. That is, the entire byte of data at such register addresses may be read or altered, or individual bits may be read or altered. Software instructions are generally able to specify a register by its address, its symbolic name, or both Pin description A pinout of the 8051 packaged in a 40-pin DIP is shown in Figure 2 with the full and abbreviated names of the signals for each pin. It is important to note that many of the pins are used for more than one function (the alternate functions are shown in parentheses in Figure 2). Not all of the possible 8051 features may be used at the same time. 195

196 Fig.5.2 Programming model of 8051 As seen in figure above, the 8051 microcontroller has nothing impressive in appearance: 4 Kb of ROM is not much at all. 128Kb of RAM (including SFRs) satisfies the user's basic needs. 4 ports having in total of 32 input/output lines are in most cases sufficient to make all necessary connections to peripheral environment Pinout Description Pins 1-8: Port 1 Each of these pins can be configured as an input or an output. Pin 9: RS A logic one on this pin disables the microcontroller and clears the contents of most registers. In other words, the positive voltage on this pin resets the microcontroller. By applying logic zero to this pin, the program starts execution from the beginning. 196

197 Fig pin diagram Pins10-17: Port 3 Similar to port 1, each of these pins can serve as general input or output. Besides, all of them have alternative functions: Pin 10: RXD Serial asynchronous communication input or Serial synchronous communication output. Pin 11: TXD Serial asynchronous communication output or Serial synchronous communication clock output. Pin 12: INT0 Interrupt 0 input. Pin 13: INT1 Interrupt 1 input. Pin 14: T0 Counter 0 clock input. Pin 15: T1 Counter 1 clock input. Pin 16: WR Write to external (additional) RAM. Pin 17: RD Read from external RAM. Pin 18, 19: X2, X1 Internal oscillator input and output. A quartz crystal which specifies operating frequency is usually connected to these pins. Instead of it, miniature ceramics resonators can also be used for frequency stability. Later versions of microcontrollers operate at a frequency of 0 Hz up to over 50 Hz. Pin 20: GND Ground. 197

198 Pin 21-28: Port 2 If there is no intention to use external memory then these port pins are configured as general inputs/outputs. In case external memory is used, the higher address byte, i.e. addresses A8-A15 will appear on this port. Even though memory with capacity of 64Kb is not used, which means that not all eight port bits are used for its addressing, the rest of them are not available as inputs/outputs. Pin 29: PSEN If external ROM is used for storing program then a logic zero (0) appears on it every time the microcontroller reads a byte from memory. Pin 30: ALE Prior to reading from external memory, the microcontroller puts the lower address byte (A0- A7) on P0 and activates the ALE output. Pin 31: EA By applying logic zero to this pin, P2 and P3 are used for data and address transmission with no regard to whether there is internal memory or not. Pin 32-39: Port 0 Similar to P2, if external memory is not used, these pins can be used as general inputs/outputs. Otherwise, P0 is configured as address output (A0-A7) when the ALE pin is driven high (1) or as data output (Data Bus) when the ALE pin is driven low (0). Pin 40: VCC +5V power supply. Programming instructions or physical pin connections determine the use of any multifunction pins. For example, port 3 bit 0 (abbreviated P3.0) may be used as a general-purpose I/O pin, or as an input (RXD) to SBUF, the serial data receiver register. The system designer decides which of these two functions is to be used and designs the hardware and software affecting that pin accordingly The 8051 Oscillator and Clock The heart of the 8051 is the circuitry that generates the clock pulses by which all internal operations are synchronized. Pins XTALI and XTAL2 are provided for connecting a resonant network to form an oscillator. Typically, a quartz crystal and capacitors are employed, as shown in Figure 3. The crystal frequency is the basic internal clock frequency of the microcontroller. The manufacturers make available 8051 designs that can run at specified maximum and minimum frequencies, typically I megahertz to 16 megahertz. Minimum frequencies imply that some internal memories are dynamic and must always operate above a minimum frequency, or data will be lost. Serial data Communication needs often dictate the frequency of the oscillator due to the requirement that internal counters must divide the basic clock rate to yield standard communication bit per second (baud) rates. If the basic clock frequency is not divisible without a remainder. then the resulting communication frequency is not standard. Ceramic resonators may be used as a low-cost alternative to crystal resonators. However, decreases in frequency stability and accuracy make the ceramic resonator a poor choice if high-speed serial data communication with other systems, or critical timing, is to be done. The oscillator formed by the crystal, capacitors, and an on-chip inverter generates a pulse train at the frequency of the crystal, as shown in Figure. 198

199 Fig.5.4 Timing diagram The clock frequency, f. establishes the smallest interval of time within the microcontroller, called the pulse P, time. The smallest interval of time to accomplish any simple instruction, or part of a complex instruction, however, is the machine cycle. The machine cycle is itself made up of six states. A state is the basic time interval for discrete operations of the microcontroller such as fetching an opcode byte, decoding an opcode, executing an opcode, or writing a data byte. Two oscillator pulses define each state. Program instructions may require one, two, or four machine cycles to be executed. depending on the type of instruction. Instructions are fetched and executed by the microcontroller automatically, beginning with the instruction located at ROM memory address 0000h at the time the microcontroller is first reset Program Counter and Data Pointer The 8051 contains two 16-bit registers: the program counter (PC) and the data pointer (DPTR). Each is used to hold the address of a byte in memory. Program instruction bytes are fetched from locations in memory that are addressed by the PC. Program ROM may be on the chip at addresses 0000h to OFFFh, external to the chip for addresses that exceed 0FFFh, or totally external for all addresses from 0000h to FFFFh. The PC is automatically incremented after every instruction byte is fetched and may also be altered by certain instructions. The PC is the only register that does not have an internal address. The DPTR register is made up of two 8-bit registers. named DPH and DPL, that are used to furnish memory addresses for internal and external code access and external data access. The DPTR is under the control of program instructions and can be specified by its 16-bit name, DPTR, or by each individual byte name, DPH and DPL. DPTR does not have a single internal address; DPH and DPL are each assigned an address. 199

200 A and B CPU Registers The 8051 contains 34 general-purpose, or working. registers. Two of these, registers A and B, comprise the mathematical core of the 8051 central processing unit (CPU). The other 32 are arranged as part of internal RAM in four banks, B0-B3. of eight registers and comprise the mathematical core. The A (accumulator) register is the most versatile of the two CPU registers and is used for many operations. including addition, subtraction, integer multiplication and division, and Boolean bit manipulations. The A register is also used for all data transfers between the 8051 and any external memory. The B register is used with the A register for multiplication and division operations and has no other function other than as a location where data may be stored Flags and the Program Status Word (PSW) Flags are 1-bit registers provided to store the results of certain program instructions. Other instructions can test the condition of the flags and make decisions based upon the flag states. In order that the flags may be conveniently addressed, they are grouped inside the program status word (PSW) and the power control (PCON) registers. The 8051 has four math flags that respond automatically to the outcomes of math operations and three general-purpose user flags that can be set to I or cleared to 0 by the programmer as desired. The math flags include carry (C), auxiliary carry (AC), overflow (OY), and parity (P). User flags are named FO, GFO, and GFI; they are general-purpose flags that may be used by the programmer to record some event in the program. Note that all of the flags can be set and cleared by the programmer at will. The math Hags, however, are also affected by math operations. Fig.5.5 Flags The program status word is shown in Figure. The PSW contains the math flags, user program Hag FO, and the register select bits that identify which of the four general-purpose register banks is currently in 200

201 use by the program. The remaining two user flags, GFO and GFI, are stored in PCON, which is shown in Figure. Detailed descriptions of the math Hag operations will be discussed in topics that cover the opcodes that affect the flags. The user flags can be set or cleared using data move instructions will be covered Internal Memory A functioning computer must have memory for program code bytes, commonly in ROM, and RAM memory for variable data that can be altered as the program runs. The 8051 has internal RAM and ROM memory for these functions. Additional memory can be added externally using suitable circuits. Unlike microcontrollers with Von Neumann architectures, which can use a single memory address for either program code or data, but not for both, the 8051 has a Harvard architecture, which uses the same address, in different memories, for code and data. Internal circuitry accesses the correct memory based upon the nature of the operation in progress Internal RAM Fig.5.6 Internal Memory 201

202 The 128-byte internal RAM, which is shown generally in Figure 1 and in detail in Figure 5, is organized into three distinct areas: 1. Thirty-two bytes from address 00h to 1 Fh that make up 32 working registers organized as four banks of eight registers each. The four register banks are numbered 0 to 3 and are made up of eight registers named R0 to R 7. Each register can be addressed by name (when its bank is selected) or by its RAM address. Thus R0 of bank 3 is R0 (if bank 3 is currently selected) or address 18h (whether bank 3 is selected or not). Bits RS0 and RS 1 in the PSW determine which bank of registers is currently in use at any time when the program is running. Register banks not selected can be used as general-purpose RAM. Bank 0 is selected upon reset. 2. A bit-addressable area of 16 bytes occupies RAM byte addresses 20h to 2Fh, forming a total of 128 addressable bits. An addressable bit may be specified by its bit address of 00h to 7Fh, or 8 bits may form any byte address from 20h to 2Fh. Thus. for example, bit address 4Fh is also bit 7 of byte address 29h. Addressable bits are useful when the program need only remember a binary event (switch on, light off, etc.). Internal RAM is in short supply as it is, so why use a byte when a bit will do? 3. A general-purpose RAM area above the bit area, from 30h to 7Fh, addressable as bytes The Stack and the Stack Pointer The stack refers to an area of internal RAM that is used in conjunction with certain opcodes to store and retrieve data quickly. The 8-bit stack pointer (SP) register is used by the 8051 to hold an internal RAM address that is called the "top of the stack." The address held in the SP register is the location in internal RAM where the last byte of data was stored by a stack operation. When data is to be placed on the stack, the SP increments before storing data on the stack so that the stack grows up as data is stored. As data is retrieved from the stack, the byte is read from the stack, and then the SP decrements to point to the next available byte of stored data. Operation of the stack and the SP is shown in Figure 6. The SP is set to 07h when the 8051 is reset and can be changed to any internal RAM address by the programmer. Fig 5.7 The Stack Pointer 202

203 The stack is limited in height to the size of the internal RAM. The stack has the potential (if the programmer is not careful to limit its growth) to overwrite valuable data in the register banks, bitaddressable RAM, and scratch-pad RAM areas. The programmer is responsible for making sure the stack does not grow beyond pre-defined bounds! The stack is normally placed high in internal RAM, by an appropriate choice of the number placed in the SP register, to avoid conflict with the register, bit, and scratch-pad internal RAM areas Special Function Registers The 8051 operations that do not use the internal 128-byte RAM addresses from 00h to 7Fh are done by a group of specific internal registers. each called a special-function register (SFR). which may be addressed much like internal RAM. using addresses from 80h to FFh. Some SFRs (marked with an asterisk * in Figure 1b) are also bit addressable. as is the case for the bit area of RAM. This feature allows the programmer to change only what needs to be altered. leaving the remaining bits in that SFR unchanged. Not all of the addresses from 80h to FFh are used for SFRs. and attempting to use an address that is not defined. or "empty." results in unpredictable results. In Figure 2. I b, the SFR addresses are shown in the upper right corner of each block. The SFR names and equivalent internal RAM addresses are given in the following list: NAME FUNCTION INTERNAL RAM ADDRESS (HEX) A Accumulator OEO B Arithmetic 0F0 DPH Addressing external memory 83 DPL Addressing external memory 82 IE Interrupt enable control 0A8 IP Interrupt priority 0B8 PO Input/output port latch 80 Pl Input/output port latch 90 P2 Input/output port latch A0 P3 Input/output port latch 0B0 PC ON Power control 87 PSW Program status word 0D0 SCON Serial port control 98 SBUF Serial port data buffer 99 SP Stack pointer 81 TMOD Timer / counter mode control 89 TCON Timer / counter control 88 TLO Timer 0 low byte 8A THO Timer 0 low byte 8C TL1 Timer 0 low byte 8B TH1 Timer 1 high byte 8D Table 5.8 Special Function Registers 203

204 Note that the PC is not part of the SFR and has no internal RAM address. See also Appendix F SFRs are named in certain opcodes by their functional names, such as A or TH0, and are referenced by other opcodes by their addresses, such as 0E0h or 8Ch. Note that any address used in the program must start with a number; thus address E0h for the A SFR begins with 0. Failure to use this number convention will result in an assembler error when the program is assembled Internal ROM The 8051 is organized so that data memory and program code memory can be in two entirely different physical memory entities. Each has the same address ranges. The structure of the internal RAM has been discussed previously. A corresponding block of internal program code, contained in an internal ROM, occupies code address space 0000h to 0FFFh. The PC is ordinarily used to address program code bytes from addresses 0000h to FFFFh. Program addresses higher than 0FFFh, which exceed the internal ROM capacity, will cause the 8051 to automatically fetch code bytes from external program memory. Code bytes can also be fetched exclusively from an external memory, addresses 0000h to FFFFh, by connecting the external access pin (EA pin 31 on the DIP) to ground. The PC does not care where the code is; the circuit designer decides whether the code is found totally in internal ROM, totally in external ROM, or in a combination of internal and external ROM I/O ports All 8051 microcontrollers have 4 I/O ports each comprising 8 bits which can be configured as inputs or outputs. Accordingly, in total of 32 input/output pins enabling the microcontroller to be connected to peripheral devices are available for use. Input pin A logic one (1) is applied to a bit of the P register. The output FE transistor is turned off and the appropriate pin remains connected to the power supply voltage over a pull-up resistor of high resistance. Logic state (voltage) of any pin can be changed or read at any moment. A logic zero (0) and logic one (1) are not equal. A logic one (0) represents a short circuit to ground. Such a pin acts as an output. A logic one (1) is loosely connected to the power supply voltage over a resistor of high resistance. Since this voltage can be easily reduced by an external signal, such a pin acts as an input. Port 0 The P0 port is characterized by two functions. If external memory is used then the lower address byte (addresses A0-A7) is applied on it. Otherwise, all bits of this port are configured as inputs/outputs. The other function is expressed when it is configured as an output. Unlike other ports consisting of pins with built-in pull-up resistor connected by its end to 5 V power supply, pins of this port have this resistor left out. This apparently small difference has its consequences: 204

205 Fig. 5.9 port pin configuration If any pin of this port is configured as an input then it acts as if it floats. Such an input has unlimited input resistance and indetermined potential When the pin is configured as an output, it acts as an open drain. By applying logic 0 to a port bit, the appropriate pin will be connected to ground (0V). By applying logic 1, the external output will keep on 205

206 floating. In order to apply logic 1 (5V) on this output pin, it is necessary to built in an external pull-up resistor. Only in case P0 is used for addressing external memory, the microcontroller will provide internal power supply source in order to supply its pins with logic one. There is no need to add external pull-up resistors. Port 1 P1 is a true I/O port, because it doesn't have any alternative functions as is the case with P0, but can be configured as general I/O only. It has a pull-up resistor built-in and is completely compatible with TTL circuits. Port 2 P2 acts similarly to P0 when external memory is used. Pins of this port occupy addresses intended for external memory chip. This time it is about the higher address byte with addresses A8-A15. When no memory is added, this port can be used as a general input/output port showing features similar to P1. Port 3 All port pins can be used as general I/O, but they also have an alternative function. In order to use these alternative functions, a logic one (1) must be applied to appropriate bit of the P3 register. In terms of hardware, this port is similar to P0, with the difference that its pins have a pull-up resistor built-in. Pin's Current limitations PIN ALTERNATE USE SFR P3.0-RXD Serial data input SBUF P3.1- TXD Serial data output SBUF P3.2-INTO External interrupt 0 TCON.l P3.3-INT1 External interrupt 1 TCON.3 P3.4- TO External timer 0 input TMOD P3.5- T1 External timer 1 input TMOD P3.6-WR External memory write pulse - P3.7-RD External memory read pulse - Table 5.10 Special Function When configured as outputs (logic zero (0)), single port pins can receive a current of 10mA. If all 8 bits of a port are active, a total current must be limited to 15mA (port P0: 26mA). If all ports (32 bits) are active, total maximum current must be limited to 71mA. When these pins are configured as inputs (logic 1), built-in pull-up resistors provide very weak current, but strong enough to activate up to 4 TTL inputs of LS series. 206

207 As seen from description of some ports, even though all of them have more or less similar architecture, it is necessary to pay attention to which of them is to be used for what and how. For example, if they shall be used as outputs with high voltage level (5V), then P0 should be avoided because its pins do not have pull-up resistors, thus giving low logic level only. When using other ports, one should have in mind that pull-up resistors have a relatively high resistance, so that their pins can give a current of several hundreds microamperes only Timers A single machine-cycle instruction lasts for 12 quartz oscillator periods, which means that by embedding quartz with oscillator frequency of 12MHz, a number stored in the timer register will be changed million times per second, i.e. each microsecond. The 8051 microcontroller has 2 timers/counters called T0 and T1. As their names suggest, their main purpose is to measure time and count external events. Besides, they can be used for generating clock pulses to be used in serial communication, so called Baud Rate. Timer T0 As seen in figure below, the timer T0 consists of two registers TH0 and TL0 representing a low and a high byte of one 16-digit binary number. Accordingly, if the content of the timer T0 is equal to 0 (T0=0) then both registers it consists of will contain 0. If the timer contains for example number 1000 (decimal), then the TH0 register (high byte) will contain the number 3, while the TL0 register (low byte) will contain decimal number

208 Formula used to calculate values in these two registers is very simple: TH TL0 = T Matching the previous example it would be as follows: = 1000 Since the timer T0 is virtually 16-bit register, the largest value it can store is In case of exceeding this value, the timer will be automatically cleared and counting starts from 0. This condition is called an overflow. Two registers TMOD and TCON are closely connected to this timer and control its operation TMOD Register (Timer Mode) The TMOD register selects the operational mode of the timers T0 and T1. As seen in figure below, the low 4 bits (bit0 - bit3) refer to the timer 0, while the high 4 bits (bit4 - bit7) refer to the timer 1. There are 4 operational modes and each of them is described herein. Bits of this register have the following function: GATE1 enables and disables Timer 1 by means of a signal brought to the INT1 pin (P3.3): o 1 - Timer 1 operates only if the INT1 bit is set. o 0 - Timer 1 operates regardless of the logic state of the INT1 bit. C/T1 selects pulses to be counted up by the timer/counter 1: o 1 - Timer counts pulses brought to the T1 pin (P3.5). o 0 - Timer counts pulses from internal oscillator. T1M1, T1M0 These two bits select the operational mode of the Timer 1. T1M1 T1M0 Mode Description bit timer bit timer bit auto-reload Split mode 208

209 GATE0 enables and disables Timer 1 using a signal brought to the INT0 pin (P3.2): o 1 - Timer 0 operates only if the INT0 bit is set. o 0 - Timer 0 operates regardless of the logic state of the INT0 bit. C/T0 selects pulses to be counted up by the timer/counter 0: o 1 - Timer counts pulses brought to the T0 pin (P3.4). o 0 - Timer counts pulses from internal oscillator. T0M1, T0M0 These two bits select the operational mode of the Timer 0. T0M1 T0M0 Mode Description bit timer bit timer bit auto-reload Split mode 209

210 Timer 0 in mode 0 (13-bit timer) Timer 0 in mode 1 (16-bit timer) Mode 1 configures timer 0 as a 16-bit timer comprising all the bits of both registers TH0 and TL0. That's why this is one of the most commonly used modes. Timer operates in the same way as in mode 0, with difference that the registers count up to as allowable by the 16 bits. Timer 0 in mode 2 (Auto-Reload Timer) Mode 2 configures timer 0 as an 8-bit timer. Actually, timer 0 uses only one 8-bit register for counting and never counts from 0, but from an arbitrary value (0-255) stored in another (TH0) register. 210

211 Timer 0 in Mode 3 (Split Timer) Mode 3 configures timer 0 so that registers TL0 and TH0 operate as separate 8-bit timers. In other words, the 16-bit timer consisting of two registers TH0 and TL0 is split into two independent 8-bit timers. This mode is provided for applications requiring an additional 8-bit timer or counter. The TL0 timer turns into timer 0, while the TH0 timer turns into timer 1. In addition, all the control bits of 16-bit Timer 1 (consisting of the TH1 and TL1 register), now control the 8-bit Timer 1. Even though the 16-bit Timer 1 can still be configured to operate in any of modes (mode 1, 2 or 3), it is no longer possible to disable it as there is no control bit to do it. Thus, its operation is restricted when timer 0 is in mode

212 The only application of this mode is when two timers are used and the 16-bit Timer 1 the operation of which is out of control is used as a baud rate generator Timer Control (TCON) Register TCON register is also one of the registers whose bits are directly in control of timer operation. Only 4 bits of this register are used for this purpose, while rest of them is used for interrupt control to be discussed later. TF1 bit is automatically set on the Timer 1 overflow. TR1 bit enables the Timer 1. o 1 - Timer 1 is enabled. o 0 - Timer 1 is disabled. TF0 bit is automatically set on the Timer 0 overflow. TR0 bit enables the timer 0. o 1 - Timer 0 is enabled. o 0 - Timer 0 is disabled. 212

213 How to use the Timer 0? In order to use timer 0, it is first necessary to select it and configure the mode of its operation. Bits of the TMOD register are in control of it: Referring to figure above, the timer 0 operates in mode 1 and counts pulses generated by internal clock the frequency of which is equal to 1/12 the quartz frequency. Turn on the timer: The TR0 bit is set and the timer starts operation. If the quartz crystal with frequency of 12MHz is embedded then its contents will be incremented every microsecond. After microseconds, the both registers the timer consists of will be loaded. The microcontroller automatically clears them and the timer keeps on repeating procedure from the beginning until the TR0 bit value is logic zero (0). How to 'read' a timer? Depending on application, it is necessary either to read a number stored in the timer registers or to register the moment they have been cleared. - It is extremely simple to read a timer by using only one register configured in mode 2 or 3. It is sufficient to read its state at any moment. That's all! 213

214 - It is somehow complicated to read a timer configured to operate in mode 2. Suppose the lower byte is read first (TL0), then the higher byte (TH0). The result is: TH0 = 15 TL0 = 255 Everything seems to be ok, but the current state of the register at the moment of reading was: TH0 = 14 TL0 = 255 In case of negligence, such an error in counting (255 pulses) may occur for not so obvious but quite logical reason. The lower byte is correctly read (255), but at the moment the program counter was about to read the higher byte TH0, an overflow occurred and the contents of both registers have been changed (TH0: 14 15, TL0: 255 0). This problem has a simple solution. The higher byte should be read first, then the lower byte and once again the higher byte. If the number stored in the higher byte is different then this sequence should be repeated. It's about a short loop consisting of only 3 instructions in the program. There is another solution as well. It is sufficient to simply turn the timer off while reading is going on (the TR0 bit of the TCON register should be cleared), and turn it on again after reading is finished. Timer 0 Overflow Detection Usually, there is no need to constantly read timer registers. It is sufficient to register the moment they are cleared, i.e. when counting starts from 0. This condition is called an overflow. When it occurs, the TF0 bit of the TCON register will be automatically set. The state of this bit can be constantly checked from within the program or by enabling an interrupt which will stop the main program execution when this bit is set. Suppose it is necessary to provide a program delay of 0.05 seconds ( machine cycles), i.e. time when the program seems to be stopped: First a number to be written to the timer registers should be calculated: Then it should be written to the timer registers TH0 and TL0: 214

215 When enabled, the timer will resume counting from this number. The state of the TF0 bit, i.e. whether it is set, is checked from within the program. It happens at the moment of overflow, i.e. after exactly machine cycles or 0.05 seconds. How to measure pulse duration? How to count up pulses? Similarly to the previous example, the answer to this question again lies in the TCON register. This time it's about the C/T0 bit. If the bit is cleared the timer counts pulses generated by the internal oscillator, i.e. measures the time passed. If the bit is set, the timer input is provided with pulses from the P3.4 pin (T0). Since these pulses are not always of the same width, the timer cannot be used for time measurement and is turned into a counter, therefore. The highest frequency that could be measured by such a counter is 1/24 frequency of used quartz-crystal. Timer 1 Timer 1 is identical to timer 0, except for mode 3 which is a hold-count mode. It means that they have the same function, their operation is controlled by the same registers TMOD and TCON and both of them can operate in one out of 4 different modes. 215

216 5.6. UART (Universal Asynchronous Receiver and Transmitter) One of the microcontroller features making it so powerful is an integrated UART, better known as a serial port. It is a full-duplex port, thus being able to transmit and receive data simultaneously and at different baud rates. Without it, serial data send and receive would be an enormously complicated part of the program in which the pin state is constantly changed and checked at regular intervals. Serial port must be configured prior to being used. In other words, it is necessary to determine how many bits is contained in one serial word, baud rate and synchronization clock source. The whole process is in control of the bits of the SCON register (Serial Control). Serial Port Control (SCON) Register SM0 - Serial port mode bit 0 is used for serial port mode selection. SM1 - Serial port mode bit 1. SM2 - Serial port mode 2 bit, also known as multiprocessor communication enable bit. When set, it enables multiprocessor communication in mode 2 and 3, and eventually mode 1. It should be cleared in mode 0. REN - Reception Enable bit enables serial reception when set. When cleared, serial reception is disabled. TB8 - Transmitter bit 8. Since all registers are 8-bit wide, this bit solves the problem of transmitting the 9th bit in modes 2 and 3. It is set to transmit a logic 1 in the 9th bit. 216

217 RB8 - Receiver bit 8 or the 9th bit received in modes 2 and 3. Cleared by hardware if 9th bit received is a logic 0. Set by hardware if 9th bit received is a logic 1. TI - Transmit Interrupt flag is automatically set at the moment the last bit of one byte is sent. It's a signal to the processor that the line is available for a new byte transmite. It must be cleared from within the software. RI - Receive Interrupt flag is automatically set upon one byte receive. It signals that byte is received and should be read quickly prior to being replaced by a new data. This bit is also cleared from within the software. As seen, serial port mode is selected by combining the SM0 and SM2 bits: SM0 SM1 Mode Description Baud Rate bit Shift Register 1/12 the quartz frequency bit UART Determined by the timer bit UART 1/32 the quartz frequency (1/64 the quartz frequency) bit UART Determined by the timer 1 In mode 0, serial data are transmitted and received through the RXD pin, while the TXD pin output clocks. The bout rate is fixed at 1/12 the oscillator frequency. On transmit, the least significant bit (LSB bit) is sent/received first. TRANSMIT - Data transmit is initiated by writing data to the SBUF register. In fact, this process starts after any instruction being performed upon this register. When all 8 bits have been sent, the TI bit of the SCON register is automatically set. 217

218 RECEIVE - Data receive through the RXD pin starts upon the two following conditions are met: bit REN=1 and RI=0 (both of them are stored in the SCON register). When all 8 bits have been received, the RI bit of the SCON register is automatically set indicating that one byte receive is complete. Since there are no START and STOP bits or any other bit except data sent from the SBUF register in the pulse sequence, this mode is mainly used when the distance between devices is short, noise is minimized and operating speed is of importance. A typical example is I/O port expansion by adding a cheap IC (shift registers 74HC595, 74HC597 and similar). Mode 1 In mode 1, 10 bits are transmitted through the TXD pin or received through the RXD pin in the following manner: a START bit (always 0), 8 data bits (LSB first) and a STOP bit (always 1). The START 218

219 bit is only used to initiate data receive, while the STOP bit is automatically written to the RB8 bit of the SCON register. TRANSMIT - Data transmit is initiated by writing data to the SBUF register. End of data transmission is indicated by setting the TI bit of the SCON register. RECEIVE - The START bit (logic zero (0)) on the RXD pin initiates data receive. The following two conditions must be met: bit REN=1 and bit RI=0. Both of them are stored in the SCON register. The RI bit is automatically set upon data reception is complete. The Baud rate in this mode is determined by the timer 1 overflow. Mode 2 219

220 In mode 2, 11 bits are transmitted through the TXD pin or received through the RXD pin: a START bit (always 0), 8 data bits (LSB first), a programmable 9th data bit and a STOP bit (always 1). On transmit, the 9th data bit is actually the TB8 bit of the SCON register. This bit usually has a function of parity bit. On receive, the 9th data bit goes into the RB8 bit of the same register (SCON).The baud rate is either 1/32 or 1/64 the oscillator frequency. TRANSMIT - Data transmit is initiated by writing data to the SBUF register. End of data transmission is indicated by setting the TI bit of the SCON register. RECEIVE - The START bit (logic zero (0)) on the RXD pin initiates data receive. The following two conditions must be met: bit REN=1 and bit RI=0. Both of them are stored in the SCON register. The RI bit is automatically set upon data reception is complete. Mode 3 Mode 3 is the same as Mode 2 in all respects except the baud rate. The baud rate in Mode Baud Rate Baud Rate is a number of sent/received bits per second. In case the UART is used, baud rate depends on: selected mode, oscillator frequency and in some cases on the state of the SMOD bit of the SCON register. All the necessary formulas are specified in the table: Baud Rate Bit SMOD Mode 0 Fosc. / 12 Mode 1 1 Fosc (256-TH1) Mode 2 Fosc. / 32 Fosc. / 64 Bit SMOD 1 0 Mode 3 1 Fosc (256-TH1) 220

221 Timer 1 as a clock generator Timer 1 is usually used as a clock generator as it enables various baud rates to be easily set. The whole procedure is simple and is as follows: First, enable Timer 1 overflow interrupt. Configure Timer T1 to operate in auto-reload mode. Depending on needs, select one of the standard values from the table and write it to the TH1 register. That's all. Baud Rate Fosc. (MHz) Bit SMOD Multiprocessor Communication h 30 h 00 h A0 h 98 h 80 h 75 h 52 h D0 h CC h C0 h BB h A9 h E8 h E6 h E0 h DE h D5 h F4 h F3 h F0 h EF h EA h F3 h EF h EF h FA h F8 h F5 h FD h FC h F5 h FD h FC h FE h FF h 1 As you may know, additional 9th data bit is a part of message in mode 2 and 3. It can be used for checking data via parity bit. Another useful application of this bit is in communication between two or more microcontrollers, i.e. multiprocessor communication. This feature is enabled by setting the SM2 bit of the SCON register. As a result, after receiving the STOP bit, indicating end of the message, the serial port interrupt will be generated only if the bit RB8 = 1 (the 9th bit). This is how it looks like in practice: Suppose there are several microcontrollers sharing the same interface. Each of them has its own address. An address byte differs from a data byte because it has the 9th bit set (1), while this bit is cleared (0) in a data byte. When the microcontroller A (master) wants to transmit a block of data to one of several 221

222 slaves, it first sends out an address byte which identifies the target slave. An address byte will generate an interrupt in all slaves so that they can examine the received byte and check whether it matches their address. Of course, only one of them will match the address and immediately clear the SM2 bit of the SCON register and prepare to receive the data byte to come. Other slaves not being addressed leave their SM2 bit set ignoring the coming data bytes Operation Interrupts There are five interrupt sources for the 8051, Each interrupt can be enabled or disabled by setting bits of the IE register. Likewise, the whole interrupt system can be disabled by clearing the EA bit of the same register. Refer to figure below. Now, it is necessary to explain a few details referring to external interrupts- INT0 and INT1. If the IT0 and IT1 bits of the TCON register are set, an interrupt will be generated on high to low transition, i.e. on the falling pulse edge (only in that moment). If these bits are cleared, an interrupt will be continuously executed as far as the pins are held low. 222

223 IE Register (Interrupt Enable) EA - global interrupt enable/disable: o 0 - disables all interrupt requests. o 1 - enables all individual interrupt requests. ES - enables or disables serial interrupt: o 0 - UART system cannot generate an interrupt. o 1 - UART system enables an interrupt. ET1 - bit enables or disables Timer 1 interrupt: o 0 - Timer 1 cannot generate an interrupt. o 1 - Timer 1 enables an interrupt. EX1 - bit enables or disables external 1 interrupt: o 0 - change of the pin INT0 logic state cannot generate an interrupt. o 1 - enables an external interrupt on the pin INT0 state change. ET0 - bit enables or disables timer 0 interrupt: o 0 - Timer 0 cannot generate an interrupt. o 1 - enables timer 0 interrupt. EX0 - bit enables or disables external 0 interrupt: o 0 - change of the INT1 pin logic state cannot generate an interrupt. o 1 - enables an external interrupt on the pin INT1 state change. 223

224 Interrupt Priorities The priority list offers 3 levels of interrupt priority: 1. Reset! The absolute master. When a reset request arrives, everything is stopped and the microcontroller restarts. 2. Interrupt priority 1 can be disabled by Reset only. 3. Interrupt priority 0 can be disabled by both Reset and interrupt priority 1. The IP Register (Interrupt Priority Register) specifies which one of existing interrupt sources have higher and which one has lower priority. Interrupt priority is usually specified at the beginning of the program. According to that, there are several possibilities: If an interrupt of higher priority arrives while an interrupt is in progress, it will be immediately stopped and the higher priority interrupt will be executed first. If two interrupt requests, at different priority levels, arrive at the same time then the higher priority interrupt is serviced first. If the both interrupt requests, at the same priority level, occur one after another, the one which came later has to wait until routine being in progress ends. If two interrupt requests of equal priority arrive at the same time then the interrupt to be serviced is selected according to the following priority list: 1. External interrupt INT0 2. Timer 0 interrupt 3. External Interrupt INT1 4. Timer 1 interrupt 5. Serial Communication Interrupt IP Register (Interrupt Priority) The IP register bits specify the priority level of each interrupt (high or low priority). PS - Serial Port Interrupt priority bit o Priority 0 o Priority 1 PT1 - Timer 1 interrupt priority o Priority 0 o Priority 1 PX1 - External Interrupt INT1 priority o Priority 0 o Priority 1 PT0 - Timer 0 Interrupt Priority o Priority 0 224

225 o Priority 1 PX0 - External Interrupt INT0 Priority o Priority 0 o Priority Handling Interrupt When an interrupt request arrives the following occurs: 1. Instruction in progress is ended. 2. The address of the next instruction to execute is pushed on the stack. 3. Depending on which interrupt is requested, one of 5 vectors (addresses) is written to the program counter in accordance to the table below: Interrupt Source IE0 TF0 TF1 RI, TI Vector (address) 3 h B h 1B h 23 h All addresses are in hexadecimal format 4. These addresses store appropriate subroutines processing interrupts. Instead of them, there are usually jump instructions specifying locations on which these subroutines reside. 5. When an interrupt routine is executed, the address of the next instruction to execute is poped from the stack to the program counter and interrupted program resumes operation from where it left off. From the moment an interrupt is enabled, the microcontroller is on alert all the time. When an interrupt request arrives, the program execution is stopped, electronics recognizes the source and the program jumps to the appropriate address (see the table above). This address usually stores a jump instruction specifying the start of appropriate subroutine. Upon its execution, the program resumes operation from where it left off. Reset Reset occurs when the RS pin is supplied with a positive pulse in duration of at least 2 machine cycles (24 clock cycles of crystal oscillator). After that, the microcontroller generates an internal reset signal which clears all SFRs, except SBUF registers, Stack Pointer and ports (the state of the first two ports is not defined, while FF value is written to the ports configuring all their pins as inputs). Depending on surrounding and purpose of device, the RS pin is usually connected to a power-on reset push button or circuit or to both of them. Figure below illustrates one of the simplest circuit providing safe power-on reset. 225

226 Interrupt system of the 8051 microcontroller practically stops operation of the microcontroller and enables instructions to be executed one after another by pressing the button. Two interrupt features enable that: Interrupt request is ignored if an interrupt of the same priority level is in progress. Upon interrupt routine execution, a new interrupt is not executed until at least one instruction from the main program is executed. In order to use this in practice, the following steps should be done: 1. External interrupt sensitive to the signal level should be enabled (for example INT0). 2. Three following instructions should be inserted into the program (at the 03hex. address): What is going on? As soon as the P3.2 pin is cleared (for example, by pressing the button), the microcontroller will stop program execution and jump to the 03hex address will be executed. This address stores a short interrupt routine consisting of 3 instructions. The first instruction is executed until the push button is realised (logic one (1) on the P3.2 pin). The second instruction is executed until the push button is pressed again. Immediately after that, the RETI instruction is executed and the processor resumes operation of the main program. Upon execution of any program instruction, the interrupt INT0 is generated and the whole procedure is repeated (push button is still pressed). In other words, one button press - one instruction. 226

227 Microcontroller Power Consumption Control Actually, there are two power-saving modes of operation: Idle and Power Down. 227 Idle mode Upon the IDL bit of the PCON register is set, the microcontroller turns off the greatest power consumer- CPU unit while peripheral units such as serial port, timers and interrupt system continue operating normally consuming 6.5mA. In Idle mode, the state of all registers and I/O ports remains unchanged. In order to exit the Idle mode and make the microcontroller operate normally, it is necessary to enable and execute any interrupt or reset. It will cause the IDL bit to be automatically cleared and the program resumes operation from instruction having set the IDL bit. It is recommended that first three instructions to execute now are NOP instructions. They don't perform any operation but provide some time for the microcontroller to stabilize and prevents undesired changes on the I/O ports. Power Down mode By setting the PD bit of the PCON register from within the program, the microcontroller is set to Power down mode, thus turning off its internal oscillator and reduces power consumption enormously. The microcontroller can operate using only 2V power supply in power- down mode, while a total power consumption is less than 40uA. The only way to get the microcontroller back to normal mode is by reset. While the microcontroller is in Power Down mode, the state of all SFR registers and I/O ports remains unchanged. By setting it back into the normal mode, the contents of the SFR register is lost, but the content of internal RAM is saved. Reset signal must be long enough, approximately 10mS, to enable stable operation of the quartz oscillator.

228 PCON register The purpose of the Register PCON bits is: SMOD Baud rate is twice as much higher by setting this bit. GF1 General-purpose bit (available for use). GF1 General-purpose bit (available for use). GF0 General-purpose bit (available for use). PD By setting this bit the microcontroller enters the Power Down mode. IDL By setting this bit the microcontroller enters the Idle mode Instruction Set and Programming Addressing Modes The 8051 instructions use eight addressing modes. These are: 1. Register 2. Direct 3. Indirect 4. Immediate 5. Relative 6. Absolute 7. Long 8. Indexed 1. Register Addressing In this mode the data, which the instruction operates on, is in one of eight registers labeled R0 to R7 (Rn, in general). These registers are to be found in one of four register banks, only one of which can be active at any one time. The active bank may be selected by using bit 3 and bit 4 of the PSW (rs0 & rs1). On power-up or reset, the default register bank is bank 0. The format of an instruction using register addressing: For example, to logically OR the contents of accumulator A with that of register R3, the following instruction is used: ORL A, R3 and the op-code is B. The upper five bits, 01001, indicate the instruction, and the lower three bits, 011, the register. 2. Direct Addressing Instructions using direct addressing consists of two bytes: op-code and address. Such instructions can access any on-chip variable or hardware register. Note that the most significant bit of the direct address determines which area in the on-chip is to be accessed. An address between 00H and 7FH accesses a location in the low-order on-chip RAM. Any address with bit 7 = 1 refers to one of the special function 228

229 registers. It is not necessary to remember the addresses of these special function registers. The assembler usually understands and converts the mnemonic of a special function register, e.g. P2 for Port 2, into the appropriate address. An example of a direct addressing instruction is MOV P1, A which transfer the content of the accumulator to Port 1. The direct address of Port 1 (90H) is determined by the assembler and inserted as byte 2 of the instruction. The source of the data, the accumulator, is specified implicitly in the op-code. The complete encoding of this instruction is 3. Indirect Addressing In this mode of addressing the instruction performs an operation on the data whose address is contained in register R0 or R1. Instructions using indirect addressing are single byte instructions. In 8051 assembly language the before R0 or R1 denotes indirect addressing. An example of an indirect addressing instruction is SUBB This in (C) ((R0)). 4. Immediate Addressing In an instruction that uses immediate addressing, the operand of the instruction is given as the byte that follows the op-code. The operand may be a numeric constant, a symbolic variable, or an arithmetic expression using constants, symbols, and operators. In assembly language we use the symbol # before an operand to denote immediate addressing. An example of an instruction using immediate addressing is ANL A, #77 5. Relative Addressing Sometimes this is also called program counter relative addressing. This addressing mode is used only with certain jump instructions. A relative address (or offset) is an 8-bit signed value, which is added to the program counter to form the address of the next instruction executed. The range for such a jump instruction is 128 to +127 locations. Although the range is rather limited, relative addressing does offers the advantage of providing position-independent code (since absolute addresses are not used). For example, the instruction JZ rel performs the following operations: (PC) = IF (A) = 0 THEN (PC) =(PC) + rel ELSE continue The branch destination is computed by adding the signed relative-displacement in the second instruction byte to the PC, after incrementing the PC twice. 6. Absolute Addressing There are only two instructions that use this addressing: ACALL (absolute call) and AJMP (absolute jump). These instructions perform branching within the current 2K page of program memory. The branch address is obtained by successively concatenating the five high-order bits of the program counter, bits 5 7 of the op-code, and the second byte of the instruction. The diagrams illustrate how this is done: 229

230 Note that the branch destination address is within the same 2K page of program memory because the highest most five address bits are the same as those in the program counter before the branch is taken. 7. Long Addressing Only two instructions use this addressing mode. These instructions are LCALL addr16 and LJMP addr16. Both of these are three byte instructions with the op-code being the first byte and the following two bytes are the address high-byte and address low-byte respectively. These instructions enable the program to branch to anywhere within the full 64 K-bytes of program memory address space. 8. Indexed Addressing In this mode the 16-bit address in a base register is added to a positive offset to form an effective address for the jump indirect instruction and the two move code byte instructions MOVC A,@A+DPTR and MOVC A,@A+PC. The base register in the jump instruction is the data pointer and the positive offset is held in the accumulator. For the move instructions the base register can either be the data pointer or the program counter, and again the positive offset is in the accumulator. The operations of these three instructions are as follows: MOVC A,@A+DPTR (A) =((A) + (DPTR)) (A) =((A) + (PC)) Instruction set The 8051 instructions are divided among five functional groups: 1. Arithmetic 2. Logical 3. Data transfer 4. Boolean variable 5. Program branching 1. Arithmetic Instructions With the arithmetic instructions four addressing modes may be used. These modes are direct, indirect, register and immediate. For instance the add-with-carry instruction ADDC A, operand2 has the following four forms: 230

231 Most of the arithmetic instructions execute in twelve oscillator clock periods with the following three exceptions: 2. Logical Instructions The logical instructions can perform Boolean operations on the data contained either in the accumulator or in an internal RAM location. Those logical instructions that use the accumulator as one of the operands have the same addressing modes as those found in arithmetic instruction. Examples of such instructions are: Note that in addition to the ORL A, direct instruction we also have the equivalent mirror instruction ORL direct, A (OR the accumulator to the direct byte). All such instructions execute in twelve oscillator clock periods. Apart from the logical instructions that use the accumulator as one of the operands, there are three logical instructions that perform Boolean operations directly on any byte in the internal data memory without going through the accumulator. The table below gives a summary of these instructions. These three instructions take 24-oscillator clock period to execute. Note that these instructions perform what is known as read-modify-write operation. In a read-modify-write instruction the datum in the direct address location is first read, then the logical operation is performed on the read datum with the immediate byte, and finally the result of the logical operation is written back to the direct address location. The logical group of instructions also contains four rotate instructions, which operate on the contents of the 231

232 accumulator, and a swap instruction (SWAP A). The swap instruction is useful in BCD arithmetic manipulations. 3. Data Transfer Instructions This group contains the largest number of instructions that enable us to move data within the internal RAM, move data between the internal RAM and external RAM, and three instructions that allow us to manipulate look-up tables. The following table contains some examples of data transfer instructions. Note that the stack in the 8051 is implemented in the on-chip RAM. Unlike the stack implementations in other microprocessors the stack grows upwards in memory, i.e. towards higher memory addresses. The execution of the PUSH instruction first increments the stack pointer, and then copies the indicated byte into the stack. 4. Boolean instruction The 8051 has a range of Boolean variable manipulating instructions which enable us to set or reset individual bits within some of the locations in the internal RAM, and some of the special function registers. We give some examples of these instructions in the table below. 5. Control Flow Instruction This group contains conditional and unconditional branch instructions. Some of the conditional branch instructions which test individual bits such as JC rel (jump if Carry is set) are found in the previous instruction group. The following is a list of some of the program branch instructions. 232

233 5.10. Programming Timer/Counter In the following program, we create a square wave of 50% duty cycle (with equal portions high and low) on the P1.5 bit. Timer 0 is used to generate the time delay. Analyze the program In the above program notice the following step. 1. TMOD is loaded. 2. FFF2H is loaded into TH0-TL0. 3. P1.5 is toggled for the high and low portions of the pulse. The following program generates a square wave on P1.5 continuously using timer 1 for a time delay. Find the frequency of the square wave if XTAL = MHz. In your calculation do not include the overhead due to Instructions in the loop. 233

234 Solution: Since FFFFH 7634H = 89CBH + 1 = 89CCH and 89CCH = clock count and us = ms for half of the square wave. The frequency = Hz. Also notice that the high portion and low portion of the square wave pulse are equal. In the above calculation, the overhead due to all the instruction in the loop is not included. Assume XTAL = MHz, write a program to generate a square wave of 50 khz frequency on pin P2.3. Solution: Look at the following steps. (a) T = 1 / 50 = 20 ms, the period of square wave. (b) 1 / 2 of it for the high and low portion of the pulse is 10 ms. (c) 10 ms / us = 9216 and = in decimal, and in hex it is DC00H. (d) TL = 00 and TH = DC (hex). Examine the following program and find the time delay in seconds. Exclude the overhead due to the instructions in the loop. Solution: TH-TL = 0108H = 264 in decimal and = Now μs = ms, and for 200 of them we have ms = seconds. 234

235 Assume XTAL = MHz, find the frequency of the square wave generated on pin P1.0 in the following program Solution: First notice the target address of SJMP. In mode 2 we do not need to reload TH since it is auto-reload. Now (256-05) us = us = us is the high portion of the pulse. Since it is a 50% duty cycle square wave, the period T is twice that; as a result T = us = us and the frequency = khz. Find the frequency of a square wave generated on pin P1.0. T = 2 ( us ) = ms, and frequency = 72 Hz Serial Communication 1. With XTAL = MHz, find the TH1 value needed to have the following baud rates. (a) 9600 (b) 2400 (c) 1200 Solution: The machine cycle frequency of 8051 = / 12 = khz, and khz / 32 = 28,800 Hz is frequency by UART to timer 1 to set baud rate. (a) 28,800 / 3 = 9600 where -3 = FD (hex) is loaded into TH1 235

236 (b) 28,800 / 12 = 2400 where -12 = F4 (hex) is loaded into TH1 (c) 28,800 / 24 = 1200 where -24 = E8 (hex) is loaded into TH1 Notice that dividing 1/12 of the crystal frequency by 32 is the default value upon activation of the 8051 RESET pin. NOTE FOR REFERENCE 2. Write a program for the 8051 to transfer letter A serially at 4800 baud, continuously. 3.Write a program for the 8051 to receive bytes of data serially, and put them in P1, set the baud rate at 4800, 8-bit data, and 1 stop bit 236

237 4. Write a program for the 8051 to transfer YES serially at 9600 baud, 8-bit data, 1 stop bit, do this continuously 5.Assume that XTAL = MHz for the following program, state (a) what this program does, (b) compute the frequency used by timer 1 to set the baud rate, and (c) find the baud rate of the data transfer. Solution: (a) This program transfers ASCII letter B ( binary) continuously (b) With XTAL = MHz and SMOD = 1 in the above program, we have: / 12 = khz machine cycle frequency / 16 = 57,600 Hz frequency used by timer 1 to set the baud rate / 3 = 19,200, the baud rate. 237

238 Interrupts Programming An interrupt is an external or internal event that interrupts the microcontroller to inform it that a device needs its service A single microcontroller can serve several devices by two ways Interrupts Whenever any device needs its service, the device notifies the microcontroller by sending it an interrupt signal Upon receiving an interrupt signal, the microcontroller interrupts whatever it is doing and serves the device The program which is associated with the interrupt is called the interrupt service routine (ISR) or interrupt handler Polling The microcontroller continuously monitors the status of a given device When the conditions met, it performs the service After that, it moves on to monitor the next device until everyone is serviced Polling can monitor the status of several devices and serve each of them as certain conditions are met The polling method is not efficient, since it wastes much of the microcontroller s time by polling devices that do not need service ex. JNB TF,target The advantage of interrupts is that the microcontroller can serve many devices (not all at the same time) Each devices can get the attention of the microcontroller based on the assigned priority For the polling method, it is not possible to assign priority since it checks all devices in a roundrobin fashion The microcontroller can also ignore (mask) a device request for service This is not possible for the polling method For every interrupt, there must be an interrupt service routine (ISR), or interrupt handler When an interrupt is invoked, the microcontroller runs the interrupt service routine For every interrupt, there is a fixed location in memory that holds the address of its ISR The group of memory locations set aside to hold the addresses of ISRs is called interrupt vector table 238

239 Upon activation of an interrupt, the microcontroller goes through the following steps 1. It finishes the instruction it is executing and saves the address of the next instruction (PC) on the stack 2. It also saves the current status of all the interrupts internally (i.e.: not on the stack) 3. It jumps to a fixed location in memory, called the interrupt vector table, that holds the address of the ISR 4. The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it 5. It starts to execute the interrupt service subroutine until it reaches the last instruction of the subroutine which is RETI (return from interrupt) 6. Upon executing the RETI instruction, the microcontroller returns to the place where it was interrupted 7. First, it gets the program counter (PC) address from the stack by popping the top two bytes of the stack into the PC 8. Then it starts to execute from that address Six interrupts are allocated as follows 1. Reset power-up reset 2. Two interrupts are set aside for the timers: one for timer 0 and one for timer 1 3. Two interrupts are set aside for hardware external interrupts 4. P3.2 and P3.3 are for the external hardware interrupts INT0 (or EX1), and INT1 (or EX2) 5. Serial communication has a single interrupt that belongs to both receive and transfer 239

240 Show the instructions to (a) enable the serial interrupt, timer 0 interrupt, and external hardware interrupt 1 (EX1),and (b) disable (mask) the timer 0 interrupt, then (c) show how to disable all the interrupts with a single instruction. 1.Write a program to generate a square wave if 50Hz frequency on pin P1.2. This is similar to Example 9-12 except that it uses an interrupt for timer 0. Assume that XTAL= MHz 240

241 Assume that the INT1 pin is connected to a switch that is normally high. Whenever it goes low, it should turn on an LED. The LED is connected to P1.3 and is normally off. When it is turned on it should stay on for a fraction of a second. As long as the switch is pressed low, the LED should stay on. 241

242 I/O programming The following code will continuously send out to port 0 the alternating value 55H and AAH BACK: MOV A,#55H MOV P0,A ACALL DELAY MOV A,#0AAH MOV P0,A ACALL DELAY SJMP BACK Port 0 is configured first as an input port by writing 1s to it, and then data is received from that port and sent to P1 MOV A,#0FFH ;A=FF hex MOV P0,A ;make P0 an i/p port ;by writing it all 1s BACK: MOV A,P0 ;get data from P0 MOV P1,A ;send it to port 1 SJMP BACK ;keep doing it 242

243 Write the following programs. Create a square wave of 50% duty cycle on bit 0 of port 1. Solution: The 50% duty cycle means that the on and off state (or the high and low portion of the pulse) have the same length. Therefore, we toggle P1.0 with a time delay in between each state. Another way to write the above program is: Sometimes we need to access only 1 for 2 bits of the port Write a program to perform the following: (a) Keep monitoring the P1.2 bit until it becomes high 243

244 (b) When P1.2 becomes high, write value 45H to port 0 (c) Send a high-to-low (H-to-L) pulse to P2.3 The look-up table allows access to elements of a frequently used table with minimum operations Write a program to get the x value from P1 and send x2 to P2, continuously 244

245 While there are instructions such as JNC and JC to check the carry flag bit (CY), there are no such instructions for the overflow flag bit (OV). How would you write code to check OV? Assume that RAM locations 40 44H have the following values. Write a program to find the sum of the values. At the end of the program, register A should contain the low byte and R7 the high byte. 40 = (7D) 41 = (EB) 42 = (C5) 43 = (5B) 44 = (30) 245

246 Write a program to add two 16-bit numbers. Place the sum in R7 and R6; R6 should have the lower byte. (a) Write a program to get hex data in the range of 00 FFH from port 1 and convert it to decimal. Save it in R7, R6 and R5. (b) Assuming that P1 has a value of FDH for data, analyze program. (b) To convert a binary (hex) value to decimal, we divide it by 10 repeatedly until the quotient is less than 10. After each division the remainder is saves. Therefore, we have FDH=253. Write a program that finds the number of 1s in a given byte. 246

247 Write a program to transfer value 41H serially (one bit at a time) via pin P2.1. Put two highs at the start and end of the data. Send the byte LSB first. Write a program to bring in a byte of data serially one bit at a time via pin P2.7 and save it in register R2. The byte comes in with the LSB first. 247

248 CHAPTER 6 Case study SYSTEM DESIGN USING MICRO PROCESSOR & MICROCONTROLLER 248

249 6.1. Interfacing with DC Motor Introduction Whenever a robotics hobbyist talk about making a robot, the first thing comes to his mind is making the robot move on the ground. And there are always two options in front of the designer whether to use a DC motor or a stepper motor. When it comes to speed, weight, size, cost... DC motors are always preferred over stepper motors. There are many things which you can do with your DC motor when interfaced with a microcontroller. For example you can control the speed of motor, you can control the direction of rotation, you can also do encoding of the rotation made by DC motor i.e. keeping track of how many turns are made by your motors etc. So you can see DC motors are no less than a stepper motor. Usually H-bridge is preferred way of interfacing a DC motor. These days many IC manufacturers have H-bridge motor drivers available in the market like L293D is most used H-Bridge driver IC. H-bridge can also be made with the help of transistors and MOSFETs etc. rather of being cheap, they only increase the size of the design board, which is sometimes not required so using a small 16 pin IC is preferred for this purpose. Working Theory of H-Bridge The name "H-Bridge" is derived from the actual shape of the switching circuit which controls the motion of the motor. It is also known as "Full Bridge". Basically there are four switching elements in the H-Bridge as shown in the figure below. As you can see in the figure above there are four switching elements named as "High side left", "High side right", "Low side right", "Low side left". When these switches are turned on in pairs motor changes its direction accordingly. Like, if we switch on High side left and Low side right then motor rotate in forward direction, as current flows from Power supply through the motor coil goes to ground via switch low side right. This is shown in the figure below. 249

250 Similarly, when you switch on low side left and high side right, the current flows in opposite direction and motor rotates in backward direction. This is the basic working of H-Bridge. We can also make a small truth table according to the switching of H-Bridge explained above. Truth Table High Left High Right Low Left Low Right Description On Off Off On Motor runs clockwise Off On On Off Motor runs anti-clockwise On On Off Off Motor stops or decelerates Off Off On On Motor stops or decelerates As already said, H-bridge can be made with the help of transistors as well as MOSFETs, the only thing is the power handling capacity of the circuit. If motors are needed to run with high current then lot of dissipation is there. So head sinks are needed to cool the circuit. Now you might be thinking why i did not discuss the cases like High side left on and Low side left on or high side right on and low side right on. Clearly seen in the diagram, you don't want to burn your power supply by shorting them. So that is why those combinations are not discussed in the truth table. So we have seen that using simple switching elements we can make our own H-Bridge, or other option we have is using an IC based H-bridge driver. Both of them are discussed in the next section of the tutorial. BJT H-Bridge A simple H-bridge can be made with the help of Power BJTs like TIP31 and TIP32. An example and a working demo of this circuit is shown in the figure below. 250

251 L293D Dual H-Bridge Motor Driver L293D is a dual H-Bridge motor driver, So with one IC we can interface two DC motors which can be controlled in both clockwise and counter clockwise direction and if you have motor with fix direction of motion the you can make use of all the four I/Os to connect up to four DC motors. L293D has output current of 600mA and peak output current of 1.2A per channel. Moreover for protection of circuit from back EMF ouput diodes are included within the IC. The output supply (VCC2) has a wide range from 4.5V to 36V, which has made L293D a best choice for DC motor driver.a simple schematic for interfacing a DC motor using L293D is shown below. 251

252 As you can see in the circuit, three pins are needed for interfacing a DC motor (A, B, Enable). If you want the o/p to be enabled completely then you can connect Enable to VCC and only 2 pins needed from controller to make the motor work. As per the truth mentioned in the image above its fairly simple to program the microcontroller. It s also clear from the truth table of BJT circuit and L293D the programming will be same for both of them, just keeping in mind the allowed combinations of A and B. We will discuss about programming in C as well as assembly for running motor with the help of a microcontroller. Assembly programming CODE: L293D_A equ P2.0 L293D_B equ P2.1 L293D_E equ P2.2 org 0H Main: acall rotate_f acall delay acall break acall delay acall rotate_b acall delay acall break acall delay sjmp Main ;L293D A - Positive of Motor ;L293D B - Negative of Motor ;L293D E - Enable pin of IC ;Rotate motor forward ;Let the motor rotate ;Stop the motor ;Wait for some time ;Rotate motor backward ;Let the motor rotate ;Stop the motor ;Wait for some time ;Do this in loop rotate_f: setb L293D_A ;Make Positive of motor 1 clr L293D_B ;Make negative of motor 0 setb L293D_E ;Enable to run the motor ret ;Return from routine rotate_b: clr L293D_A ;Make positive of motor 0 setb L293D_B ;Make negative of motor 1 setb L293D_E ;Enable to run the motor ret ;Return from routine break: clr L293D_A ;Make Positive of motor 0 clr L293D_B ;Make negative of motor 0 clr L293D_E ;Disable the o/p ret ;Return from routine delay: ;Some Delay 252

253 mov r7,#20h back: mov r6,#ffh back1: mov r5,#ffh here: djnz r5, here djnz r6, back1 djnz r7, back ret C programming CODE: #include <AT89X51.H>#define L293D_A P2_0 #define L293D_B P2_1 //Negative of motor #define L293D_E P2_2 //Enable of L293D //Positive of motor // Function Prototypes void rotate_f(void); void rotate_b(void); void breaks(void); void delay(void); //Forward run funtion //Backward run function //Motor stop function //Some delay void main(){ //Our main function while(1){ //Infinite loop rotate_f(); //Run forward delay(); //Some delay breaks(); //Stop delay(); //Some delay rotate_b(); //Run Backwards delay(); //Some delay breaks(); //Stop delay(); //Some delay } //Do this infinitely } void rotate_f(){ L293D_A = 1; //Make positive of motor 1 L293D_B = 0; //Make negative of motor 0 L293D_E = 1; //Enable L293D } void rotate_b(){ L293D_A = 0; //Make positive of motor 0 L293D_B = 1; //Make negative of motor 1 L293D_E = 1; //Enable L293D } void breaks(){ L293D_A = 0; //Make positive of motor 0 L293D_B = 0; //Make negative of motor 0 L293D_E = 0; //Disable L293D } 253

254 void delay(){ //Some delay... unsigned char i,j,k; for(i=0;i<0x20;i++) for(j=0;j<255;j++) for(k=0;k<255;k++); } ORG 00H // initial starting address MAIN: MOV P1,# B // motor runs clockwise ACALL DELAY // calls the 1S DELAY MOV P1,# B // motor runs anti clockwise ACALL DELAY // calls the 1S DELAY SJMP MAIN // jumps to label MAIN for repaeting the cycle DELAY: MOV R4,#0FH WAIT1: MOV R3,#00H WAIT2: MOV R2,#00H WAIT3: DJNZ R2,WAIT3 DJNZ R3,WAIT2 DJNZ R4,WAIT1 RET END L293 Motor Driver L293 is a dedicated quadruple half H bridge motor driver IC available in 16 pin package. To know more about H bridge, check this link. H bridge motor driver circuit. L293 has a current capacity of 600mA/channel and has supply voltage range from 4.5 to 36V DC. They are fitted with internal high speed clamp diodes for inductive spike protection. Other good features of L293 are high noise immunity, internal ESD protection, thermal shutdown, separate input supply for each channel etc. The pin out and truth table of an L293 motor driver is shown in the figure below. 254

255 Bidirectional motor with pushbutton control The circuit shown below is of an 8051 based bi directional motor whose direction can be controlled using 2 push button switches. The circuit is very similar to the previous one except for the two push button switches. These pushbutton switches are interfaced to Port 3 of the microcontroller. Resistors R2 and R3 are the pull down resistors for P3.0 and 3.1 respectively. The code for the above project is so written that initially when power is switched ON, the motor remains OFF. When push button switch S2 is pressed P1.0 goes high and P1.1 remains low. The motor run in the clockwise direction and this condition is maintained until S3 is pressed. When push button switch S3 is pressed the logic of P1.0 and P1.1 toggles making the motor to run in the opposite direction and this condition is maintained until the next press of S2. Program ORG 00H // initiall starting address MOV P3,# B // initiates P3 as the pushbutton interface MOV P1,# B // clears P1 for keeping the motor OFF initially MAIN:MOV A,P3 // moves the current state of P3 to Accumulator CJNE A,# B,LABEL1 // checks whether S2 is pressed 255

256 MOV P1,# B // makes the motor run clockwise LABEL1:CJNE A,# B,LABEL2 // checks whether S3 is pressed MOV P1,# B // makes the motor to run anti clockwise LABEL2:SJMP MAIN // jumps back to the MAIN loop END About the program Checking whether a particular push button is pressed is done using the CJNE (compare and jump if not equal) instruction. In simple words the CJNE instruction compares two operands and jump to a predefined LABEL if the operands are not equal. If the two operands are equal nothing happens and the next instruction is executed. Whenever push button S2 is pressed the status of P3 will be B.This status is moved to accumulator A and compared with B using the CJNE instruction. Both operands are equal means S2 is pressed and the next instruction (MOV P1,# B) which makes the motor run clockwise is executed. If the operands are not equal that means the S2 is not pressed and the controller jumps to LABEL1 which is to check the S3. To check S3, status of P3 is moved to A again and it is compared with B using the CJNE instruction. Both operands are equal means the S3 is pressed and the next instruction (MOV P1,# B) which makes the motor run anti clockwise is executed. Both operands are not equal means S3 is not pressed and the controller goes to check S2 again and this cycle is repeated. Notes The maximum current capacity of L293 is 600mA/channel. So do not use a motor that consumes more than that. The supply voltage range of L293 is between 4.5 and 36V DC. So you can use a motor falling in that range DC motor direction control using L293d This is another tutorial for microcontroller interfacing series. This is all about how to interface/control a simple DC motor using microcontrollers. Controlling a DC motor is nothing but controlling the direction and speed of a motor. It is very necessary to go through motor controlling concept, if you are designing an autonomous robot. How does DC Motor work??? Lets start with how actually DC motor runs? Direction control of a DC motor is very simple, just reverse the polarity. Mean to say that every DC motor has two terminals out. When we apply DC voltage with proper current to a motor, it rotates in a particular direction but when we reverse the connection of voltage between two terminals, motor rotates in another direction. 256

257 Controlling using Micro Controllers!!! I think you are now familiar how to change the direction of DC motor. Now let us consider how to control motor using Microcontroller provided: 1. Microcontroller provides us only digital logic (1 or a 0). 2. We can t provide polarity from microcontroller Digital I/O. 3. We can t connect motors to Controller as mostly motors runs on voltage level more than +5V, and motors demands high current (depends). Now the solution to above limitations is, to use a H Bridge circuit.it is a special circuit which allows motor rotation in both directions. From four terminals of a H bridge you can control the direction of a DC motor. Using L293d Dual half H Bridge depending on current & power requirements, We can make our own H bridge using transistors/mosfets but it will be better to demonstrate the working, if we use some readymade IC such as L293d, its a dual half H bridge IC. we can drive a maximum of two DC motor and One stepper motor using one L293d. Decision Table will look like IN1 IN2 Motor1 0 1 Rotates in one direction 1 0 Rotates in other direction 257

258 Similar is true for another motor connected to Out3 and Out4 of L293d and can be controlled through IN3 and IN4. This is all about controlling direction of DC motor using L293d and /********************************************************************* Example program for DC motor control using L293d H bridge IC This program simply make both of 2 Dc motors to rotate some time in one direction and sometime in other. *********************************************************************/ #include<at89x52.h> void delay(void) { unsigned int i,j; for(i=0;i<200;i++) { for(j=0;j<1250;j++); } } void main(void) { P2=0x00; // initially both motors stopped while(1==1) { P2=0xA0; // both motors in one direction delay(); // Some delay delay(); delay(); P2=0x50; // Both motors in another direction delay(); delay(); 258

259 delay(); } } 6.2. Stepper Motor Introduction This section of tutorial will explain you everything that you need to know about stepper motors. Stepper motors can be used in various areas of your microcontroller projects such as making robots, robotic arm, automatic door lock system etc. This tutorial will explain you construction of stepper motors (unipolar and bipolar stepper motors ), basic pricipal, different controlling types (Half step and Full step), Interfacing Techniques (using L293D or ULN2003) and programming your microcontroller in C and assembly to control stepper motor. Unipolar stepper motor The unipolar stepper motor has five or six wires and four coils (actually two coils divided by center connections on each coil). The center connections of the coils are tied together and used as the power connection. They are called unipolar steppers because power always comes in on this one pole. Bipolar stepper motor The bipolar stepper motor usually has four wires coming out of it. Unlike unipolar steppers, bipolar steppers have no common center connection. They have two independent sets of coils instead. You can distinguish them from unipolar steppers by measuring the resistance between the wires. You should find two pairs of wires with equal resistance. If you've got the leads of your meter connected to two wires that are not connected (i.e. not attached to the same coil), you should see infinite resistance (or no continuity). As already said, we will talk mostly on "Unipolar stepper motors" which is most common type of stepper motor available in the market. A simple example of 6 lead step motor is given below and in 5 lead step motor wire 5 and 6 are joined together to make 1 wire as common. 259

260 Working of Stepper Motor Now let s discuss the operation principle of a stepper motor. When we energize a coil of stepper motor, The shaft of stepper motor (which is actually a permanent magnet) align itself according to poles of energized coil. So when motor coils are energized in a particular sequence, motor shaft tend to align itself according to pole of coils and hence rotates. A small example of energizing operation is given below. You can see in the example, when coil "A" is energized, a north-south polarity is generated at "A+A\" as shown in the figure above and magnetic shaft automatically align itself according to the poles generated. When the next coil is energized the shafts again align itself and take a step. Hence the working principle. We have seen that to make the stepper motor work, we need to energize coil in a sequence. The explanation and generation of the sequence is explained in the next section of the tutorial. Stepper motors can be driven in two different patterns or sequences. Namely, Full Step Sequence Half Step Sequence, we will go through these sequences one by one. Full Step Sequence 260

261 In the full step sequence, two coils are energized at the same time and motor shaft rotates. The order in which coils has to be energized is given in the table. Full Mode Sequence Step A B A\ B\ The working of the full mode sequence is given in the animated figure 261

262 262

263 Half Step Sequence In Half mode step sequence, motor step angle reduces to half the angle in full mode. So the angular resolution is also increased i.e. it becomes double the angular resolution in full mode. Also in half mode sequence the number of steps gets doubled as that of full mode. Half mode is usually preferred over full mode. Table below shows the pattern of energizing the coils. Half Mode Sequence Step A B A\ B\ The working of the half mode sequence is given in the animated figure below. 263

264 264

265 Step Angle Step angle of the stepper motor is defined as the angle traversed by the motor in one step. To calculate step angle, simply divide 360 by number of steps a motor takes to complete one revolution. As we have seen that in half mode, the number of steps taken by the motor to complete one revolution gets doubled, so step angle reduces to half. As in above examples, Stepper Motor rotating in full mode takes 4 steps to complete a revolution, So step angle can be calculated as... Step Angle ø = 360 / 4 = 90 and in case of half mode step angle gets half so 45. So this way we can calculate step angle for any stepper motor. Usually step angle is given in the spec sheet of the stepper motor you are using. Knowing stepper motor's step angle helps you calibrate the rotation of motor also to helps you move the motor to correct angular position. Step Sequence for 2-wire control of Unipolar stepper motor As seen in above explanation, in every step of the sequence, two wires are always set to opposite polarities. Because of this, it's possible to control steppers with only two wires instead of four, with a slightly more complex circuit. The stepping sequence is the same as it is for the two coils A and B, and the opposite polarity value is given to A\ and B\. The sequence is given in the table. 265

266 Step Sequence for Bipolar stepper motor 2-wire Mode Sequence Step A B Bipolar motor has simpler construction. It has two windings with no center taps and a permanent magnet at the center just like unipolar stepper motors. Being simpler in construction, the stepping sequence is a little complex, as the power for both the coils has to be controlled in such a way that the polarity of the poles get reversed. This polarity sequence is shown in the table below. Polarity Sequence Step A A\ B B\ 0 +ve -ve -ve -ve 1 -ve -ve +ve -ve 2 -ve +ve -ve -ve 3 -ve -ve -ve +ve The above polarity sequence can be interpreted in terms of logic levels for microcontroller by activating one coil at a time as shown in the table below. Step Sequence Step A A\ B B\ We have now learnt most of the necessary things regarding a stepper motor. In the next section we will discuss about the various techniques to interface a stepper motor Connecting Unipolar Stepper Motor There are actually many ways you can interface a stepper motor to your controller, out of them the most used interfaces are: 1. Interface using L293D - H-Bridge Motor Driver 2. Interface using ULN2003/ Darlington Arrays We will discuss both connection techniques one by one. The above mentioned methods need 4 controller pins for interface. Connecting Unipolar stepper using L293D 266

267 As you see in the circuit above the four pins "Controller pin 1",2,3 and 4 will control the motion and direction of the stepper motor according to the step sequence programmed in the controller. Connecting Unipolar stepper using ULN2003/2004 As already discussed in case of L293D, Here in this circuit too the four pins "Controller pin 1",2,3 and 4 will control the motion and direction of the stepper motor according to the step sequence sent by the controller. 2-wire connection for Unipolar Stepper Motor We have seen the generally used 4-wire connection method for interfacing unipolar stepper motor, but we can simplify the design to make controller use less pins with the help of 2-wire connection method. The circuit for 2-wire connection is shown below. 267

268 Connecting Bipolar Stepper Motor As we have studied that, Bi-polar stepper motors has 2 different coils. The step sequence for Bipolar stepper motor is same as that of unipolar stepper motors. The driving circuit for this require an H- Bridge as it allows the polarity of the power applied to be controlled independently. This can be done as shown in the figure below: Now we have seen the methods for connecting stepper motors with your microcontroller. So keeping these circuits in mind, we will now look at the programming of microcontroller to control stepper motors. This is discussed in the next section of the tutorial. Stepper motor is connected at Port 1.0 to Port 3. Adjusting the delay will increase or decrease the speed of the motor Programming 268

269 CODE: #include <REG2051.H>. #define stepper P1 void delay(); void main(){ while(1){ stepper = 0x0C; delay(); stepper = 0x06; delay(); stepper = 0x03; delay(); stepper = 0x09; delay(); } } void delay(){ unsigned char i,j,k; for(i=0;i<6;i++) for(j=0;j<255;j++) for(k=0;k<255;k++); } Assembly Programming CODE: org 0H stepper equ P1 main: mov stepper, #0CH acall delay mov stepper, #06H acall delay mov stepper, #03H acall delay mov stepper, #09H acall delay sjmp main delay: mov r7,#4 wait2: mov r6,#0ffh wait1: mov r5,#0ffh wait: djnz r5,wait 269

270 djnz r6,wait1 djnz r7,wait2 ret end The working of the above code can be seen in the demo animation below. C Programming for Half step Sequence Just the main routine changes rest everything remains same, i mean same delay routine. CODE: void main(){ while(1){ stepper = 0x08; delay(); stepper = 0x0C; delay(); stepper = 0x04; delay(); stepper = 0x06; delay(); stepper = 0x02; delay(); stepper = 0x03; delay(); stepper = 0x01; delay(); stepper = 0x09; delay(); } } 270

271 Assembly Programming Here also the main routine changes rest everything remains same. CODE: main: mov stepper, #08H acall delay mov stepper, #0CH acall delay mov stepper, #04H acall delay mov stepper, #06H acall delay mov stepper, #02H acall delay mov stepper, #03H acall delay mov stepper, #01H acall delay mov stepper, #09H acall delay sjmp main The working of the above code can be seen in the demo animation below. Programming for 2-wire connection of Unipolar Stepper Motor C Programming CODE: 271

272 void main(){ while(1){ stepper = 0x03; delay(); stepper = 0x01; delay(); stepper = 0x00; delay(); stepper = 0x02; delay(); } } Assembly Programming CODE: main: mov stepper, #03H acall delay mov stepper, #01H acall delay mov stepper, #00H acall delay mov stepper, #02H acall delay sjmp main The working of the above code can be seen in the demo animation below. Programming for Bipolar Stepper Motor 272

273 C Programming CODE: void main(){ while(1){ stepper = 0x08; delay(); stepper = 0x02; delay(); stepper = 0x04; delay(); stepper = 0x01; delay(); } } Assembly Programming CODE: main: mov stepper, #08H acall delay mov stepper, #02H acall delay mov stepper, #04H acall delay mov stepper, #01H acall delay sjmp main 6.3.PWM Introduction Pulse width Modulation or PWM is one of the powerful techniques used in control systems today. They are not only employed in wide range of control application which includes: speed control, power control, measurement and communication. This tutorial will take you through the PWM basics and implementation of PWM on 8051 and AVR microcontrollers. Basic Principal of PWM Pulse-width Modulation is achieved with the help of a square wave whose duty cycle is changed to get a varying voltage output as a result of average value of waveform. A mathematical explanation of this is given below. 273

274 Consider a square wave shown in the figure above. T on is the time for which the output is high and T off is time for which output is low. Let T total be time period of the wave such that, Duty cycle of a square wave is defined as The output voltage varies with duty cycle as... So you can see from the final equation the output voltage can be directly varied by varying the T on value. If T on is 0, V out is also 0. if T on is T total then V out is V in or say maximum. This was all about theory behind PWM. Now lets take a look at the practical implementation of PWM on microcontrollers Idea Behind Implementation The basic idea behind PWM implementation on 8051 is using timers and switching port pin high/low at defined intervals. As we have discussed in the introduction of PWM that by changing the T on time, we can vary the width of square wave keeping same time period of the square wave. 274

275 We will be using 8051 Timer0 in Mode 0. Values for high and low level will be loaded in such a way that total delay remains same. If for high level we load a value X in TH0 then for low level TH0 will be loaded with 255-X so that total remains as Assembly Code Example Timer setup for PWM CODE: PWMPIN EQU P1.0 ; PWM output pin PWM_SETUP: MOV TMOD,#00H ; Timer0 in Mode 0 MOV R7, #160 ; Set pulse width control ; The value loaded in R7 is value X as ; discussed above. SETB EA ; Enable Interrupts SETB ET0 ; Enable Timer 0 Interrupt SETB TR0 ; Start Timer RET Interrupt Service Routine CODE: TIMER_0_INTERRUPT: JB F0, HIGH_DONE ; If F0 flag is set then we just finished ; the high section of the LOW_DONE: ; cycle so Jump to HIGH_DONE SETB F0 ; Make F0=1 to indicate start of high section SETB PWMPIN ; Make PWM output pin High MOV TH0, R7 ; Load high byte of timer with R7 ; (pulse width control value) CLR TF0 RETI ; Clear the Timer 0 interrupt flag ; Return from Interrupt to where ; the program came from HIGH_DONE: CLR F0 ; Make F0=0 to indicate start of low section CLR PWMPIN ; Make PWM output pin low MOV A, #0FFH ; Move FFH (255) to A CLR C ; Clear C (the carry bit) so it does ; not affect the subtraction SUBB A, R7 ; Subtract R7 from A. A = R7. MOV TH0, A ; so the value loaded into TH0 + R7 = 255 CLR TF0 ; Clear the Timer 0 interrupt flag RETI ; Return from Interrupt to where ; the program came from In your main program you need to call this PWM_SETUP routine and your controller will have a PWM output. Timer Interrupt service routine will take care of PWM in the background. The width of PWM can be changed by changing the value of R7 register. In above example I am using 160, you can choose any value from 0 to 255. R7 = 0 will give you o/p 0V approx and R7 = 255 will give you 5V approx. 275

276 You can also make use of Timer1 if you want. And the output pin can be changed to whatever pin you want. C Code Example Timer setup for PWM in C CODE: //Global variables and definition #define PWMPIN P1_0 unsigned char pwm_width; bit pwm_flag = 0; void pwm_setup(){ TMOD = 0; pwm_width = 160; EA = 1; ET0 = 1; TR0 = 1; } Interrupt Service Routine CODE: void timer0() interrupt 1 { if(!pwm_flag) { //Start of High level pwm_flag = 1; //Set flag PWMPIN = 1; //Set PWM o/p pin TH0 = pwm_width; //Load timer TF0 = 0; //Clear interrupt flag return; //Return } else { //Start of Low level pwm_flag = 0; //Clear flag PWMPIN = 0; //Clear PWM o/p pin TH0 = pwm_width; //Load timer TF0 = 0; //Clear Interrupt flag return; //return } } 6.4. Traffic light This example explain how to design a microprocessor system to control traffic lights. The traffic light arrangement is as shown in Fig. The traffic should be controlled in the following manner. 1) Allow traffic from W to E and E to W transition for 20 seconds. 2) Give transition period of 5 seconds (Yellow bulbs ON) 3) Allow traffic from N to 5 and 5 to N for 20 seconds 4) Give transition period of 5 seconds (Yellow bulbs ON) 5) Repeat the process. 276

277 Fig. shows the interfacing diagram to control 12 electric bulbs. Port A is used to control lights on N-S road and Port B is used to control lights on W-E road. Actual pin connections are listed in Table 1 below. The electric bulbs are controlled by relays. The 8255 pins are used to control relay on-off action with the help of relay driver circuits. The driver circuit includes 12 transistors to drive 12 relays. Fig. also shows the interfacing of 8255 to the system. 277

278 SOFTWARE FOR TRAFFIC LIGHT CONTROL Source program: MVI A, 80H OUT 83H (CR) START: MVI A, 09H OUT 80H (PA) MVI A, 24H OUT 81H (PB) MVI C, 28H CALL DELAY MVI A, 12H OUT (81H) PA OUT (81H) PB MVI C, 0AH CALL: DELAY MVI A, 24H OUT (80H) PA MVI A, 09H OUT (81H) PB MVI C, 28H CALL DELAY MVI A, 12H OUT PA OUT PB MVI C, 0AH : Initialize 8255, port A and port B : in output mode : Send data on PA to glow R1 and R2 : Send data on PB to glow G3 and G4 : Load multiplier count (40ıο) for delay : Call delay subroutine : Send data on Port A to glow Y1 and Y2 : Send data on port B to glow Y3 and Y4 : Load multiplier count (10ıο) for delay : Call delay subroutine : Send data on port A to glow G1 and G2 : Send data on port B to glow R3 and R4 : Load multiplier count (40ıο) for delay : Call delay subroutine : Send data on port A to glow Y1 and Y2 : Send data on port B to glow Y3 and Y4 : Load multiplier count (10ıο) for delay 278

279 CALL DELAY JMP START : Call delay subroutine Delay Subroutine: DELAY: LXI D, Count : Load count to give 0.5 sec delay BACK: DCX D : Decrement counter MOV A, D ORA E : Check whether count is 0 JNZ BACK : If not zero, repeat DCR C : Check if multiplier zero, otherwise repeat JNZ DELAY RET : Return to main program Traffic Lights controller using 8051 microcontroller (Easy Assembly Program) Now a day microcontrollers find their application in almost every electronics applications ranging from remote based toy cars to mobile phones, aircraft, etc. The general layout of the traffic lights is shown in the diagram: 279

280 The green colour depicts green LED while red colour depicts red LED. The corresponding pins to which the LEDs are connected are also given beside the colour boxes. 0) The logic table for this project is shown below: (considering the LED will glow when pin output = Delay P0.0 P0.1 P0.2 P0.3 P0.4 P0.5 P0.6 P0.7 1 st nd rd th Program: org 0000h here: mov p0,#0d4h acall delay1 mov p0,#53h acall delay1 mov p0,#4dh acall delay1 mov p0,#35h acall delay1 sjmp here delay1: MOV R2,#42d MOV R1,#00d MOV R0,#00d loop: DJNZ R0,loop DJNZ R1,loop DJNZ R2,loop RET 6.5. Relay A relay is a solenoid that operates electrical contacts. When the relay is energized, the contacts are shorted or opened, just like a mechanical switch. For the sake of simplicity, this section will address relays, but the same considerations apply to solenoids. Figure 6.1A shows a relay as it might be connected to a microprocessor. A single bit is used to turn the relay on and off. The figure shows an NPN 280

281 transistor connected to a port bit on the processor; you could also use a MOSFET. Some microprocessors have outputs that are capable of sinking sufficient current to activate a relay, as long as the relay is operating from the same voltage as the processor. Because the relay or solenoid is activated by a coil, there is a fly back voltage that occurs when the drive transistor is turned off and the magnetic field collapses in the coil. This voltage can reach high enough levels to damage the drive transistor. Figure 6.1B shows how a diode can be used to clamp the voltage across the coil to safe levels. When the transistor turns on, activating the relay, the diode is reverse biased. When the transistor turns off, the top end of the coil is tied to the drive voltage, so a voltage spike appears at the lower end (transistor collector). As soon as this voltage reaches the supply voltage plus one diode drop (about 0.6V for a silicon diode), the diode conducts. There are two considerations when using a diode clamp on a relay. The first is that the energy in the coil doesn t just disappear. It has to go somewhere, and it gets dumped into the positive supply through the diode. This results in a current surge into the supply. For this reason, the supply needs to be well bypassed. If the relay is on a board that is some distance from the power supply, there may be a noise spike on the ground as well. The second problem with this technique is that it slows the release time down. Figure 6.2 shows a method that can be used to speed up the relay release by using a zener diode. When the transistor is turned on and the relay pulls in, the normal diode keeps current from flowing through the zener. When the transistor turns off and the flyback pulse occurs, the normal diode is forward biased and the zener is reverse biased. The result is that the transistor collector voltage is clamped at the zener voltage plus one diode drop above the positive supply. Of course, the resulting voltage has to be lower than the transistor breakdown voltage or damage will result. 281

282 Typical numbers for a generic 6V relay with no clamp, a diode clamp, and two zener clamps are as follows: Clamp Open time none 1 ms 12V zener 1.5 ms 6V zener 2.2 ms diode 5.5 ms. These numbers were obtained by switching off the relay coil and measuring the time until the contacts open. You can see that the higher the flyback voltage is allowed to rise, the faster the field dissipates and the faster the contacts open. Tranzorbs can also be used to clamp a relay or solenoid. A Tranzorb is a zener like device that is used for clamping high-energy transients. A Tranzorb clamps at the same voltage in both directions, so no blocking diode is needed. Pick/Hold The DC current drawn by a relay has to be high enough to pull the relay contact from one end of its travel to the other. However, the current needed to hold that position is much lower typically 50% of the pull-in (or pick) voltage. In many cases, a smaller power supply can be used if the current is reduced once the relay contacts are pulled in, especially if several relays are to be activated at once. In addition, using a lower hold current decreases the release time, because there is less energy stored in the coil when the relay is turned off. Relay Relays are devices which allow low power circuits to switch a relatively high Current/Voltage ON/OFF. A relay circuit is typically a smaller switch or device which drives (opens/closes) an electric switch that is capable of carrying much larger current amounts Interfacing Relays Fig. 1 shows how to interface the Relay to microcontroller. There are 2 input channels. Each input is connected to the triggering coil of the respective relay. There are 2 output channels that each correspond to an input. When the input is energized, the relay turns on and the '+' output is connected to +12v. When the relay is off, the '+' output is connected to Ground. The '-' output is permanently wired to Ground. 282

283 Interfacing Relay with 8051 Fig. 1 Interfacing Relay to Microcontroller In ADB Board two no. Of SPDT relays are used. Both the relays operate on 5V DC. The outputs of both the terminals of the relay are taken out on the connecter to connect the external circuitry. The relay can be connected to the Microcontroller through any of the selected port (P0.4 & P0.5) or (P1.4 & P1.5) or (P2.4 & P2.5) by using the FRC connector. Pin Assignment with 8051 RELAY SPDT 8051 Lines RELAY Power Select Relay-1 P0.4 RELAY Modules Relay-2 P0.5 A. Note : Relay selection connect 10pinFRC cable CN7 to JP8 (P ). 283

284 C Program to control Relay in 8051 #include <reg51.h> #include<stdio.h> sbit relay1 = P0^4; sbit relay2 = P0^5; void DelayMs(unsigned int); // // Main Program // void main (void) { P2 = 0; while(1) { relay1 = 1; relay2 = 0; DelayMs(200); relay1 = 0; relay2 = 1; DelayMs(200); } } // // Delay Function // void DelayMs(unsigned int n) { unsigned int i,j; for(j=0;j<n;j++) { Other Relay Circuits } //Define 8051 registers for(i=0;i<1000;i++); } //Delay function //Initialize Port //Loop Forever //Relay1 - ON //Relay2 - Off //Delay 20msec //Relay1 - Off //Relay2 - ON //Delay 20msec 284

285 Relays are devices which allow low power circuits to switch a relatively high Current/Voltage ON/OFF. For a relay to operate a suitable pull-in & holding current should be passed through its coil. Generally relay coils are designed to operate from a particular voltage often its 5V or 12V. The function of relay driver circuit is to provide the necessary current (typically 25 to 70ma) to energize the relay coil. Figure 1 shows the basic relay driver circuit. As you can see an NPN transistor BC547 is being used to control the relay. The transistor is driven into saturation (turned ON) when a LOGIC 1 is written on the PORT PIN thus turning ON the relay. The relay is turned OFF by writing LOGIC 0 on the port pin. A diode (1N4007/1N4148) is connected across the relay coil; this is done so as to protect the transistor from damage due to the BACK EMF generated in the relay's inductive coil when the transistor is turned OFF. When the transistor is switched OFF the energy stored in the inductor is dissipated through the diode & the internal resistance of the relay coil. Normally 1N4148 can be used as it is fast switching diode with a maximum forward current of 300ma. This diode is also called as free-wheeling diode. The LED is used to indicate that the RELAY has been turned ON. The resistor R1 defines the current flowing through the LED thereby defining the LED s intensity. Resistor R2 is used as a Series Base Resistor to set the base current. When working with 8051 controllers I have noted that it s not compulsory to use this resistor as the controller has internal 10k resistor which acts as a base resistor. Microcontrollers have internal pull up resistors hence when a port pin is HIGH the output current flows through this internal pull up resistor microcontrollers have an internal pull up of 10KΩ. Hence the maximum output current will be 5v/10k = 0.5ma. This current is not sufficient to drive the transistor into saturation and turn ON the relay. Hence an external pull up resistor R3 is used. Let us now calculate the value of R3. Normally a relay requires a pull in current of 70ma to be turned ON. So our BC547 transistor will require enough base current to make sure it remains saturated and provide the necessary collector current i.e. 70ma. The gain (h fe ) of BC547 is 100 so we need to provide at least 70ma/100 = 0.7ma of base current. In practice you require roughly double the value of this current so we will calculate for 1.4ma of base current. Base Current(1.4ma) =o/p current of controller (0.5ma) + 5v/R3 285

286 From the above equation the value of R3 comes out to be 5.55KΩ. Typically I use 4.7KΩ resistor. Whenever 8051 microcontroller is turned ON initially the controller is in reset state and all the controller pins are HIGH which would result in TURNING ON the relay every time power is turned ON or if there is a power fluctuation. This may also damage the device connected to relay so as to avoid this problem another transistor Q2 has been added between the controller & the previous transistor. This transistor acts as an inverter. Figure 2 shows the upated Relay Driver Circuit. So now when a High is applied from the controller the TRANSISTOR Q2 turns ON so the base of transistor Q1 gets 0 so the transistor Q1 turns OFF so the relay turns OFF. And when a LOW is applied from the controller the TRANSISTOR Q2 turns OFF so the base of transistor Q1 gets high voltage through the resistor R2 so the transistor Q1 turns ON which turns ON the relay. So basically Q2 & R2 acts as an inverter. If you want to connect more relays to microcontroller then you can use ULN 2003 for connecting seven relays or ULN 2803 for connecting eight relays. Figure 3 shows how to connect a relay to microcontroller using ULN 2003/ULN These IC s are high voltage, high current Darlington transistor arrays with open collector outputs and free-wheeling clamping diodes hence there is no need of a diode across the relay. Also there is no need of the series base resistor as the IC has an internal resistor of 2.7KΩ 286

287 6.6. Real Time Clock Interfacing (DS1307) with AT89S51 DS 1307 GENERAL DESCRIPTION: The DS1307 serial real-time clock (RTC) is a low power, full binary-coded decimal (BCD) clock/calendar plus 56 bytes of NV SRAM. Address and Data are transferred serially through an I2C bidirectional bus. The clock/calendar provides seconds, minutes, hour, date, day, month, and year information. The end of the month date is automatically adjusted for months with fewer than 31 days, including corrections for leap year. The clock operates in either the 24-hour or 12- hour format with AM/PM indicator. The DS1307 has a built-in power-sense circuit that detects power failures and automatically switches to the backup supply.timekeeping operation continues while the part operates from the backup supply. FEATURES: 287

288 Real-Time Clock (RTC) Counts Seconds, Minutes, Hours, Date of the Month, Month, Day of the week, and Year with Leap-Year Compensation Valid Up to Byte, Battery-Backed, General-Purpose RAM with Unlimited Writes. I2C Serial Interface. Programmable Square-Wave Output Signal. Automatic Power-Fail Detect and Switch Circuitry. Consumes Less than 500nA in Battery-Backup. Mode with Oscillator Running. Optional Industrial Temperature Range:-40 C to +85 C. Available in 8-Pin Plastic DIP or SO. Underwriters laboratories Recognized. Typical operating circuit 288

289 OSCILLATOR CIRCUIT: The DS1307 uses an external kHz crystal. The oscillator circuit does not require any external resistors or capacitors to operate. Table 1 specifies several crystal parameters for the external crystal. Figure 1 shows a functional schematic of the oscillator circuit. If using a crystal with the specified characteristics, the startup time is usually less than one second. 289

290 CLOCK ACCURACY : The accuracy of the clock is dependent upon the accuracy of the crystal and the accuracy of the match between the capacitive load of the oscillator circuit and the capacitive load for which the crystal was trimmed. Additional error will be added by crystal frequency drift caused by temperature shifts. External circuit noise coupled into the oscillator circuit may result in the clock running fast. Schematic Of Digital Alarm Clock Using 8051 Micro Controller: There are four switches connected to the uc, as shown in the figure. Function of the keys are same as clear from their names. When the power supply is switched on it will give you the default date and time, but later you can change it to the desired value. After setting once, the backup battery will keep the clock ticking even after the power is not there. A little about I2C: There are basically four main conditions in I2C protocol. 1) Start Condition 2)Stop Condition 3)Data Validity 4)Acknowledgement 1)Start Condition: when SCL is high and SDA H->L, will be taken as start condition for the communication. 2)Stop Condition: when SCL is high and SDA L->H, will generate a stop condition. 3)Data Validity: When SCL is high there should be no change in SDA line only then the data is valid, the data change should be made only when SCL is low. 4)Acknowledgement: After sending of one byte of data 290

291 the reciever has to acknowledge the sender for the successful reception. for this the sender make the SDA line high and reciever pulls down the SDA low, which tells the sender that data has reached safely. This application note describes the general hardware configuration and basic software communication examples for the Dallas I2C serial-interface Real-Time Clocks (RTC). The devices covered are the BCDformat I2C clocks: DS1307, DS1337, DS1338, DS1339 and DS1340. The DS1375 could also be supported, if circuit modifications were made to provide a digital clock signal (32,768Hz, 8,192Hz, 60H, or 50Hz) to the CLK input pin. The microcontroller used for this example is the DS2250, and the example software is written in C. A schematic of the circuit is shown in Figure 1. The schematic shows connections for a DS1340. The other RTCs may require modifications. The DS1337, for example, replaces the battery back up input with an additional interrupt output. The low voltage versions of the RTCs would require replacing the DS2250/DS5000 with a suitable low-voltage microcontroller. Figure 2 shows the software listing. The #define directive is used to conditionally compile the code for the proper device. The example shown is for the DS1307. The #define statement for the DS1307 should be replaced with the correct device before compiling the code 291

292 RTC (DS1307) Interfacing with AT89C Washing machine Circuits Many washing m/c shell in the market has mechanical controlled sequence for activated the timer and the sequence back and forth for their motor; washing motor or spinning motor. Spinning motor control only has one direction only, and its simple could be changed to the discrete mechanical timer which sell on the market. But washing motor control has 2 direction for this purpose, it means to squeeze the clothes, it must go to forward and then reversed. The sequence is like this : First, go to forward direction for about a few seconds Then stop, while the chamber is still rotate Second, go back to reverse direction for about a few seconds Then stop, while the chamber is still rotate And so on, back and forth, until the the timer elapsed TRIACs are effectively bidirectional electronic switches. They have greater efficiency characteristics, and fit into far smaller form factors than electromechanical alternatives. Unlike electromechanical devices, they don t have moving parts and aren t prone to oxidation of their contacts both of which can seriously 292

293 shorten the period over which traditional relays remain fully operational. Migration to TRIACs based control circuits will result in the creation of more compelling products which hit higher performance benchmarks. However, engineers need to have a good understanding of the various nuances involved in their use, in order to specify devices which are optimized for their particular application. Motion control implementation One of the most important application areas for TRIAC technology is in the control of motors, scaling the speed as required (see Figure.1). TRIAC devices are suitable for industrial, transportation and domestic system designs of this nature. TRIACs are now being deployed into a variety of white goods and appliances used around the home. They provide the switching functions to control the motors in washing machines, power tools, dish washers and air conditioners, as well as refrigerator compressors. For food processors or handheld blenders they allow the speed to be set at different levels, so that a variety of tasks can be done, while in washing machines they allow the speed at which the appliance runs to be matched to the size of washing load, thus helping to save energy. In refrigerators, having different compressor speeds (rather than simply off and full speed) enhances appliance efficiency, and once again means that energy can be saved. Figure 2 shows the typical three-phase motor arrangement utilized in a modern washing machine. TRIAC devices handling currents of 8 A RMS to 16A RMS are normally specified for this sort of application. Generally the motion control circuit will have a complement of three of these TRIACs which, once they are triggered, supply power to drive the three-phase motor that spins the washing machine s drum. An optocoupler device supplies the signal current to each of the TRIACs. The three optocouplers ensure the motor keeps the same phase shift between lines as they incorporate zero crossing circuits. TRIACs are generally connected to the line voltage. As well as powering the motor drive of the washing machine s drum, they drive smaller solenoid valves through which the water intake and draining operations are carried out, as well as soap dispensing. As the TRIACs are connected to the line on the mains they can 293

294 be driven directly from a microprocessor. The microprocessor triggers the appropriate TRIAC based on the cycle that has been selected by the user. The mains connection delivers an AC signal, and as this will cross 0 V it provides the means to have the TRIACs to return to their blocking state. The microprocessor then only needs to pulse the gate of each TRIAC when operation is required once again. TRIACs employed in this type of application will normally have blocking voltages (V DRM /V RRM ) of around 800 V. A drain pump of a washing machine is cyclically activated during a drain operation conducted as part of a spin cycle in a manner which reduces the run time of the pump. At least one dynamic operating parameter of the washing machine is sensed and used to control the operation of the drain pump. In accordance with a preferred embodiment of the invention, the rotational speed of the wash tub is sensed and, when a predetermined spin speed is maintained for a prescribed period of time, the drain operation is initiated. Water level, pump power and/or drive motor torque can also be utilized as pump cycling control parameters. This is a block diagram of a washing machine and how it is controlled by a Microcontroller. The basic components are electrical switches which in the past were relay, today they are Triacs. A triac is what is used in a home dimmer switch. The other important components are sensors. These come in many varieties and types. 294

295 295

296 The latest washing machines use inverter control for both washing and spin-drying. Inverter control helps reduce wash/spin noise and vibration and enables a washing machine to adjust the amount of water and motor torque to suit the wash load. IGBTs are used for motor drive, and microcontrollers for overall control. Additionally, an intelligent power device (IPD) is used to drive a water circulating pump of a spin dryer. Power factor correction (PFC) ICs or IGBTs are used in the power supply circuit to keep harmonics in the input current below the IEC limit Water Level Controller The Microcontroller based Water Level Controller cum Motor Protector controls on and off conditions of the motor depending upon the level of water in the over head tank (OHT), the status of which is displayed on an LCD module. The circuit also protects the motor from high voltages, low voltages, fluctuations of mains power and dry running. The circuit of the Microcontroller based Water Level Controller cum Motor Protector comprises of the operational amplifier LM324, microcontroller AT89C51, optocoupler PC817, regulator 7805 and an LCD module. Port pins P2.0 through P2.2 of the AT89C51 (IC2) are used to sense the water level, while pins P2.3 and P2.4 are used to sense the under-voltage and over-voltage, respectively. Pin P3.4 is used to control 296

297 relay RL1 with the help of optocoupler IC3 and transistor T5 in the case of under-voltage, over-voltage and different water-level conditions. The LM324 (IC1) is a quad operational amplifier (op-amp). Two of its opamps are used as comparators to detect under- and over-voltage. In normal condition, output pin 7 of IC1 is low, making pin P2.3 of IC2 high. When the voltage at pin 6 of N1 goes below the set reference voltage at pin 5 (say, 170 volts), output pin 7 of N1 goes high. This high output makes pin P2.3 of IC2 low, which is sensed by the microcontroller and the LCD module shows low voltage. In normal condition, pin 1 of N2 is high. When the voltage at pin 2 of N2 goes above the set voltage at pin 3, output pin 1 of N2 goes low. This low signal is sensed by the microcontroller and the LCD module shows high voltage. Presets VR1 and VR2 are used for calibrating the circuit for under- and over-voltage, respectively. When water in the tank rises to come in contact with the sensor, the base of transistor BC548 goes high. This high signal drives transistor BC548 into saturation and its collector goes low. The low signal is sensed by port pins of microcontroller IC2 to detect empty tank, dry sump and full tank, respectively. When water in the tank is below sensor A, the motor will switch on to fill water in the tank. The LCD module will show motor on. The controller is programmed for a 10-minute time interval to check the dryrun condition of the motor. If water reaches sensor B within 10 minutes, the microcontroller comes out of the dry-run condition and allows the motor to keep pushing water in the tank. The motor will remain on until water reaches sensor C. Then it will stop automatically and the microcontroller will go into the standby mode. The LCD module will show tank full followed by standby mode after a few seconds. The standby mode message is displayed until water in the tank goes below sensor A. In case water does not reach sensor B within 10 minutes, the microcontroller will go into the dry-running mode and stop the motor for 5 minutes, allowing it to cool down. The LCD module will show dry-sump1. After five minutes, the microcontroller will again switch on the motor for 10 minutes and check the status at sensor B. If water is still below sensor B, it will go into the dry-running mode and the LCD module will show dry-sump2. The same procedure will repeat, and if the dry-run condition still persists, the display will show dry-sump3 and the microcontroller will not start the motor automatically. Now you have to check the line for water and manually reset the microcontroller to start operation. In the whole procedure, the microcontroller checks for high and low voltages. For example, when the voltage is high, it will scan for about two seconds to check whether it is a fluctuation. If the voltage remains high after two seconds, the microcontroller will halt running of the motor. Now it will wait for the voltage to settle down. After the voltage becomes normal, it will still check for 90 seconds whether the voltage is normal or not. After normal condition, it will go in the standby mode and start the aforementioned procedure. 297

298 QUESTION BANK 2marks Question and Answers UNIT 1 BASICS OF MICROPROCESSOR BASED SYSTEM 1. What is Microprocessor? Give the power supply & clock frequency of 8085? Ans:A microprocessor is a multipurpose, programmable logic device that reads binary instructions from a storage device called memory accepts binary data as input and processes data according to those instructions and provides result as output. The power supply of 8085 is +5V and clock frequency in 3MHz. 2. List few applications of microprocessor-based system. Ans: It is used: i. For measurements, display and control of current, voltage, temperature, pressure, etc. ii. For traffic control and industrial tool control. iii. For speed control of machines. 3. What are the functions of an accumulator? Ans:The accumulator is the register associated with the ALU operations and sometimes I/O operations. It is an integral part of ALU. It holds one of data to be processed by ALU. It also temporarily stores the result of the operation performed by the ALU. 4. What is an Opcode? Ans: The part of the instruction that specifies the operation to be performed is called the operation code or opcode. 298

299 5. What is the function of IO/M signal? Ans: It is a status signal. It is used to differentiate between memory locations and I/O operations. When this signal is low (IO/M = 0) it denotes the memory related operations. When this signal is high (IO/M = 1) it denotes an I/O operation. 6. What is an Operand? Ans: The data on which the operation is to be performed is called as an Operand. 7. Explain the difference between a JMP instruction and CALL instruction. Ans: A JMP instruction permanently changes the program counter. A CALL instruction leaves information on the stack so that the original program execution sequence can be resumed. 8. Explain the purpose of the I/O instructions IN and OUT. Ans: The IN instruction is used to move data from an I/O port into the accumulator. The OUT instruction is used to move data from the accumulator to an I/O port. The IN & OUT instructions are used only on microprocessor, which use a separate address space for interfacing. 9. What is the difference between the shift and rotate instructions? Ans: A rotate instruction is a closed loop instruction. That is, the data moved out at one end is put back in at the other end. The shift instruction loses the data that is moved out of the last bit locations. 10. How many address lines in a 4096 x 8 EPROM CHIP? Ans: 12 address lines. 11. What are the Control signals used for DMA operation? Ans:-HOLD & HLDA. 12. What is meant by Wait State? Ans:-This state is used by slow peripheral devices. The peripheral devices can transfer the data to or from the microprocessor by using READY input line. The microprocessor remains in wait state as long as READY line is low. During the wait state, the contents of the address, address/data and control buses are held constant. 13. What is meant by polling? Ans:-Polling or device polling is a process which identifies the device that has interrupted the microprocessor. 14. What is meant by interrupt? Ans:-Interrupt is an external signal that causes a microprocessor to jump to a specific subroutine. 299

300 15. What is a microcomputer? Ans:-A computer that is designed using a microprocessor as its CPU is called microcomputer. 16. Basic concepts in memory interfacing Ans:-The primary function of memory interfacing is that the microprocessor should be able to read from and write into a given register of a memory chip. To perform these operations the microprocessor should Be able to select the chip Identify the register Enable the appropriate buffer 17. What is an instruction? Ans:-An instruction is a binary pattern entered through an input device to command the microprocessor to perform that specific function 18. What is the use of ALE Ans:-The ALE is used to latch the lower order address so that it can be available in T2 and T3 and used for identifying the memory address. During T1 the ALE goes high, the latch is transparent ie, the output changes according to the input data, so the output of the latch is the lower order address. When ALE goes low the lower order address is latched until the next ALE. 19. What is the use of addressing modes, mention the different types Ans:The various formats of specifying the operands are called addressing modes, it is used to access the operands or data. The different types are as follows Immediate addressing Register addressing Direct addressing Indirect addressing Implicit addressing 20. What is the use of bi-directional buffers? Ans:It is used to increase the driving capacity of the data bus. The data bus of a microcomputer system is bi-directional, so it requires a buffer that allows the data to flow in both directions. 21. Define stack and explain stack related instructions Ans:The stack is a group of memory locations in the R/W memory that is used for the temporary storage of binary information during the execution of the program. The stack related instructions are PUSH & POP 22. What is Microcontroller and Microcomputer 300

301 Ans:Microcontroller is a device that includes microprocessor; memory and I/O signal lines on a single chip, fabricated using VLSI technology. Microcomputer is a computer that is designed using microprocessor as its CPU. It includes microprocessor, memory and I/O. 23. Define Flags Ans:The flags are used to reflect the data conditions in the accumulator. The flags are S-Sign flag, Z-Zero flag, AC-Auxiliary carry flag, P-Parity flag, CYCarry flag, D7 D6 D5 24. How does the microprocessor differentiate between data and instruction? Ans:When the first m/c code of an instruction is fetched and decoded in the instruction register, the microprocessor recognizes the number of bytes required to fetch the entire instruction. For example MVI A, Data, the second byte is always considered as data. If the data byte is omitted by mistake whatever is in that memory location will be considered as data & the byte after the data will be treated as the next instruction. 25. What is assembler? Ans:The assembler translates the assembly language program text which is given as input to the assembler to their binary equivalents known as object code. The time required to translate the assembly code to object code is called access time. The assembler checks for syntax errors & displays them before giving the object code. 26. What is loader? Ans:The loader copies the program into the computer s main memory at load time and begins the program execution at execution time. 27. What is linker? Ans:A linker is a program used to join together several object files into one large object file. For large programs it is more efficient to divide the large program modules into smaller modules. Each module is individually written, tested & debugged. When all the modules work they are linked together to form a large functioning program. 28. What is interrupt service routine? Ans:Interrupt means to break the sequence of operation. While the CPU is executing a program an interrupt breaks the normal sequence of execution of instructions & diverts its execution to some other program. This program to which the control is transferred is called the interrupt service routine. 29.What are the various programmed data transfer methods? Ans: i) Synchronous data transfer ii) Asynchronous data transfer iii) Interrupt driven data transfer 30. What is synchronous data transfer? 301

302 Ans:It is a data method which is used when the I/O device and the microprocessor match in speed. To transfer a data to or from the device, the user program issues a suitable instruction addressing the device. The data transfer is completed at the end of the execution of this instruction. 31. What is asynchronous data transfer? Ans:It is a data transfer method which is used when the speed of an I/O device does not match with the speed of the microprocessor. Asynchronous data transfer is also called as Handshaking. UNIT 1 & SYSTEME DESIGN AND PROGRAMMING 1. Define pipelining? Ans: In 8086, to speedup the execution of program, the instructions fetching and execution of instructions are overlapped each other. This technique is known as pipelining. In pipelining, when the n th instruction is executed, the n+1 th instruction is fetched and thus the processing speed is increased. 2. Discuss the function of instruction queue in 8086? Ans: In 8086, a 6-byte instruction queue is presented at the Bus Interface Unit (BIU). It is used to prefetch and store at the maximum of 6 bytes of instruction code from the memory. Due to this, overlapping instruction fetch with instruction execution increases the processing speed. 3. What is the maximum memory size that can be addressed by 8086? Ans: In 8086, an memory location is addressed by 20 bit address and the address bus is 20 bit address and the address bus is 20 bits. So it can address up to one mega byte (2^20) of memory space. 4. What is the function of the signal in 8086? Ans: BHE signal means Bus High Enable signal. The BHE signal is made low when there is some read or write operation is carried out. ie. When ever the data bus of the system is busy i.e. whenever there is some data transfer then the BHE signal is made low. 5.What are the predefined interrupts in 8086? Ans: The various predefined interrupts are, DIVISION BY ZERO -- (type 0) Interrupt. SINGLE STEP -- (type 1) Interrupt. NONMASKABLE -- (type2) Interrupt. BREAK POINT -- (type 3) Interrupt. OVER FLOW -- (type 4) Interrupt. 6. What are the different flag available in status register of 8086? 302

303 Ans: There are 6 one bit flags are present. They are, AF - Auxiliary Carry Flag CF - Carry Flag OF - Overflow Flag SF - Sign Flag PF - Parity Flag ZF - Zero Flag 7. List the various addressing modes present in 8086? Ans: There are 12 addressing modes present in They are, (a) Register and immediate addressing modes Register addressing modes Immediate addressing mode (b) Memory addressing modes. Direct addressing modes Register indirect addressing modes Based addressing modes Indexed addressing modes Based Indexed addressing modes String addressing modes (c) I/O addressing modes Direct addressing mode Indirect addressing mode (d) Relative addressing mode (e) Implied addressing mode 8. How single stepping can be done in 8086? Ans: By setting the Trace Flag (TF) the 8086 goes to single-step mode. In this mode, after the execution of each instruction s 8086 generates an internal interrupt and by writing some interrupt service routine we can display the content of desired registers and memory locations. So it is useful for debugging the program. 9. State the significance of LOCK signal in 8086? Ans: If 8086 is working at maximum mode, there are multiprocessors are present. If the system bus is given to a processor then the LOCK signal is made low. That means the system bus is busy and it cannot be given of any other processors. After the use of the system bus again the LOCK signal is made high. That means it is ready to give the system bus to any processor. 10. What are the functions of bus interface unit (BIU) in 8086? 303

304 Ans: (a) Fetch instructions from memory. (b) Fetch data from memory and I/O ports. (c) Write data to memory and I/O ports. (d) To communicate with outside world. (e) Provide external bus operations and bus control signals. 11. What is the clock frequency of 8086? Ans: Microprocessor Internal clock Frequency External Clock Frequency 5 MHz 8MHz 4MHz 15MHZ 24MHZ 12MHZ 12. What are the two modes of operations present in 8086? Ans: i. Minimum mode (or) Uniprocessor system ii. Maximum mode (or) Multiprocessor system 13. Explain the process control instructions Ans: STC It sets the carry flag & does not affect any other flag CLC it resets the carry flag to zero &does not affect any other flag CMC It complements the carry flag & does not affect any other flag STD It sets the direction flag to 1 so that SI and/or DI can be decremented automatically after execution of string instruction & does not affect other flags CLD It resets the direction flag to 0 so that SI and/or DI can be incremented automatically after execution of string instruction & does not affect other flags STI Sets the interrupt flag to 1. Enables INTR of CLI Resets the interrupt flagto will not respond to INTR. 14. Explain REPEAT-UNTIL statements Ans: REPEAT-UNTIL statements allow executing a series of instructions repeatedly until some condition occurs. The REPEAT defines the start of the loop & UNTIL the end of the loop. UNTIL has a condition when the condition is true the loop is terminated. 15. What is the purpose of segment registers in 8086? 304

305 Ans:There are 4 segment registers present in They are 1. Code Segment (CS ) register - The code segment register gives the address of the current code segment. ie. It will points out where the instructions, to be executed, are stored in the memory. 2. Data Segment (DS ) register - The data segment register points out where the operands are stored in the memory. 3. Stack Segment (SS ) register - The stack segment registers points out the address of the current stack, which is used to store the temporary results. 4. Extra Segment (ES ) register - If the amount of data used is more the Extra segment register points out where the large amount of data is stored in the memory. 16. What is assembler? Ans: The assembler translates the assembly language program text which is given as input to the assembler to their binary equivalents known as object code. The time required to translate the assembly code to object code is called access time. The assembler checks for syntax errors & displays them before giving the object code. 17. What is loader? Ans:The loader copies the program into the computer s main memory at load time and begins the program execution at execution time. 18. What is linker? A linker is a program used to join together several object files into one large object file. For large programs it is more efficient to divide the large program modules into smaller modules. Each module is individually written, tested & debugged. When all the modules work they are linked together to form a large functioning program. 19. Explain ALIGN & ASSUME: Ans: The ALIGN directive forces the assembler to align the next segment at an address divisible by specified divisor. The format is ALIGN number where number can be 2, 4, 8 or 16. Example ALIGN 8. The ASSUME directive assigns a logical segment to a physical segment at any given time. It tells the assembler what address will be in the segment registers at execution time. Example ASSUME CS: code, DS: data, SS: stack 20. Explain PTR & GROUP Ans: A program may contain several segments of the same type. The GROUP directive collects them under a single name so they can reside in a single segment, usually a data segment. The format is Name GROUP Seg-name,..Seg-name PTR is used to assign a specific type to a variable or a label. It is also used to override the declared type of a variable. 21. What are the three classifications of 8086 interrupts? Ans: 305

306 (1) Predefined interrupts (2) User defined Hardware interrupts (3) User defined software interrupts. 22. What are the functions of status pins in 8086? Ans: S2 S1 S0 Functions Interrupt acknowledge Read I/O Write I/O Halt Code access Read memory Write memory inactive S4 S3 Functions 0 0 I/O from extra segment 0 1 I/O from Stack Segment 1 0 I/O from Code segment 1 0 I/O from Data segment S5 --Status of interrupt enable flag S6 --Hold acknowledge for system bus S7 --Address transfer. 23. What are the schemes for establishing priority in order to resolve bus arbitration problem? Ans: There are three basic bus access control and arbitration schemes 1. Daisy Chaining 2. Independent Request 3. Polling 306

307 24.What are the different types of methods used for data transmission? Ans: The data transmission between two points involves unidirectional or bi-directional transmission of meaningful digital data through a medium. There are basically there modes of data transmission. (a) Simplex (b) Duplex (c) Half Duplex In simplex mode, data is transmitted only in one direction over a single communication channel.for example, a computer (CPU) may transmit data for a CRT display unit in this mode. In duplex mode, data may be transferred between two transreceivers in both directions simultaneously. In half duplex mode, on the other hand, data transmission may take pace in either direction, but at a time data may be transmitted only in one direction. For example, a computer may communicate with a terminal in this mode. When the terminal sends data (i.e. terminal is sender). The message is received by the computer (i.e the computer is receiver). However, it is not possible to transmit data from the computer to terminal and from terminal to the computer simultaneously. 25.What are the various programmed data transfer methods? Ans: i) Synchronous data transfer ii) Asynchronous data transfer iii) Interrupt driven data transfer 26. What is synchronous data transfer? Ans: It is a data method which is used when the I/O device and the microprocessor match in speed. To transfer a data to or from the device, the user program issues a suitable instruction addressing the device. The data transfer is completed at the end of the execution of this instruction. 27. What is asynchronous data transfer? Ans: It is a data transfer method which is used when the speed of an I/O device does not match with the speed of the microprocessor. Asynchronous data transfer is also called as Handshaking. 28.What are the different inter connection topologies? Ans: Shared bus Multiport Memory Linked Input/Output Bus window Crossbar Switching. 29. What are the configurations used for physical interconnections? Ans: 307

308 Star Configuration Loop configuration Complete interconnection Regular topologies Irregular topologies 30. Give the instruction set of 8087? Ans: 1. Data Transfer Instructions 2. Arithmetic Instructions 3. Comparison Instructions. 4. Transcendental Operations. 5. Constant Operations. 6. Coprocessor Control Operations. 31. Write the advantages of loosely coupled system over tightly coupled systems? Ans: 1. More number of CPUs can be added in a loosely coupled system to improve the system performance 2. The system structure is modular and hence easy to maintain and troubleshoot. 3. A fault in a single module does not lead to a complete system breakdown. 32. What is the different clock frequencies used in 80286? Ans: Various versions of are available that run on 12.5MHz, 10MHz and 8MHz clock frequencies. 33. Define swapping in? Ans: The portion of a program is required for execution by the CPU, it is fetched from the secondary memory and placed in the physical memory. This is called swapping in of the program. 34. What are the different operating modes used in 80286? Ans: The works in two operating modes 1. Real addressing mode 2. Protected virtual address mode. 35. What are the CPU contents used in 80286? Ans: The CPU contains almost the same set of registers, as in 8086 Eight 16-bit general purpose register Four 16-bit segment registers Status and control register 308

309 Instruction pointer. 36. What is status flag bit? Ans: The flag register reflects the results of logical and arithmetic instructions. The flag register digits D0, D2, D4, D6, D7 and D11 are modified according to the result of the execution of logical and arithmetic instruction. These are called as status flag bits. 37. What is a control flag? Ans: The bits D8 and D9 namely, trap flag (TF) and interrupt flag (IF) bits, are used for controlling machine operation and thus they are called control flags. 38. What is instruction pipelining? Ans: Major function of the bus unit is to fetch instruction bytes from the memory. In fact, the instructions are fetched in advance and stored in a queue to enable faster execution of the instructions. This concept is known as instruction pipelining. 39. What is swapping? Ans: The procedure of fetching the chosen program segments or data from the secondary storage into the physical memory is called swapping. 40. What is mean by microcontroller? Ans: A device which contains the microprocessor with integrated peripherals like memory, serial ports, parallel ports, timer/counter, interrupt controller, data acquisition interfaces like ADC,DAC is called microcontroller. 41. Explain about MODEL Ans: This directive provides short cuts in defining segments. It initializes memory model before defining any segment. The memory model can be SMALL, MEDIUM, COMPACT or LARGE. Model Code segments Data segments Small One One Medium Multiple One Compact One Multiple Large Multiple Multiple 42. Explain PROC & ENDP Ans: PROC directive defines the procedures in the program. The procedure name must be unique. After PROC the term NEAR or FAR are used to specify the type of procedure. Example FACT PROC FAR. ENDP is used along with PROC and defines the end of the procedure. 43. Explain SEGMENT & ENDS 309

310 Ans: An assembly program in.exe format consists of one or more segments. The starts of these segments are defined by SEGMENT and the end of the segment is indicated by ENDS directive. Format Name SEGMENT Name ENDS 44. Explain TITLE & TYPE Ans: The TITLE directive helps to control the format of a listing of an assembled program. It causes a title for the program to print on line 2 of each page of the program listing. Maximum 60 characters are allowed. Format TITLE text. TYPE operator tells the assembler to determine the type of specified variable in bytes. For bytes the assembler gives a value 1, for word 2 & double word Define SOP Ans: The segment override prefix allows the programmer to deviate from the default segment Eg : MOV CS : [BX], AL 46. Define variable Ans: A variable is an identifier that is associated with the first byte of data item. In assembly language statement: COUNT DB 20H, COUNT is the variable. 47. What are procedures? Ans: Procedures are a group of instructions stored as a separate program in memory and it is called from the main program whenever required. The type of procedure depends on where the procedures are stored in memory. If it is in the same code segment as that of the main program then it is a near procedure otherwise it is a far procedure. 48. Explain the linking process: Ans: A linker is a program used to join together several object files into one large object file. The linker produces a link file which contains the binary codes for all the combined modules. It also produces a link map which contains the address information about the link files. The linker does not assign absolute addresses but only relative address starting from zero, so the programs are relocatable & can be put anywhere in memory to be run. 49. Explain about passing parameters using registers with example: Ans: Procedures process some data or address variable from the main program, for processing it is necessary to pass the address variables or data. This is called passing parameters to procedures. In passing parameters using registers the data to be passed is stored in registers & these registers are accessed in the procedure to process the data. CODE SEGMENT MOV AL, DATA CALL PRO1 PRO1 PROC NEAR MOV INPUT, AL 310

311 RET PRO1 ENDP CODE ENDS 50. What is recursive procedures? Ans: A recursive procedure is a procedure, which calls itself. Recursive procedures are used to work with complex data structures called trees. If the procedure is called with N=3, then the N is decremented by 1 after each procedure CALL and the procedure is called until N= What are libraries? Ans: Library files are collection of procedures that can be used in other programs. These procedures are assembled and compiled into a library file by the LIB program. The library file is invoked when a program is linked with linker program. when a library file is linked only the required procedures are copied into the program. Use of library files increase s/w reusability & reduce s/w development time. 52. What are Macros? Ans: Macro is a group of instruction. The macro assembler generates the code in the program each time where the macro is called. Macros are defined by MACRO & ENDM directives. Creating macro is similar to creating new opcodes that can be used in the program INIT MACRO MOV AX, data MOV DS MOV ES, AX ENDM 53. How do 8086 interrupts occur? Ans: An 8086 interrupt can come from any of the following three sources External signals Special instructions in the program Condition produced by instruction 54. What are the 8086 interrupt types? Ans: Dedicated interrupts Type 0: Divide by zero interrupt Type 1: Single step interrupt Type 2:Non maskable interrupt Type 3: Breakpoint Type 4: Overflow interrupt Software interrupts Type

312 55. What is interrupt service routine? Ans: Interrupt means to break the sequence of operation. While the CPU is executing a program an interrupt breaks the normal sequence of execution of instructions & diverts its execution to some other program. This program to which the control is transferred is called the interrupt service routine. 56. Define BIOS Ans: The IBM PC has in its ROM a collection of routines, each of which performs some specific function such as reading a character from keyboard, writing character to CRT. This collection of routines is referred to as Basic Input Output System or BIOS. 57. Explain PUBLIC Ans: For large programs several small modules are linked together. In order that the modules link together correctly any variable name or label referred to in other modules must be declared public in the module where it is defined. The PUBLIC directive is used to tell the assembler that a specified name or label will be accessed from other modules. Format PUBLIC Symbol. 58. Explain DUP Ans: The DUP directive can be used to initialize several locations & to assign values to these locations. Format Name Data_Type Num DUP (value) Example TABLE DW 10 DUP (0). Reserves an array of 10 words of memory and initializes all 10 words with 0. array name is TABLE. 59. Compare Procedure & Macro Ans: Procedure Accessed by CALL & RET instruction Machine code for instruction is put only once in the memory With procedures less memory is required Parameters can be passed in registers, memory locations or stack Macro Accessed during assembly with name given during program execution to macro when defined Machine code is generated for instruction each time when macro is called. With macro more memory is required Parameters passed as part of statement which calls macro 60. Define: Multiprogramming Ans: If more than one process is carried out at the same time, then it is know as multiprogramming. Another definition is the interleaving of CPU and I/O operations among several programs is called multiprogramming. To improve the utilization of CPU and I/O devices, we are designing to process a set of independent programs concurrently by a single CPU. This technique is known as multiprogramming. 312

313 46. Differentiate between absolute and linear select decoding? Ans: Absolute decoding All higher address lines are defined to select the memory or I/O device More h/w is required to design decoding logic Higher cost for decoding circuit No multiple address Used in large systems Linear decoding Few higher address lines are decoded to select the memory or I/O device Hardware required to design decoding logic is less Less cost for decoding circuit Has a disadvantage of multiple addressing Used in small systems 47. What are the three classifications of 8086 interrupts? Ans: (1) Predefined interrupts (2) User defined Hardware interrupts (3) User defined software interrupts. 48. What is the use of 8251 chip? Ans: Intel s 8251A is a universal synchronous asynchronous receiver and transmitter compatible with Intel s Processors. This may be programmed to operate in any of the serial communication modes built into it. This chip converts the parallel data into a serial stream of bits suitable for serial transmission. It is also able to receive a serial stream of bits and converts it into parallel data bytes to be read by a microprocessor. 49. What is interfacing? Ans: An interface is a shared boundary between the devices which involves sharing information. Interfacing is the process of making two different systems communicate with each other. 50. What is meant by interrupt? Ans: Interrupt is an external signal that causes a microprocessor to jump to a specific subroutine. 313

314 UNIT 3 PERIPHERAL INTERFACING 53. What are the basic modes of operation of 8255? Ans: There are two basic modes of operation of 8255, They are: 1. I/O mode. 2. BSR mode. In I/O mode, the 8255 ports work as programmable I/O ports, while In BSR mode only port C (PC0-PC7) can be used to set or reset its individual port bits. Under the IO mode of operation, further there are three modes of operation of 8255, So as to support different types of applications, viz. mode 0, mode 1 and mode 2. Mode 0 - Basic I/O mode Mode 1 - Strobed I/O mode Mode 2 - Strobed bi-directional I/O. 54. Write the features of mode 0 in 8255? Ans: 1. Two 8-bit ports (port A and port B) and two 4-bit ports (port C upper and lower) are available. The two 4-bit ports can be combined used as a third 8-bit port. 2. Any port can be used as an input or output port. 3.Output ports are latched. Input ports are not latched. 4. A maximum of four ports are available so that overall 16 I/O configurations are possible. 55. What are the features used mode 1 in 8255? Ans:Two groups group A and group B are available for strobed data transfer. 1. Each group contains one 8-bit data I/O port and one 4-bit control/data port. 2. The 8-bit data port can be either used as input or output port. The inputs and outputs both are latched. 3. Out of 8-bit port C, PC0-PC2 is used to generate control signals for port B and PC3=PC5 are used to generate control signals for port A. The lines PC6, PC7 may be used as independent data lines. 56. What are the signals used in input control signal & output control signal? Ans: Input control signal STB (Strobe input) IBF (Input buffer full) INTR(Interrupt request) 314

315 Output control signal OBF (Output buffer full) ACK (Acknowledge input) INTR(Interrupt request) 57. What are the features used mode 2 in 8255? Ans:The single 8-bit port in-group A is available. 1. The 8-bit port is bi-directional and additionally a 5-bit control port is available. 2. Three I/O lines are available at port C, viz PC2-PC0. 3. Inputs and outputs are both latched. 4. The 5-bit control port C (PC3=PC7) is used for generating/accepting handshake signals for the 8-bit data transfer on port A. 58. What are the modes of operations used in 8253? Ans:Each of the three counters of 8253 can be operated in one of the following six modes of operation. 1. Mode 0 (Interrupt on terminal count) 2. Mode 1 (Programmable monoshot) 3. Mode 2 (Rate generator) 4. Mode 3 (Square wave generator) 5. Mode 4 (Software triggered strobe) 6. Mode 5 (Hardware triggered strobe) 59. What are the different types of write operations used in 8253? Ans:There are two types of write operations in 8253 (1) Writing a control word register (2) Writing a count value into a count register The control word register accepts data from the data buffer and initializes the counters, as required. The control word register contents are used for (a) Initializing the operating modes (mode 0-mode4) (b) Selection of counters (counter 0- counter 2) (c) Choosing binary /BCD counters (d) Loading of the counter registers. The mode control register is a write only register and the CPU cannot read its contents. 60. Give the different types of command words used in 8259a? Ans:The command words of 8259A are classified in two groups 1. Initialization command words (ICWs) 2. Operation command words (OCWs) 315

316 61. Give the operating modes of 8259a? Ans: (a) Fully Nested Mode (b) End of Interrupt (EOI) (c) Automatic Rotation (d) Automatic EOI Mode (e) Specific Rotation (f) Special Mask Mode (g) Edge and level Triggered Mode (h) Reading 8259 Status (i) Poll command (j) Special Fully Nested Mode (k) Buffered mode (l) Cascade mode 62. Define scan counter? Ans: The scan counter has two modes to scan the key matrix and refresh the display. In the encoded mode, the counter provides binary count that is to be externally decoded to provide the scan lines for keyboard and display. In the decoded scan mode, the counter internally decodes the least significant 2 bits and provides a decoded 1 out of 4 scan on SL0-SL3.The keyboard and display both are in the same mode at a time. 63. What is the output modes used in 8279? Ans: 8279 provides two output modes for selecting the display options. 1.Display Scan In this mode, 8279 provides 8 or 16 character-multiplexed displays those can be organized as dual 4-bit or single 8-bit display units. 2.Display Entry 8279 allows options for data entry on the displays. The display data is entered for display from the right side or from the left side. 64. What are the modes used in keyboard modes? Ans: 1. Scanned Keyboard mode with 2 Key Lockout. 2. Scanned Keyboard with N-key Rollover. 3. Scanned Keyboard special Error Mode. 4. Sensor Matrix Mode. 65. What are the modes used in display modes? Ans:1. Left Entry mode 316

317 In the left entry mode, the data is entered from the left side of the display unit. 2. Right Entry Mode. In the right entry mode, the first entry to be displayed is entered on the rightmost display. 66. What is the use of modem control unit in 8251? Ans: The modem control unit handles the modem handshake signals to coordinate the communication between the modem and the USART. 67. Give the register organization of 8257? Ans: The 8257 perform the DMA operation over four independent DMA channels. Each of the four channels of 8257 has a pair of two 16-bit registers. DMA address register and terminal count register. Also, there are two common registers for all the channels; namely, mode set registers and status register. Thus there are a total of ten registers. The CPU selects one of these ten registers using address lines A0- A What is the function of DMA address register? Ans: Each DMA channel has one DMA address register. The function of this register is to store the address of the starting memory location, which will be accessed by the DMA channel. Thus the starting address of the memory block that will be accessed by the device is first loaded in the DMA address register of the channel. Naturally, the device that wants to transfer data over a DMA channel, will access the block of memory with the starting address stored in the DMA Address Register. 69. What is the use of terminal count register? Ans: Each of the four DMA channels of 8257 has one terminal count register. This 16-bit register is used for ascertaining that the data transfer through a DMA channel ceases or stops after the required number of DMA cycles. 70. What is the function of mode set register in 8257? Ans: The mode set register is used for programming the 8257 as per the requirements of the system. The function of the mode set register is to enable the DMA channels individually and also to set the various modes of operation. 71. What is interfacing? Ans: An interface is a shared boundary between the devices which involves sharing information. Interfacing is the process of making two different systems communicate with each other. 72. List the operation modes of 8255 Ans: a) I.O Mode 317

318 i. Mode 0-Simple Input/Output. ii. Mode 1-Strobed Input/Output (Handshake mode) iii. Mode 2-Strobed bidirectional mode b) Bit Set/Reset Mode. 73. What is a control word? Ans: It is a word stored in a register (control register) used to control the operation of a program digital device. 74. What is the purpose of control word written to control register in 8255? Ans: The control words written to control register specify an I/O function for each I.O port. The bit D7 of the control word determines either the I/O function of the BSR function. 75.What is the size of ports in 8255? Ans: Port-A : 8-bits Port-B : 8-bits Port-CU : 4-bits Port-CL : 4-bits 76. Distinguish between the memories mapped I/O peripheral I/O? Ans: 16-bit device address Memory Mapped I/O 8-bit device address Peripheral MappedI/O Data transfer between any general-purpose register and I/O port. The memory map (64K) is shared between I/O device and system memory. More hardware is required to decode 16-bit address Arithmetic or logic operation can be directly performed with I/O data Data is transfer only between accumulator and I.O port The I/O map is independent of the memory map; 256 input device and 256 output device can be connected Less hardware is required to decode 8-bit address Arithmetic or logical operation cannot be directly performed with I/O data 77. What is memory mapping? 318

319 Ans: The assignment of memory addresses to various registers in a memory chip is called as memory mapping. 78. What is I/O mapping? Ans:The assignment of addresses to various I/O devices in the memory chip is called as I/O mapping. 79. What is an USART? Ans:USART stands for universal synchronous/asynchronous Receiver/Transmitter. It is a programmable communication interface that can communicate by using either synchronous or asynchronous serial data. 80.What is the use of 8251 chip? 8251 chip is mainly used as the asynchronous serial interface between the processor and the external equipment. 81. What is 8279? Ans:The 8279 is a programmable Keyboard/Display interface. 82. List the major components of the keyboard/display interface. a. Keyboard section b. Scan section c. Display section d. CPU interface section 83. What is Key bouncing? Ans: Mechanical switches are used as keys in most of the keyboards. When a key is pressed the contact bounce back and forth and settle down only after a small time delay (about 20ms). Even though a key is actuated once, it will appear to have been actuated several times. This problem is called Key Bouncing. 84.Define HRQ? Ans: The hold request output requests the access of the system bus. In non- cascaded 8257 systems, this is connected with HOLD pin of CPU. In cascade mode, this pin of a slave is connected with a DRQ input line of the master 8257, while that of the master is connected with HOLD input of the CPU. 85. What is the use of stepper motor? Ans:A stepper motor is a device used to obtain an accurate position control of rotating shafts. A stepper motor employs rotation of its shaft in terms of steps, rather than continuous rotation as in case of AC or DC motor. 86. What is TXD? Ans: TXD- Transmitter Data Output This output pin carries serial stream of the transmitted data bits along with other information like start bit, stop bits and priority bit. 319

320 87. What is RXD? Ans: RXD- Receive Data Input This input pin of 8251A receives a composite stream of the data to be received by 8251A. 88. What is meant by key bouncing? Ans:Microprocessor must wait until the key reach to a steady state; this is known as Key bounce. 89. What is swapping? The procedure of fetching the chosen program segments or data from the secondary storage into the physical memory is called swapping. 90. Write the function of crossbar switch? Ans: The crossbar switch provides the inter connection paths between the memory module and the processor. Each node of the crossbar represents a bus switch. All these nodes may be controlled by one of these processors or by a separate one altogether. 91. What is a data amplifier? Ans: Transceivers are the bi-directional buffers are some times they are called as data amplifiers. They are required to separate the valid data from the time multiplexed address data signal. They are controlled by 2 signals i.e DEN & DT/R. 92. What is status flag bit? Ans: The flag register reflects the results of logical and arithmetic instructions. The flag register digits D0, D2, D4, D6, D7 and D11 are modified according to the result of the execution of logical and arithmetic instruction. These are called as status flag bits. 93. What is a control flag? Ans: The bits D8 and D9 namely, trap flag (TF) and interrupt flag (IF) bits, are used for controlling machine operation and thus they are called control flags. 94. What is instruction pipelining? Ans: Major function of the bus unit is to fetch instruction bytes from the memory. In fact, the instructions are fetched in advance and stored in a queue to enable faster execution of the instructions. This concept is known as instruction pipelining. 95. Compare Microprocessor and Microcontroller. Ans: Microprocessor Microcontroller 320

321 Microprocessor contains ALU,general purpose registers,stack pointer, program counter, clock timing circuit and interrupt circuit. It has many instructions to move data between memory and CPU. Microcontroller contains the circuitry of microprocessor and in addition it has built- in ROM, RAM, I/O devices, timers and counters. It has one or two instructions to move data between memory and CPU. It has one or two bit handling instructions. It has many bit handling instructions. Access times for memory and I/O devices are more. Microprocessor based system requires more hardware. Less access times for built-in memory and I/O devices. Microcontroller based system requires less hardware reducing PCB size and increasing the reliability. 321

322 UNIT ARCHITECTURE 322

323 323

324 324

325 x 325

326 326

327 327

328 328

329 329

330 330

331 331

332 332

333 333

334 UNIT INSTRUCTIONS AND PROGRAMMING 334

335 335

336 336

337 337

338 338

339 339

340 340

341 341

342 342

343 343

344 344

345 UNIT 5 SYSTEM DESIGN USING MICRO PROCESSOR &MICROCONTROLLER 1. What is an H-Bridge Ans: The name "H-Bridge" is derived from the actual shape of the switching circuit which control the motoion of the motor. It is also known as "Full Bridge". Basically there are four switching elements in the H-Bridge 2. List the truth table according to the switching of H-Bridge Ans:. Truth Table High Left High Right Low Left Low Right Description On Off Off On Motor runs clockwise Off On On Off Motor runs anti-clockwise On On Off Off Motor stops or decelerates Off Off On On Motor stops or decelerates 3. What is a L293 IC used for? Ans L293 is a dedicated quadruple half H bridge motor driver IC available in 16 pin package. 4. What is a Unipolar stepper motor? Ans: The unipolar stepper motor has five or six wires and four coils (actually two coils divided by center connections on each coil). The center connections of the coils are tied together and used as the power connection. They are called unipolar steppers because power always comes in on this one pole. 5. What is a Bipolar stepper motor? Ans: The bipolar stepper motor usually has four wires coming out of it. Unlike unipolar steppers, bipolar steppers 345

1.1. INTRODUCTION TO MICROPROCESSOR, MICROCONTROLLER AND SYSTEM DESIGN

1.1. INTRODUCTION TO MICROPROCESSOR, MICROCONTROLLER AND SYSTEM DESIGN .. INTRODUCTION TO MICROPROCESSOR, MICROCONTROLLER AND SYSTEM DESIGN The brain or engine of the PC is the processor (sometimes called microprocessor), or central processing unit (CPU). The CPU performs

More information

SARDAR RAJA COLLEGES SARDAR RAJA COLLEGE OF ENGINEERING ALANGULAM

SARDAR RAJA COLLEGES SARDAR RAJA COLLEGE OF ENGINEERING ALANGULAM SARDAR RAJA COLLEGES SARDAR RAJA COLLEGE OF ENGINEERING ALANGULAM DEPARTMENT OF ELECTRONICS & COMMUNICATION ENGINEERING MICRO LESSON PLAN SUBJECT NAME : MICROPROCESSOR AND MICRO CONTROLLER SUBJECT CODE

More information

3.1 Description of Microprocessor. 3.2 History of Microprocessor

3.1 Description of Microprocessor. 3.2 History of Microprocessor 3.0 MAIN CONTENT 3.1 Description of Microprocessor The brain or engine of the PC is the processor (sometimes called microprocessor), or central processing unit (CPU). The CPU performs the system s calculating

More information

CREATED BY M BILAL & Arslan Ahmad Shaad Visit:

CREATED BY M BILAL & Arslan Ahmad Shaad Visit: CREATED BY M BILAL & Arslan Ahmad Shaad Visit: www.techo786.wordpress.com Q1: Define microprocessor? Short Questions Chapter No 01 Fundamental Concepts Microprocessor is a program-controlled and semiconductor

More information

THE MICROCOMPUTER SYSTEM CHAPTER - 2

THE MICROCOMPUTER SYSTEM CHAPTER - 2 THE MICROCOMPUTER SYSTEM CHAPTER - 2 20 2.1 GENERAL ASPECTS The first computer was developed using vacuum tubes. The computers thus developed were clumsy and dissipating more power. After the invention

More information

The Central Processing Unit

The Central Processing Unit The Central Processing Unit All computers derive from the same basic design, usually referred to as the von Neumann architecture. This concept involves solving a problem by defining a sequence of commands

More information

8085 microprocessor Submitted in partial fulfillment of the requirement for the award of degree of Electronics

8085 microprocessor Submitted in partial fulfillment of the requirement for the award of degree of Electronics A Seminar report On 8085 microprocessor Submitted in partial fulfillment of the requirement for the award of degree of Electronics SUBMITTED TO: www.studymafia.org SUBMITTED BY: www.studymafia.org Acknowledgement

More information

Microprocessors/Microcontrollers

Microprocessors/Microcontrollers Microprocessors/Microcontrollers A central processing unit (CPU) fabricated on one or more chips, containing the basic arithmetic, logic, and control elements of a computer that are required for processing

More information

Segment 1A. Introduction to Microcomputer and Microprocessor

Segment 1A. Introduction to Microcomputer and Microprocessor Segment 1A Introduction to Microcomputer and Microprocessor 1.1 General Architecture of a Microcomputer System: The term microcomputer is generally synonymous with personal computer, or a computer that

More information

Microcontrollers. Fig. 1 gives a comparison of a microprocessor system and a microcontroller system.

Microcontrollers. Fig. 1 gives a comparison of a microprocessor system and a microcontroller system. Syllabus: : Introduction to, 8051 Microcontroller Architecture and an example of Microcontroller based stepper motor control system (only Block Diagram approach). (5 Hours) Introduction to A microcontroller

More information

SYSTEM BUS AND MOCROPROCESSORS HISTORY

SYSTEM BUS AND MOCROPROCESSORS HISTORY SYSTEM BUS AND MOCROPROCESSORS HISTORY Dr. M. Hebaishy momara@su.edu.sa http://colleges.su.edu.sa/dawadmi/fos/pages/hebaishy.aspx Digital Logic Design Ch1-1 SYSTEM BUS The CPU sends various data values,

More information

Calendar Description

Calendar Description ECE212 B1: Introduction to Microprocessors Lecture 1 Calendar Description Microcomputer architecture, assembly language programming, memory and input/output system, interrupts All the instructions are

More information

Chapter 1 : Introduction

Chapter 1 : Introduction Chapter 1 Introduction 1.1 Introduction A Microprocessor is a multipurpose programmable, clock driven, register based electronic device that reads binary instructions from a storage device called memory,

More information

MicroProcessor. MicroProcessor. MicroProcessor. MicroProcessor

MicroProcessor. MicroProcessor. MicroProcessor. MicroProcessor 1 2 A microprocessor is a single, very-large-scale-integration (VLSI) chip that contains many digital circuits that perform arithmetic, logic, communication, and control functions. When a microprocessor

More information

Introduction to Microprocessor

Introduction to Microprocessor Introduction to Microprocessor Slide 1 Microprocessor A microprocessor is a multipurpose, programmable, clock-driven, register-based electronic device That reads binary instructions from a storage device

More information

e-pg Pathshala Subject : Computer Science Paper: Embedded System Module: 8051 Architecture Module No: CS/ES/5 Quadrant 1 e-text

e-pg Pathshala Subject : Computer Science Paper: Embedded System Module: 8051 Architecture Module No: CS/ES/5 Quadrant 1 e-text e-pg Pathshala Subject : Computer Science Paper: Embedded System Module: 8051 Architecture Module No: CS/ES/5 Quadrant 1 e-text In this lecture the detailed architecture of 8051 controller, register bank,

More information

Fig 1. Block diagram of a microcomputer

Fig 1. Block diagram of a microcomputer Computer: A computer is a multipurpose programmable machine that reads binary instructions from its memory, accepts binary data as input,processes the data according to those instructions and provides

More information

Lecture-7 Characteristics of Memory: In the broad sense, a microcomputer memory system can be logically divided into three groups: 1) Processor

Lecture-7 Characteristics of Memory: In the broad sense, a microcomputer memory system can be logically divided into three groups: 1) Processor Lecture-7 Characteristics of Memory: In the broad sense, a microcomputer memory system can be logically divided into three groups: 1) Processor memory 2) Primary or main memory 3) Secondary memory Processor

More information

ENE 334 Microprocessors

ENE 334 Microprocessors Page 1 ENE 334 Microprocessors Lecture 7: MCS-51 Architecture I : Dejwoot KHAWPARISUTH http://webstaff.kmutt.ac.th/~dejwoot.kha/ ENE 334 MCS-51 Architecture I Page 2 Outlines: 8051 Microcontroller Hardware

More information

Ali Karimpour Associate Professor Ferdowsi University of Mashhad

Ali Karimpour Associate Professor Ferdowsi University of Mashhad AUTOMATIC CONTROL SYSTEMS Ali Karimpour Associate Professor Ferdowsi University of Mashhad Main reference: Christopher T. Kilian, (2001), Modern Control Technology: Components and Systems Publisher: Delmar

More information

1. INTRODUCTION TO MICROPROCESSOR AND MICROCOMPUTER ARCHITECTURE:

1. INTRODUCTION TO MICROPROCESSOR AND MICROCOMPUTER ARCHITECTURE: 1. INTRODUCTION TO MICROPROCESSOR AND MICROCOMPUTER ARCHITECTURE: A microprocessor is a programmable electronics chip that has computing and decision making capabilities similar to central processing unit

More information

Microprocessors I MICROCOMPUTERS AND MICROPROCESSORS

Microprocessors I MICROCOMPUTERS AND MICROPROCESSORS Microprocessors I Outline of the Lecture Microcomputers and Microprocessors Evolution of Intel 80x86 Family Microprocessors Binary and Hexadecimal Number Systems MICROCOMPUTERS AND MICROPROCESSORS There

More information

PART B UNIT II PART A

PART B UNIT II PART A SRM INSTITUTE OF SCIENCE AND TECHNOLOGY (Deemed University) DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK SUB : Microprocessor/CS201 YEAR/SEM : II/III UNIT I PART - A 1. Differentiate accumulator

More information

COMP2121: Microprocessors and Interfacing. Introduction to Microprocessors

COMP2121: Microprocessors and Interfacing. Introduction to Microprocessors COMP2121: Microprocessors and Interfacing Introduction to Microprocessors http://www.cse.unsw.edu.au/~cs2121 Lecturer: Hui Wu Session 2, 2017 1 1 Contents Processor architectures Bus Memory hierarchy 2

More information

Computer Systems Organization

Computer Systems Organization The IAS (von Neumann) Machine Computer Systems Organization Input Output Equipment Stored Program concept Main memory storing programs and data ALU operating on binary data Control unit interpreting instructions

More information

BASIC INTERFACING CONCEPTS

BASIC INTERFACING CONCEPTS Contents i SYLLABUS UNIT - I 8085 ARCHITECTURE Introduction to Microprocessors and Microcontrollers, 8085 Processor Architecture, Internal Operations, Instructions and Timings, Programming the 8085-Introduction

More information

MICROCONTROLLERS 8051

MICROCONTROLLERS 8051 MICROCONTROLLERS 8051 PART A Unit 1: Microprocessor and Microcontroller. Introduction, Microprocessor and Microcontrollers, A Microcontroller survey. RISC & CISC CPU Architectures, Harvard & Von Neumann

More information

Lecture 1. Course Overview and The 8051 Architecture

Lecture 1. Course Overview and The 8051 Architecture Lecture 1 Course Overview and The 8051 Architecture MCUniversity Program Lectures 8051 architecture t System overview of C8051F020 8051 instruction set System clock, crossbar and GPIO Assembler directives

More information

Understanding the basic building blocks of a microcontroller device in general. Knows the terminologies like embedded and external memory devices,

Understanding the basic building blocks of a microcontroller device in general. Knows the terminologies like embedded and external memory devices, Understanding the basic building blocks of a microcontroller device in general. Knows the terminologies like embedded and external memory devices, CISC and RISC processors etc. Knows the architecture and

More information

Introduction to Microcontrollers

Introduction to Microcontrollers Introduction to Microcontrollers Embedded Controller Simply an embedded controller is a controller that is embedded in a greater system. One can define an embedded controller as a controller (or computer)

More information

In this tutorial, we will discuss the architecture, pin diagram and other key concepts of microprocessors.

In this tutorial, we will discuss the architecture, pin diagram and other key concepts of microprocessors. About the Tutorial A microprocessor is a controlling unit of a micro-computer, fabricated on a small chip capable of performing Arithmetic Logical Unit (ALU) operations and communicating with the other

More information

SYLLABUS UNIT - I 8086/8088 ARCHITECTURE AND INSTRUCTION SET

SYLLABUS UNIT - I 8086/8088 ARCHITECTURE AND INSTRUCTION SET 1 SYLLABUS UNIT - I 8086/8088 ARCHITECTURE AND INSTRUCTION SET Intel 8086/8088 Architecture Segmented Memory, Minimum and Maximum Modes of Operation, Timing Diagram, Addressing Modes, Instruction Set,

More information

Computer Organization

Computer Organization INF 101 Fundamental Information Technology Computer Organization Assistant Prof. Dr. Turgay ĐBRĐKÇĐ Course slides are adapted from slides provided by Addison-Wesley Computing Fundamentals of Information

More information

For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to

For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. Contents at a Glance About the Author...xi

More information

Computer Hardware Requirements for ERTSs: Microprocessors & Microcontrollers

Computer Hardware Requirements for ERTSs: Microprocessors & Microcontrollers Lecture (4) Computer Hardware Requirements for ERTSs: Microprocessors & Microcontrollers Prof. Kasim M. Al-Aubidy Philadelphia University-Jordan DERTS-MSc, 2015 Prof. Kasim Al-Aubidy 1 Lecture Outline:

More information

ECE 471 Embedded Systems Lecture 2

ECE 471 Embedded Systems Lecture 2 ECE 471 Embedded Systems Lecture 2 Vince Weaver http://web.eece.maine.edu/~vweaver vincent.weaver@maine.edu 7 September 2018 Announcements Reminder: The class notes are posted to the website. HW#1 will

More information

7/28/ Prentice-Hall, Inc Prentice-Hall, Inc Prentice-Hall, Inc Prentice-Hall, Inc Prentice-Hall, Inc.

7/28/ Prentice-Hall, Inc Prentice-Hall, Inc Prentice-Hall, Inc Prentice-Hall, Inc Prentice-Hall, Inc. Technology in Action Technology in Action Chapter 9 Behind the Scenes: A Closer Look a System Hardware Chapter Topics Computer switches Binary number system Inside the CPU Cache memory Types of RAM Computer

More information

Ali Karimpour Associate Professor Ferdowsi University of Mashhad

Ali Karimpour Associate Professor Ferdowsi University of Mashhad AUTOMATIC CONTROL SYSTEMS Ali Karimpour Associate Professor Ferdowsi University of Mashhad Main reference: Christopher T. Kilian, (2001), Modern Control Technology: Components and Systems Publisher: Delmar

More information

5 Computer Organization

5 Computer Organization 5 Computer Organization 5.1 Foundations of Computer Science ã Cengage Learning Objectives After studying this chapter, the student should be able to: q List the three subsystems of a computer. q Describe

More information

Microcomputer Architecture and Programming

Microcomputer Architecture and Programming IUST-EE (Chapter 1) Microcomputer Architecture and Programming 1 Outline Basic Blocks of Microcomputer Typical Microcomputer Architecture The Single-Chip Microprocessor Microprocessor vs. Microcontroller

More information

EMBEDDED SYSTEM BASICS AND APPLICATION

EMBEDDED SYSTEM BASICS AND APPLICATION EMBEDDED SYSTEM BASICS AND APPLICATION Dr.Syed Ajmal IIT- Robotics TOPICS TO BE DISCUSSED System Embedded System Components Classifications Processors Other Hardware Software Applications 2 INTRODUCTION

More information

MICROPROCESSOR AND MICROCONTROLLER BASED SYSTEMS

MICROPROCESSOR AND MICROCONTROLLER BASED SYSTEMS MICROPROCESSOR AND MICROCONTROLLER BASED SYSTEMS UNIT I INTRODUCTION TO 8085 8085 Microprocessor - Architecture and its operation, Concept of instruction execution and timing diagrams, fundamentals of

More information

machine cycle, the CPU: (a) Fetches an instruction, (b) Decodes the instruction, (c) Executes the instruction, and (d) Stores the result.

machine cycle, the CPU: (a) Fetches an instruction, (b) Decodes the instruction, (c) Executes the instruction, and (d) Stores the result. Central Processing Unit (CPU) A processor is also called the CPU, and it works hand in hand with other circuits known as main memory to carry out processing. The CPU is the "brain" of the computer; it

More information

Advanced Parallel Architecture Lesson 3. Annalisa Massini /2015

Advanced Parallel Architecture Lesson 3. Annalisa Massini /2015 Advanced Parallel Architecture Lesson 3 Annalisa Massini - 2014/2015 Von Neumann Architecture 2 Summary of the traditional computer architecture: Von Neumann architecture http://williamstallings.com/coa/coa7e.html

More information

Computers Are Your Future

Computers Are Your Future Computers Are Your Future 2008 Prentice-Hall, Inc. Computers Are Your Future Chapter 6 Inside the System Unit 2008 Prentice-Hall, Inc. Slide 2 What You Will Learn... Understand how computers represent

More information

MARIE: An Introduction to a Simple Computer

MARIE: An Introduction to a Simple Computer MARIE: An Introduction to a Simple Computer 4.2 CPU Basics The computer s CPU fetches, decodes, and executes program instructions. The two principal parts of the CPU are the datapath and the control unit.

More information

Week 1. Introduction to Microcomputers and Microprocessors, Computer Codes, Programming, and Operating Systems

Week 1. Introduction to Microcomputers and Microprocessors, Computer Codes, Programming, and Operating Systems Week 1 Introduction to Microcomputers and Microprocessors, Computer Codes, Programming, and Operating Systems 2 Introduction to Microcomputers/ Stored Program C 3 Stored Program Concept There are three

More information

Microcontroller & Interfacing

Microcontroller & Interfacing Course Title Course Code Microcontroller & Interfacing EC406 Lecture : 3 Course Credit Practical : 1 Tutorial : 0 Total : 4 Course Objective At the end of the course the students will be able to Understand

More information

PC I/O. May 7, Howard Huang 1

PC I/O. May 7, Howard Huang 1 PC I/O Today wraps up the I/O material with a little bit about PC I/O systems. Internal buses like PCI and ISA are critical. External buses like USB and Firewire are becoming more important. Today also

More information

Chapter 2 Logic Gates and Introduction to Computer Architecture

Chapter 2 Logic Gates and Introduction to Computer Architecture Chapter 2 Logic Gates and Introduction to Computer Architecture 2.1 Introduction The basic components of an Integrated Circuit (IC) is logic gates which made of transistors, in digital system there are

More information

Computer Organization and Microprocessors SYLLABUS CHAPTER - 1 : BASIC STRUCTURE OF COMPUTERS CHAPTER - 3 : THE MEMORY SYSTEM

Computer Organization and Microprocessors SYLLABUS CHAPTER - 1 : BASIC STRUCTURE OF COMPUTERS CHAPTER - 3 : THE MEMORY SYSTEM i SYLLABUS UNIT - 1 CHAPTER - 1 : BASIC STRUCTURE OF COMPUTERS Computer Types, Functional Units, Basic Operational Concepts, Bus Structures, Software, Performance, Multiprocessors and Multicomputers, Historical

More information

Question Bank Microprocessor and Microcontroller

Question Bank Microprocessor and Microcontroller QUESTION BANK - 2 PART A 1. What is cycle stealing? (K1-CO3) During any given bus cycle, one of the system components connected to the system bus is given control of the bus. This component is said to

More information

Sencer Yeralan and Helen Emery Gainesville, Florida January 2000

Sencer Yeralan and Helen Emery Gainesville, Florida January 2000 Preface This book is an outgrowth of the notes and experiments developed for the graduate classes at the University of Florida. It is intended for students, hobbyists, engineers, and scientists who would

More information

Processing Unit CS206T

Processing Unit CS206T Processing Unit CS206T Microprocessors The density of elements on processor chips continued to rise More and more elements were placed on each chip so that fewer and fewer chips were needed to construct

More information

Chapter 7: Processor and Memory

Chapter 7: Processor and Memory Slide 1/27 Learning Objectives In this chapter you will learn about: Internal structure of processor Memory structure Determining the speed of a processor Different types of processors available Determining

More information

CHAPTER 4 MARIE: An Introduction to a Simple Computer

CHAPTER 4 MARIE: An Introduction to a Simple Computer CHAPTER 4 MARIE: An Introduction to a Simple Computer 4.1 Introduction 177 4.2 CPU Basics and Organization 177 4.2.1 The Registers 178 4.2.2 The ALU 179 4.2.3 The Control Unit 179 4.3 The Bus 179 4.4 Clocks

More information

Microprocessor and Microcontroller question bank. 1 Distinguish between microprocessor and microcontroller.

Microprocessor and Microcontroller question bank. 1 Distinguish between microprocessor and microcontroller. Course B.E(EEE) Batch 2015 Semester V Subject code subject Name UAEE503 Microprocessor and Microcontroller question bank UNIT-1 Architecture of a Microprocessor PART-A Marks: 2 1 Distinguish between microprocessor

More information

Computer Organization and Assembly Language (CS-506)

Computer Organization and Assembly Language (CS-506) Computer Organization and Assembly Language (CS-506) Muhammad Zeeshan Haider Ali Lecturer ISP. Multan ali.zeeshan04@gmail.com https://zeeshanaliatisp.wordpress.com/ Lecture 2 Memory Organization and Structure

More information

An Overview of Microprocessor The first question comes in a mind "What is a microprocessor?. Let us start with a more familiar term computer. A digital computer is an electronic machine capable of quickly

More information

Chapter One. Introduction to Computer System

Chapter One. Introduction to Computer System Principles of Programming-I / 131101 Prepared by: Dr. Bahjat Qazzaz -------------------------------------------------------------------------------------------- Chapter One Introduction to Computer System

More information

Concept of Memory. The memory of computer is broadly categories into two categories:

Concept of Memory. The memory of computer is broadly categories into two categories: Concept of Memory We have already mentioned that digital computer works on stored programmed concept introduced by Von Neumann. We use memory to store the information, which includes both program and data.

More information

Instruction Register. Instruction Decoder. Control Unit (Combinational Circuit) Control Signals (These signals go to register) The bus and the ALU

Instruction Register. Instruction Decoder. Control Unit (Combinational Circuit) Control Signals (These signals go to register) The bus and the ALU Hardwired and Microprogrammed Control For each instruction, the control unit causes the CPU to execute a sequence of steps correctly. In reality, there must be control signals to assert lines on various

More information

ECED3204: Microprocessor Part I--Introduction

ECED3204: Microprocessor Part I--Introduction ECED3204: Microprocessor Part I--Introduction Jason J. Gu Department of 1 Outline i. Computer ii. Processor iii. Embedded System iv. Memory v. Program Execution VI. VII. VIII. IX. AVR AVR Memory AVR CPU

More information

5 Computer Organization

5 Computer Organization 5 Computer Organization 5.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: List the three subsystems of a computer. Describe the

More information

Lecture Objectives. Introduction to Computing Chapter 0. Topics. Numbering Systems 04/09/2017

Lecture Objectives. Introduction to Computing Chapter 0. Topics. Numbering Systems 04/09/2017 Lecture Objectives Introduction to Computing Chapter The AVR microcontroller and embedded systems using assembly and c Students should be able to: Convert between base and. Explain the difference between

More information

Digital System Design Using Verilog. - Processing Unit Design

Digital System Design Using Verilog. - Processing Unit Design Digital System Design Using Verilog - Processing Unit Design 1.1 CPU BASICS A typical CPU has three major components: (1) Register set, (2) Arithmetic logic unit (ALU), and (3) Control unit (CU) The register

More information

INTEL Architectures GOPALAKRISHNAN IYER FALL 2009 ELEC : Computer Architecture and Design

INTEL Architectures GOPALAKRISHNAN IYER FALL 2009 ELEC : Computer Architecture and Design INTEL Architectures GOPALAKRISHNAN IYER FALL 2009 GBI0001@AUBURN.EDU ELEC 6200-001: Computer Architecture and Design Silicon Technology Moore s law Moore's Law describes a long-term trend in the history

More information

Computer Systems Architecture

Computer Systems Architecture Computer Systems Architecture Guoping Qiu School of Computer Science The University of Nottingham http://www.cs.nott.ac.uk/~qiu 1 The World of Computers Computers are everywhere Cell phones Game consoles

More information

Computer Organization

Computer Organization Objectives 5.1 Chapter 5 Computer Organization Source: Foundations of Computer Science Cengage Learning 5.2 After studying this chapter, students should be able to: List the three subsystems of a computer.

More information

MICROPROCESSOR MICROPROCESSOR. From the above description, we can draw the following block diagram to represent a microprocessor based system: Output

MICROPROCESSOR MICROPROCESSOR. From the above description, we can draw the following block diagram to represent a microprocessor based system: Output 8085 SATISH CHANDRA What is a Microprocessor? The word comes from the combination micro and processor. Processor means a device that processes whatever. In this context, processor means a device that processes

More information

Chapter 1 Microprocessor architecture ECE 3120 Dr. Mohamed Mahmoud http://iweb.tntech.edu/mmahmoud/ mmahmoud@tntech.edu Outline 1.1 Computer hardware organization 1.1.1 Number System 1.1.2 Computer hardware

More information

Lecture 2 Microcomputer Organization: Fig.1.1 Basic Components of Microcomputer

Lecture 2 Microcomputer Organization: Fig.1.1 Basic Components of Microcomputer Lecture 2 Microcomputer Organization: As discussed in previous lecture microprocessor is a central processing unit (CPU) with its related timing functions on a single chip. A microprocessor combined with

More information

Microcontrollers and Applications. Revised Edition

Microcontrollers and Applications. Revised Edition Microcontrollers and Applications Revised Edition Microcontrollers and Applications Revised Edition Dr. Ramani Kalpathi Mr. Ganesh Raja Powerso Systems Chennai Sanguine Technical Publishers Bangalore -

More information

b. List different system buses of 8085 microprocessor and give function of each bus. (8) Answer:

b. List different system buses of 8085 microprocessor and give function of each bus. (8) Answer: Q.2 a. Discuss and differentiate between a Microprocessor and a Microcontroller. Microprocessor is an IC which has only the CPU inside them i.e. only the processing powers such as Intel s Pentium 1,2,3,4,

More information

INTRODUCTION OF MICROPROCESSOR& INTERFACING DEVICES Introduction to Microprocessor Evolutions of Microprocessor

INTRODUCTION OF MICROPROCESSOR& INTERFACING DEVICES Introduction to Microprocessor Evolutions of Microprocessor Course Title Course Code MICROPROCESSOR & ASSEMBLY LANGUAGE PROGRAMMING DEC415 Lecture : Practical: 2 Course Credit Tutorial : 0 Total : 5 Course Learning Outcomes At end of the course, students will be

More information

Computer Architecture Dr. Charles Kim Howard University

Computer Architecture Dr. Charles Kim Howard University EECE416 Microcomputer Fundamentals Computer Architecture Dr. Charles Kim Howard University 1 Computer Architecture Computer Architecture Art of selecting and interconnecting hardware components to create

More information

EE 3170 Microcontroller Applications

EE 3170 Microcontroller Applications EE 3170 Microcontroller Applications Lecture 4 : Processors, Computers, and Controllers - 1.2 (reading assignment), 1.3-1.5 Based on slides for ECE3170 by Profs. Kieckhafer, Davis, Tan, and Cischke Outline

More information

Von Neumann architecture. The first computers used a single fixed program (like a numeric calculator).

Von Neumann architecture. The first computers used a single fixed program (like a numeric calculator). Microprocessors Von Neumann architecture The first computers used a single fixed program (like a numeric calculator). To change the program, one has to re-wire, re-structure, or re-design the computer.

More information

The Memory Component

The Memory Component The Computer Memory Chapter 6 forms the first of a two chapter sequence on computer memory. Topics for this chapter include. 1. A functional description of primary computer memory, sometimes called by

More information

Memory Overview. Overview - Memory Types 2/17/16. Curtis Nelson Walla Walla University

Memory Overview. Overview - Memory Types 2/17/16. Curtis Nelson Walla Walla University Memory Overview Curtis Nelson Walla Walla University Overview - Memory Types n n n Magnetic tape (used primarily for long term archive) Magnetic disk n Hard disk (File, Directory, Folder) n Floppy disks

More information

ADVANCED COMPUTER ARCHITECTURE TWO MARKS WITH ANSWERS

ADVANCED COMPUTER ARCHITECTURE TWO MARKS WITH ANSWERS ADVANCED COMPUTER ARCHITECTURE TWO MARKS WITH ANSWERS 1.Define Computer Architecture Computer Architecture Is Defined As The Functional Operation Of The Individual H/W Unit In A Computer System And The

More information

FIFTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLOGY-MARCH 2014 EMBEDDED SYSTEMS (Common for CT,CM) [Time: 3 hours] (Maximum marks : 100)

FIFTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLOGY-MARCH 2014 EMBEDDED SYSTEMS (Common for CT,CM) [Time: 3 hours] (Maximum marks : 100) (Revision-10) FIFTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLOGY-MARCH 2014 EMBEDDED SYSTEMS (Common for CT,CM) [Time: 3 hours] (Maximum marks : 100) PART-A (Maximum marks : 10) I. Answer all

More information

ECE 1160/2160 Embedded Systems Design. Midterm Review. Wei Gao. ECE 1160/2160 Embedded Systems Design

ECE 1160/2160 Embedded Systems Design. Midterm Review. Wei Gao. ECE 1160/2160 Embedded Systems Design ECE 1160/2160 Embedded Systems Design Midterm Review Wei Gao ECE 1160/2160 Embedded Systems Design 1 Midterm Exam When: next Monday (10/16) 4:30-5:45pm Where: Benedum G26 15% of your final grade What about:

More information

Latches. IT 3123 Hardware and Software Concepts. Registers. The Little Man has Registers. Data Registers. Program Counter

Latches. IT 3123 Hardware and Software Concepts. Registers. The Little Man has Registers. Data Registers. Program Counter IT 3123 Hardware and Software Concepts Notice: This session is being recorded. CPU and Memory June 11 Copyright 2005 by Bob Brown Latches Can store one bit of data Can be ganged together to store more

More information

1. Define Peripherals. Explain I/O Bus and Interface Modules. Peripherals: Input-output device attached to the computer are also called peripherals.

1. Define Peripherals. Explain I/O Bus and Interface Modules. Peripherals: Input-output device attached to the computer are also called peripherals. 1. Define Peripherals. Explain I/O Bus and Interface Modules. Peripherals: Input-output device attached to the computer are also called peripherals. A typical communication link between the processor and

More information

UNIT V MICRO CONTROLLER PROGRAMMING & APPLICATIONS TWO MARKS. 3.Give any two differences between microprocessor and micro controller.

UNIT V MICRO CONTROLLER PROGRAMMING & APPLICATIONS TWO MARKS. 3.Give any two differences between microprocessor and micro controller. UNIT V -8051 MICRO CONTROLLER PROGRAMMING & APPLICATIONS TWO MARKS 1. What is micro controller? Micro controller is a microprocessor with limited number of RAM, ROM, I/O ports and timer on a single chip

More information

Chapter 5 Internal Memory

Chapter 5 Internal Memory Chapter 5 Internal Memory Memory Type Category Erasure Write Mechanism Volatility Random-access memory (RAM) Read-write memory Electrically, byte-level Electrically Volatile Read-only memory (ROM) Read-only

More information

William Stallings Computer Organization and Architecture 8th Edition. Chapter 5 Internal Memory

William Stallings Computer Organization and Architecture 8th Edition. Chapter 5 Internal Memory William Stallings Computer Organization and Architecture 8th Edition Chapter 5 Internal Memory Semiconductor Memory The basic element of a semiconductor memory is the memory cell. Although a variety of

More information

SAE5C Computer Organization and Architecture. Unit : I - V

SAE5C Computer Organization and Architecture. Unit : I - V SAE5C Computer Organization and Architecture Unit : I - V UNIT-I Evolution of Pentium and Power PC Evolution of Computer Components functions Interconnection Bus Basics of PCI Memory:Characteristics,Hierarchy

More information

INTRODUCTION TO MICROPROCESSORS

INTRODUCTION TO MICROPROCESSORS INTRODUCTION TO MICROPROCESSORS Richa Upadhyay Prabhu NMIMS s MPSTME richa.upadhyay@nmims.edu January 7, 2016 Richa Upadhyay Prabhu (MPSTME) INTRODUCTION January 7, 2016 1 / 63 Course Design Prerequisite:

More information

Components of a personal computer

Components of a personal computer Components of a personal computer Computer systems ranging from a controller in a microwave oven to a large supercomputer contain components providing five functions. A typical personal computer has hard,

More information

EE 308: Microcontrollers

EE 308: Microcontrollers EE 308: Microcontrollers AVR Architecture Aly El-Osery Electrical Engineering Department New Mexico Institute of Mining and Technology Socorro, New Mexico, USA January 23, 2018 Aly El-Osery (NMT) EE 308:

More information

MARIE: An Introduction to a Simple Computer

MARIE: An Introduction to a Simple Computer MARIE: An Introduction to a Simple Computer Outline Learn the components common to every modern computer system. Be able to explain how each component contributes to program execution. Understand a simple

More information

Computer Systems. Binary Representation. Binary Representation. Logical Computation: Boolean Algebra

Computer Systems. Binary Representation. Binary Representation. Logical Computation: Boolean Algebra Binary Representation Computer Systems Information is represented as a sequence of binary digits: Bits What the actual bits represent depends on the context: Seminar 3 Numerical value (integer, floating

More information

Homeschool Enrichment. The System Unit: Processing & Memory

Homeschool Enrichment. The System Unit: Processing & Memory Homeschool Enrichment The System Unit: Processing & Memory Overview This chapter covers: How computers represent data and programs How the CPU, memory, and other components are arranged inside the system

More information

COURSE NAME : ELECTRICAL ENGINEERING GROUP COURSE CODE : EE/EP SEMESTER : FIFTH SUBJECT TITLE : Microcontroller and Applications (Elective I for EP) SUBJECT CODE : Teaching and Examination Scheme: Teaching

More information

COSC 243. Computer Architecture 1. COSC 243 (Computer Architecture) Lecture 6 - Computer Architecture 1 1

COSC 243. Computer Architecture 1. COSC 243 (Computer Architecture) Lecture 6 - Computer Architecture 1 1 COSC 243 Computer Architecture 1 COSC 243 (Computer Architecture) Lecture 6 - Computer Architecture 1 1 Overview Last Lecture Flip flops This Lecture Computers Next Lecture Instruction sets and addressing

More information

Advanced Parallel Architecture Lesson 3. Annalisa Massini /2015

Advanced Parallel Architecture Lesson 3. Annalisa Massini /2015 Advanced Parallel Architecture Lesson 3 Annalisa Massini - Von Neumann Architecture 2 Two lessons Summary of the traditional computer architecture Von Neumann architecture http://williamstallings.com/coa/coa7e.html

More information

AVR Microcontrollers Architecture

AVR Microcontrollers Architecture ก ก There are two fundamental architectures to access memory 1. Von Neumann Architecture 2. Harvard Architecture 2 1 Harvard Architecture The term originated from the Harvard Mark 1 relay-based computer,

More information

e-pg Pathshala Subject : Computer Science Paper: Embedded System Module: Introduction to Computing Module No: CS/ES/1 Quadrant 1 e-text

e-pg Pathshala Subject : Computer Science Paper: Embedded System Module: Introduction to Computing Module No: CS/ES/1 Quadrant 1 e-text e-pg Pathshala Subject : Computer Science Paper: Embedded System Module: Introduction to Computing Module No: CS/ES/1 Quadrant 1 e-text About the course : In this digital world, embedded systems are more

More information