A Laboratory Manual for

Microprocessor Interfacing Laboratory (210254)

Semester – IV

(Computer Engineering)

Bachelor Degree in Engineering

UNIVERSITY OF PUNE, GANESHKHIND

SNJB’s KBJ College Of Engineering, Chandwad

DEPARTMENT OF COMPUTER ENGINEERING LABORATORY MANUAL DEVELOPMENT PROJECT

Designations Team for design

Project Institution Shri Neminath Jain Bramhacharyashram’s SNJB’s KBJ College of Engineering, Neminagar, Chandwad -423101.

Project Commencement Dec 2012

Head Of Institution Prof. J. J. Chopade SNJB’s KBJ College of Engineering, Neminagar, Chandwad -423101.

Chief Project Coordinator Mr. M .R Sanghavi Head,DepartmentOfComputerEngineering, SNJB’s KBJ College of Engineering, Neminagar, Chandwad -423101.

Project Coordinator Ms. K. S. Kotecha AssociateProfessor,DepartmentOfComputer Engineering,KBJ College of Engineering, Neminagar, Chandwad -423101.

Subject Experts 1. Mr.V.V Agrawal SNJB’s KBJ College of Engineering, Neminagar, Chandwad -423101

2. Mr.R.R.Bhandari SNJB’s KBJ College of Engineering, Neminagar, Chandwad -423101 JB’s KBJ College Of Engineering, Chandwad

DEPARTMENT OF COMPUTER ENGINEERING

Certificate

This is Certify that Mr/Ms. Com______puter Roll No _of

Fourth Semester of BacMicroprocessorhelor Engineer Interfacinging in Laboratoryhas completed the term work satisfactorily in in the Academic

Year 20_ to 20_ as prescribed in the curriculum.

Place

Date: Exam Seat No.

Subject Teacher Head of Department Principal Stamp of Institution List of Experiment and Record of Progressive Assessment

Sr. Name of Experiment Pag Date of Date of Assessment Sign of e No Performance Submission Marks Teacher Write N program (ALP) to add array of o 1 N hexadecimal numbers stored in the memory. Accept input from the user. Write 8086 ALP to perform non-overlapped and overlapped 2 block transfer (with and without string specific instructions). Block containing data can be defined in the data segment. Write X86 ALP to convert 4- digit Hex number into its 3 equivalent BCD number and 5- digit BCD number into its equivalent HEX number. Make your program user friendly to accept the choice from user for: (a)HEX to BCD b) BCD to HEX (c) EXIT. Display proper strings to prompt the user while accepting the input and displaying the result. Write 8086 ALP for the following operations on the string 4 entered by the user. a) Calculate Length of the string b) Reverse the string c) Check whether the string is palindrome OR Make your program user friendly by providing MENU like: (a) Enter the string b) Calculate length of string c) Reverse string d) Check palindrome e) Exit Display appropriate messages to prompt the user while accepting the input and displaying the result. Write 8086 ALP to perform string manipulation. The strings 5 to be accepted from the user is to be stored in data segment of program_l and write FAR PROCEDURES in code segment program_2 for following operations on the string: (a) Concatenation of two strings (b) Number of occurrences of a sub-string in the given string Use PUBLIC and EXTERN directive. Create .OBJ files of both the modules and link them to create an EXE file. Write X86 ALP to perform multiplication of two 8-bit 6 hexadecimal numbers. Use successive addition and add and shift method. Accept input from the user. Write 8087ALP to obtain: i) Mean ii) Variance iii) Standard 7 Deviation For a given set of data elements defined in data segment. Also display result. Write 8086 ALP to convert an analog signal in the range of 0V 8 to 5V to its corresponding digital signal using successive approximation ADC and dual slope ADC. Find resolution used in both the ADC's and compare the results. Write 8086 ALP to interface DAC and generate following 9 waveforms on oscilloscope, (i) Square wave - Variable Duty Cycle and Frequency. (ii) Ramp wave - Variable direction, (iii) Trapezoidal wave (iv) Stair case wave Write 8086 ALP to program 8253 in Mode 0, modify the program for hardware retriggerable 10.Monoshot mode. Generate a square wave with a pulse of 1 ms. Comment on the difference between Hardware Triggered and software triggered strobe mode. Observe the waveform at GATE & out pin of 1C 8254 on CRO 11 Perform an experiment to establish communication between two 8251 systems A and B. Program 8251 system A in asynchronous transmitter mode and 8251 system B in asynchronous receiver mode. Write an ALP to transmit the data from system A and receive the data at system B. The requirements are as follows: Transmission: • message is stored as ASCII characters in the memory. • message specifies the number of characters to be transmitted as the first byte. Reception: • Message is retrieved and stored in the memory. • Successful reception should be indicated.

12 Write a TSR program in 8086 ALP to implement Real Time Clock (RTC). Read the Real Time from CMOS chip by suitable INT and FUNCTION and display the RTC at the bottom right corner on the screen. Access the video RAM directly in your routine. 13 Study Assignment Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Att (2) Perm(5) Oral(3) Total(10) Sign with Date Assignment 1

Problem Definition:

Write X86/64 Assembly language program (ALP) to add array of N hexadecimal numbers stored 1.1 Prerequisites: Concepts of in the memory. Accept input from the user.  Program  Algorithm  Registers  Assembly language  Assembler  Array & its scope

1.2 Learning Objectives:  Understand the implementation  Understand the implementation of the arithmetic instruction of 80386.

1.3 New concepts:- 1.3.1 What is ALP?  Assembly language Program is mnemonic representation of .

1.3.2 Which assembler used in execution of ALP?  Three assemblers available for assembling the programs for IBM-PC are: 1. Microsoft Micro Assembler(MASM) 2. Borland (TASM) 3. Net wide Assembler (NASM)

1.4 Theory 1.4.1

Assemblydata Basic Syntax An assemblybss program can be divided into three sections: 1. The text section 2. The section 3. The section

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 7 Microprocessor and Interfacing Laboratory Second Year Computer Engineering The data Section data

The section is used for declaring initialized data or constants. This data does not change at runtime.section Youcan.data declare various constant values, file names or buffer size etc. in this section. The syntax for declaring data section is: The bss Section section .bss The bss section is used for declaring variables. The syntax for declaring bss section is: The text section

The text section is used for keeping the actual code. This section must begin with the declarationglobal main, sectionwhich tells .text the kernel where the program execution begins. Theglobal syntax main for declaring text section is: main:

Assembly Language Statements

Assembly language programs consist of three types of statements: 1. Executable instructions or instructions 2. Assembler directives or pseudo-ops 3. Macros executable instructions instructions operation code The or simply tell the processor what to do. Each instructionassembler consists directives of an pseudo-ops(). Each executable instruction generates one machine language instruction. The or tell the assembler about the various aspects of the Macrosassembly process. These are non-executable and do not generate machine language instructions. Assemblyare System basically Calls a text substitution mechanism.

System calls are APIs for the interface between user space and kernel space. We are using the system calls sys_write and sys_exit for writing into the screen and exiting from the program Linuxrespectively. System Calls

You can make use of Linux system calls in your assembly programs. You need to take the  following steps for using Linux system calls in your program: Put the system call number in the EAX register. SNJBStore’s Late theSau. arguments KBJ COLL toEGE the systemOF ENG callINE inE RtheING registers EBX, ECX, etc. Page 8 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

  Call the relevant interrupt (80h) The result is usually returned in the EAX register There are six registers that stores the arguments of the system call used. These are the EBX, ECX, EDX, ESI, EDI, and EBP. These registers take the consecutive arguments, starting with the EBX Theregister. following If there code are snippetmore than shows six arguments the use of thenthe system the memory call sys_exit: location of the first argument is stored in the EBX register.

The followingMOV EAX code, 1 snippet; system shows call numberthe use (sys_exit)of the system call sys_write: INT 0x80 ; call kernel

MOV EDX, 4 ; message length MOV ECX, MSG ; message to write MOV EBX,1 ; file descriptor (stdout) MOV EAX,4 ; system call number (sys_write) INT 0x80 ; call kernel The following table shows some of the system calls:

Assembly Variables define directives

NASM provides various for reserving storage space for variables. The define Assembler directive is used for allocation of storage space. It can be used to reserve as well as initialize one or more bytes.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 9 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Allocating Storage Space for Initialized Data

There are five basic forms of the define directive:

Allocating Storage Space for Uninitialized Data

The reserve directives are used for reserving space for uninitialized data. The reserve directives take a single operand that specifies the number of units of space to be reserved. Each define directive has a related reserve directive. There are five basic forms of the reserve directive:

1.6 Instructions needed: 1. MOV-Copies byte or word from specified source to specified destination 2. ROR-Rotates bits of byte or word right, LSB to MSB and to CF 3. AND-AND each bit in a byte or word with corresponding bit in another byte or word 4. INC-Increments specified byte/word by 1 5. DEC-Decrements specified byte/word by 1 6. JNZ-Jumps if not equal to Zero 7. JNC-Jumps if no carry is generated 8. CMP-Compares to specified bytes or words 9. JBE-Jumps if below of equal 10. ADD-Adds specified byte to byte or word to word 11. CALL-Transfers the control from calling program to procedure

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 10 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

1.7 Algorithm: 1. Start 2. Initialize data section 3. Load counter with number of elements for addition 4. Locate first location of array of numbers in a pointer register 5. Initialize result-low and result-high to 00H 6. Scan the number from user and convert it to hex 7. Increment location of pointer register 8. Decrement counter 9. Jump to step 6 if counter is not zero 10. Locate first location of array of numbers in a pointer register 11. Initialize counter with number of elements for addition 12. Add the element of array pointed by pointer register 13. Check the carry of addition. If carry is generated then go to step 14 else go to step15 14. Increment result-high register 15. Increment pointer register to array 16. Decrement counter 17. Jump to step 12 if counter is not equal to zero 18. Display the content of Result-High as carry of addition by converting hex to ASCII 19. Display the content of Result-Low as result of addition by converting hex to ASCII 20. Stop

1.5 Working with ALP in NASM

NASM - The

1. an 80x86 and x86-64 assembler designed for portability and modularity 2. Supports a range of object file formats - a.out, ELF, COFF, OBJ, WIN32, WIN64, etc. 3. Default format - binary can read, combine and write object files in many different formats such as COFF, ELF, etc 4. Different formats may be linked together to produce any available kind of object file. 5. Elf – executable & linkable file format of object file & executable file – supported by Linux

Commands • To assemble nasm –f elf64 hello.asm -o hello.o • To link ld –o hello hello.o • To execute - ./hello

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 11 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

1.8 Theory Questions: 1. Explain in detail address calculation of 16 bit and 32 bit architecture? 2. Explain in detail register model of 16 bit, 32 bit and 64 bit architecture? 3. Describe execution of CALL instruction 4. What do you mean by is assembler directives? Explain assembler directives. 5. Explain Macro and Procedure? 6. Explain advance features of i7 processor? 7. What is multi core Architecture?

1.9 Oral Questions: 1. Explain sys_exit,sys_write,sys_read? 2. Explain .data,.bss,.text ? 3. Explain how to run a program in NASM? 4. Explain RESD,RESW,RESB,RESQ ?

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 12 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Att (2) Perm(5) Oral(3) Total(10) Sign with Date

Assignment 2

Problem Definition: Write 8086 ALP to perform non-overlapped and overlapped block transfer (with and without string specific instructions). Block containing data can be defined in the data segment 2.1 Prerequisites: Concepts of  Memory  Block operations

2.2 Learning Objectives:  Understand the memory addressing  Understand the localization of data in memory.

2.3 Theory 2.3.1Registers Registers are places in the CPU where a number can be stored and manipulated. There are three sizes of registers: 8-bit, 16-bit and on 386 and above 32-bit. There are four different types of registers:

1. General Purpose Registers, 2. Segment Registers, 3. Index Registers, 4. Stack Registers. 2.3.1.1 General Registers – Following are the registers that are used for general purposes in 8086 AX accumulator (16 bit) AH accumulator high-order byte (8 bit) AL accumulator low-order byte (8 bit) BX accumulator (16 bit) BH accumulator high-order byte (8 bit) BL accumulator low-order byte (8 bit)

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 13 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

CX count and accumulator (16 bit) CH count high order byte (8 bit) CL count low order byte (8 bit) DX data and I/O address (16 bit) DH data high order byte (8 bit) DL data low order byte (8 bit)

2.3.1.2 Segment Registers - These registers are used to calculate 20 bit address from 16 bit registers. CS code segment (16 bit) DS data segment (16 bit) SS stack segment (16 bit) ES extra segment (16 bit)

2.3.1.3 Index Registers - These registers are used with the string instructions. DI destination index (16 bit) SI source index (16 bit)

2.3.1.4 Pointers - These registers are used with the segment register to obtain 20 bit addresses SP stack pointer (16 bit) BP base pointer (16 bit) IP instruction pointer (16 bit)

CS, Code Segment Used to “point” to Instructions Determines a Memory Address (along with IP) Segmented Address written as CS:IP

DS, Data Segment Used to “point” to Data Determines Memory Address (along with other registers) ES, Extra Segment allows 2 Data Address Registers

SS, Stack Segment Used to “point” to Data in Stack Structure (LIFO)

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 14 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Used with SP or BP SS:SP or SS:BP are valid Segmented Addresses IP, Instruction Pointer Used to “point” to Instructions Determines a Memory Address (along with CS) Segmented Address written as CS:IP

SI, Source Index; DI, Destination Index Used to “point” to Data Determines Memory Address (along with other registers) DS, ES commonly used

SP, Stack Pointer; BP, Base Pointer Used to “point” to Data in Stack Structure (LIFO) Used with SS SS:SP or SS:BP are valid Segmented Addresses

2.3.2 Memory address calculations The 8086 uses a 20 bit address bus but the registers are only sixteen bit. To derive twenty bit addresses from the registers two registers are combined. Every memory reference uses one of the four segment registers plus an offset and/or a base pointer and/or a index register. The segment register is multiplied by sixteen (shifted to the left four bits) and added to the sixteen bit result of the offset calculation.

Figure 1Diagrammatic Representation of Address calculation The 8086 provides four segment registers for address calculations. Each segment register is assigned a different task. The code segment register is always used with the instruction

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 15 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

pointer (also called the ) to point to the instruction that is to be executed next. The stack segment register is always used with the stack pointer to point to the last value pushed onto the stack. The extra segment is general purpose segment register. The data segment register is the default register to calculate data operations, this can be over ridden by specifying the segment register. For example mov ax,var1 would use the offset var1 and the data segment to calculate the memory reference but mov ax,ss:var1 would use the offset var1 and the stack segment register to calculate the memory reference.

The offset can be calculated in a number of ways. Their are three elements that can make up an offset. The first element is a base register, this can be one of the BX of BP registers (the BP register defaults to the stack segment). The second element is one of the index register, SI or DI. The third element is a displacement. A displacement can be a numerical value or an offset to a label. An offset can contain one to three of these elements, making a total of sixteen possibilities.

BX SI or + or + Displacement BP DI (base) (index) The offset to a label in calculated using the assembler directive OFFSET. This directive makes the assembler calculate the distant from the start of the segment that the label resides in to the label.

2.3.3 Memory Segmentation x86 Memory Partitioned into Segments – 8086: maximum size is 64K (16-bit index reg.) – 8086: can have 4 active segments (CS, SS, DS, ES) – 8086: 2-data; 1-code; 1-stack – x386: maximum size is 4GB (32-bit index reg.) – x386: can have 6 active segments (4-data; FS, GS)

Why have segmented memory? Other microprocessors could only address 64K since they only had a single 16-bit MAR (or smaller). Segments allowed computers to be built that could use more than 64K memory (but not all at the same time).

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 16 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

FFFFFh • Segment Registers: Code

Segment – Point to Base Address CS Extra ES Fragmentation SS DS Stack • Index Registers:

Data – Contain Offset Value

• Notation (Segmented Address):

System

Logical partially overlapped segment d fully overlapped Segments contiguous segment c

segment a segment b segment e

Physical Memory

30000h 0h 10000h 20000h

Note that segments can overlap. This means that two different logical addresses can refer to the same physical address (aliasing).

In non-overlapping method, address of source is totally different from address of destination. Therefore, we can directly transfer the data using MOVSB/MOVSW instruction for transferring the data.

The blocks are said to be overlapped if some of the memory locations are common for both the blocks.

Case I: If address in SI is greater than address in DI then start the data transfer from last memory location keeping DF=1.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 17 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Case II: If address in SI is less than address in DI, then start the data transfer from first memory location by keeping DF=0.

2.3.4 Algorithm: 2.3.4.1 Non-overlapped mode 1. Initialize 2 memory blocks pointed by source and destination registers. 2. Initialize counter. 3. Move the contents pointed by source register to a register. 4. Increment address of source register. 5. Move the contents from register into location pointed by destination register. 6. Increment destination registers. 7. Decrement counter. 8. Repeat from steps 3 to step 6 until counter is 0. 9. End.

2.3.4.2 Non-overlapped mode 1. Initialize 2 memory blocks pointed by source and destination registers. 2. Initialize counter. 3. Move the contents pointed by source register [si+count] to a variable. 4. Decrement address of source register. 5. Move the contents from variable into location pointed by destination register [di+count] 6. Decrement destination registers. 7. Decrement counter. 8. Repeat from steps 3 to step 6 until counter is 0. 9. End.

Input: Array of number stored in location pointed by source and destination register Example: Array 1 db 10h, 20h, 30h, 40h, 33h, 0ffh, 44,55h, 23h, 45h Array2 db 00h, 00h, 00h, 00h, 00h, 00h, 00,00h, 00h, 00h Output: NON OVER LAPPED BLOCK TRANSFER Array2 db 10h, 20h, 30h, 40h, 33h, 0ffh, 44,55h, 23h, 45h OVER LAPPED BLOCK TRANSFER Array2 db 00h, 00h, 00h, 00h, 00h,10h, 20h, 30h, 40h, 33h, 0ffh, 44,55h, 23h, 45h

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 18 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

2.4 Theory Questions: 1. Memory: Even and odd banks 2. Address decoding techniques. 3. Comparison between memory mapped I/O and I/O mapped I/O. 4. Diagrammatic representation of the overlapped and non-overlapped block transfer 5. Comparison of overlapped and non-overlapped block transfer

2.5 Oral Questions: 1. Specify all the memory addressing instruction 2. What is the use of in Block transfer? 3. What is use of Source and Destination Index in above program 4. What is the change in the contents of memory locations in overlapped and non- overlapped mode? 5. Which interrupt is used to terminate the program in 8086 kit?

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 19 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Att (2) Perm(5) Oral(3) Total(10) Sign with Date

Assignment 3

Problem Definition: Write 8086 ALP to convert 4-digit Hex number into its equivalent BCD number and 4-digit BCD number into its equivalent HEX number .Make your program user friendly to accept the choice from user for: HEX to BCD BCD to HEX EXIT Display appropriate messages to prompt the user while accepting the input and displaying the result.

3.1 Prerequisites: Concept of number system

3.2 Learning Objectives:  Understand the implementation stack for its conversion of number

3.3 New concept:-

1.3.1 Memory model directives. 1.3.2 Segment directives. 1.3.3 Data type declaration

3.4 Theory

3.4.1 Memory model directives These directives instruct the assembler as to how large the various segment (code, data, stack, etc) can and what sort of segmentation register will be required (see sect.2.4.1).

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 20 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

.MODEL Where is one of the following options:

Tiny- code and data fit into single 64k and accessed via near pointers. Small- code and segment both less than 64k and accessed via near pointers. Compact –Code segment is <64K (near ptr) and data segment is <1MB (far ptr ) Medium- Code segment is <1Mb (far ptr) and data segment is <64K (near ptr) Large- code and data segment both less than 1MB and accessed via far pointers. Huge- Like “large” model, but also permits arrays larger then 64K

3.4.2 Segment directives These directives indicate to assembler the order in which to load segment. When it encounter one of these directives, it interprets all subsequent instructor as belonging to the indicated segment (until the next directives is encounter).

.stack ; specified .code .data

3.4.3 Data type declaration

As has been previously discussed, data can be of several different lengths and assembler must be able to decide what length a specific constant (or variable) is. This can be down using data type declaration in conjunction with a constant declaration or variable assignment .this is akin to strong typing of variable in high level language .the data types are:

Byte (8 bit quantity)—synonyms are byte and db

Word (16) -- synonyms are word dw

Dword (32bit) -- synonyms are dword and dd

Qword (64bit) -- synonyms with dq

Tword (128bit) -- synonyms with dt

An example of their use is:

MOV AX, word VAR; moves a 16-bit Variable VAR into AX

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 21 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

3.5 Instruction Used: 1. PUSH:-Push word onto stack. 2. POP:-Pop word off stack. 3. DIV:-Divide byte/word 4. XOR: - Exclusive or byte/word 5. JA/JNBE:-Jump if above/not below or equal 6. JB/JNAE:-Jump if below /not above or equal 7. JG/JNLE:-Jump if /not less nor equal 8. JL/JNGE:-Jump if less /not greater nor equal 9. INT:-It allows ISR to be activated by programmer & external H\W device

3.6 New interrupt used: 1 INT 21h, function 0AH:- Read from keyboard and place into a memory buffer a row of character, untilis pressed.

3.7 New directives used: 1. .MODEL 2. .STACK 3. .DATA 4. .CODE 5. .OFFSET: - It informs the assembler to determine the offset/displacement of a named data item. 6. .PTR: - assign a specific type to variable/label

3.8 Algorithm:

3.8.1 HEX to BCD

1. Define variable on data segment. 2. Display message on screen ENTER 4-DIGIT HEX NO. 3. Accept BCD NO from user. 4. Transfer 0AH as a divisor in one of the register. 5. Divide the no by 0AH 6. PUSH reminder in one of the register 7. Increment Count _1.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 22 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

8. Repeat Till BCD NO is not zero go to step 5. 9. Pop the content of Reminder. 10. Display result by calling display procedure. 11. Decrement Count _1, till Count is not zero repeat step 9 else go to step 12. 12. Stop

3.8.2 BCD to HEX

1. Define variables in data segment 2. Display message on screen ENTER 5-DIGIT BCD NO. 3. Accept single digit from user 4. Transfer 10000 to multiplier 5. Multiply accepted BCD digit by multiplier & add it to RESULT variable. 6. Accept single digit from user 7. Transfer 1000 to multiplier 8. Multiply accepted BCD digit by multiplier & add it to RESULT variable. 9. Accept single digit from user 10. Transfer 100 to multiplier 11. Multiply accepted BCD digit by multiplier & add it to RESULT variable. 12. Accept single digit from user 13. Transfer 10 to multiplier 14. Multiply accepted BCD digit by multiplier & add it to RESULT variable. 15. Accept single digit from user 16. Transfer 1 to multiplier 17. Multiply accepted BCD digit by multiplier & add it to RESULT variable. 18. Display result by calling display procedure 19. Stop.

3.8.3 Procedure for accept numbers: (ASCII to HEX) 1. Read a single character/digit from keyboard using function 0AH of INT 21H 2. Convert ASCII to HEX as per following: a. Compare its ASCII with 30H if No is less than 0 (i.e case of -ve no given) then go to step f else go to step c. b. Compare its ASCII with 39H if No is greater than 9 (i.e case of character A – F given) then go to step f else go to step c . c. Store the resultant bit in NUM Variable.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 23 Microprocessor and Interfacing Laboratory Second Year Computer Engineering d. Check whether four digits (16-bit number) or two digits (8-bit number) are read; if yes then go to display procedure else go to step 1 for next bit e. Till counter is zero go to accept procedure. f. Display massage “I/P is invalid BCD number” & go to step 17. 3. End of accept procedure.

3.8.4 Procedure for display Result: (HEX to ASCII) 1. Compare 4 bits (one digit) of number with 9 2. If it is <= 9 then go to step 4 else go to step 3 3. Add 07 to that number 4. Add 30 to it 5. Display character on screen using function 02 of INT 21H 6. Return to main routine 7. End of display procedure.

3.9 Assignment Questions: 1. Explain various addressing modes of 8086 microprocessor used in this program. 2. Explain Different assembler directives used in this program. 3. Explain various Number Systems used in Digital Electronics. 4. What is HEX Number? Explain the steps to convert HEX No to BCD No 5. What is BCD Number? Explain the steps to convert BCD N o to HEX No

3.10 Oral Questions: 1. Differentiate between 01H and 0AH of INT 21H. 2. Explain the use of SI register in the program. 3. Explain the use of DI register in the program. 4. In above program which Procedure U used. 5. Is there any difference between Rotate Bit & Shift Bit Instruction?

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 24 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Att (2) Perm(5) Oral(3) Total(10) Sign with Date

Assignment 4

Problem Definition: Write 8086 ALP for the following operation on the string entered by the user a. Calculate Length if the string b. Reverse the string c. Check whether the string is palindrome or not Make your program friendly by providing MENU like:  Enter String  Calculate Length Of String  Reverse The String  Check Palindrome  Exit Display appropriate messages to prompt the user while accepting the input and displaying the result.

4.1 Prerequisite:  Concept of string &its operation.

4.2 Learning objectives :  Implementation of string of 8086

4.3. New concept: String manipulations in 8086.

4.4 Theory 4.4.1 The 80x86 String Instructions All members of the 80 x 86 families support five different string instructions: MOVS, CMPS, SCAS, LODS and STOS. They are the string primitives since you can build most other string operations from these five instructions.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 25 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

4.4.2 How the String Instructions Operate The string instructions operate on blocks (contiguous linear arrays) of memory. For example the MOVS instruction moves a sequence of bytes from one memory location to another. The CMPS instruction compares two blocks of memory. The SCAS instruction scans a block of memory for a particular value. These string instructions often require three operands a destination block address a source block address and (optionally) an element count. For example when using the MOVS instruction to copy a string you need a source address a destination address and a count (the number of string elements to move).

Unlike other instructions which operate on memory the string instructions are single-byte instructions which don't have any explicit operands. The operands for the string instructions include

 The SI (source index) register

 The DI (destination index) register

 The CX (count) register

 The AX register and

 The direction flag in t e FLAGS register.

For example one variant of the MOVS (move string) instruction copies a string from the source address specified by DS:SI to the destination address specified by ES:DI of length CX. Likewise the CMPS instruction compares the string pointed at by DS:SI of length CX to the string pointed at by ES:DI.

Not all instructions have source and destination operands (only MOVS and CMPS support them). For example the SCAS instruction (scan a string) compares the value in the accumulator to values in memory. Despite their differences the 80x86's string instructions all have one thing in common - using them requires that you deal with two segments the data segment and the extra segment.

4.4.3 The REP/REPE/REPZ and REPNZ/REPNE Prefixes

The string instructions by themselves do not operate on strings of data. The MOVS instruction for example will move a single byte word or double word. When executed by itself the MOVS instruction ignores the value in the CX register. The repeat prefixes tell the 80x86 to do a multi-byte string operation. The syntax for the repeat prefix is:

Field: Label repeat mnemonic operand ; comment

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 26 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

For MOVS:

REP MOVS {operands}

For CMPS:

REPE CMPS {operands}

REPZ CMPS {operands}

REPNE CMPS {operands}

REPNZ CMPS {operands}

For SCAS:

REPE SCAS {operands}

REPZ SCAS {operands}

REPNE SCAS {operands}

REPNZ SCAS {operands}

For STOS:

REP STOS {operands}

You don't normally use the repeat prefixes with the LODS instruction.

As you can see the presence of the repeat prefixes introduces a new field in the source line - the repeat prefix field. This field appears only on source lines containing string instructions. In your source file:

 The label field should always begin in column one

 The repeat field should begin at the first tab stop and

 The mnemonic field should begin at the second tab stop.

When specifying the repeat prefix before a string instruction the string instruction repeats CX times. Without the repeat prefix the instruction operates only on a single byte word or double word.

You can use repeat prefixes to process entire strings with a single instruction. You can use the string instructions without the repeat prefix as string primitive operations to synthesize more powerful string operations.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 27 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

The operand field is optional. If present MASM simply uses it to determine the size of the string to operate on. If the operand field is the name of a byte variable the string instruction operates on bytes. If the operand is a word address the instruction operates on words. Likewise for double words. If the operand field is not present you must append a "B" "W" or "D" to the end of the string instruction to denote the size e.g. MOVSB MOVSW or MOVSD.

4.4 The Direction Flag

Besides the SI, DI and ax registers one other register controls the 80x86's string instructions - the . Specifically the direction flag in the flags register controls how the CPU processes strings.

If the direction flag is clear the CPU increments SI and DI after operating upon each string element. For example if the direction flag is clear then executing MOVS will move the byte word or double word at DS:SI to ES:DI and will increment SI and DI by one two or four. When specifying the REP prefix before this instruction the CPU increments SI and DI for each element in the string. At completion the SI and DI registers will be pointing at the first item beyond the string.

If the direction flag is set then the 80x86 decrements si and di after processing each string element. After a repeated string operation the si and di registers will be pointing at the first byte or word before the strings if the direction flag was set.

The direction flag may be set or cleared using the cld (clear direction flag) and std (set direction flag) instructions. When using these instructions inside a procedure keep in mind that they modify the machine state. Therefore you may need to save the direction flag during the execution of that procedure.

4.5 Algorithm

1. Start

2. Display message to enter string 3. Enter the string 4. Display menu as 1. Calculate length of string 2. Reverse the string 3. Check palindrome 4. Exit 5. Read choice

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 28 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

If choice =1 go to step6 If choice =2 go to step8 If choice =3 go to step15 If choice =4 go to step19 6. Display message for length 7. Display the length of string and jump to step 4 8. Display message for reverse string 9. Set the counter to length of string 10. Decrement the pointer to source string 11. Move the byte from source to destination 12. Increment the destination pointer 13. Decrement counter of length 14. Repeat step10 to13 until counter of length of string becomes zero and jump to step 4 15. Compare each location of source and destination of the source string and reversed string 16. If equal increment pointers, decrement counter 17. Display message string is palindrome and jump to step 4 18. If step 15 gives not equal then Display message string is not palindrome and jump to step 4 19. Terminate the program

4.6 Assignment Questions 1. Write a program in 8086 assembly language to move string of 16 characters from 7000h: 2000h to 9000h: 0300h using string instructions. 2. Explain with example string instructions of 8086 Microprocessor.

4.7 Oral Questions 1. What is maximum size of the instruction in 8086? 2. Which are string instructions? 3. In string operations which is by default string source pointer? 4. In string operations which is by default string destination pointer? 5. What is LEA? What is its use in our program?

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 29 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Att (2) Perm(5) Oral(3) Total(10) Sign with Date

Assignment 5

Problem Definition: Write 8086 ALP to perform string manipulation. The strings to be accepted from the user is to be stores code segment Module 1 and write FAR PROCEDURES in code segment Module_2 for following operations on the string: a) Concatenation of two strings b)Number of occurrences of a sub-string in the given string Note: Use PUBLIC and EXTERN directive. Create .OBJ files of both the modules and link them to create an EXE file.

5.1 Prerequisite: a) Concept of String Operation. b) Concept of lntersegment CALL.

5.2 Learning Objectives:  Understand the working of Far Procedure  Implementation Far Procedure For string operation.

5.3 New Concepts: a. Far procedure b. PUBLIC & EXTERN Directives

5.4 Theory 5.4.1 EXTERN: Importing Symbols from Other Modules  It tells assembler that named item is defined in another assembly.  It is used to declare a symbol which is not defined anywhere in the module being assembled, but is assumed to be beaded in some other module and needs to be referred to by this one.  It can take only one argument at a timed the support for multiple arguments is implemented at the preprocessor level.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 30 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Syntax: EXTRN a day item or procedure name: type Example of a procedure i.e. far EXTRN SUB1: FAR MAINPROGRAM START . . . CALL SUBI MAINPROGRAM END

5.4.2 PUBLIC: It tells assembler that the address of a named item in current Assembly is available to other modules. Syntax: PUBLIC a label/variable/procedure name * Example of procedure PUBLIC SUB1 SUBl PROC FAR Jr

SUBl ENDP

5.4.3 Name SEGMENT [align][combine] align = BYTE align on byte address (no alignment) = WORD align on even address = DWORD align on DWORD address = PARA align on next 16 byte Paragraph = PAGE align on next 256 byte boundary Combine =PUBLIC similar named segments are concatenated (CS) = STACK similar named segments are concatenated (SS) = COMMON similar named segment are overlapped = MEMORY similar names segments are concatenated = AT addr segment relative to absolute address = nothing segment is private and loaded independent

5.4.4 GLOBAL: Exporting Symbols to Other Modules PROC: mark start and end of a procedure block called label. The statements in the block can be called with the CALL instruction or INVOKE directive.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 31 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

ENDP: The ENDFUNCdirective Darks the end of a function. ENDP is a synonym for ENDFUNC.

5.5 Algorithm: 1. Start 2. Display Menu as a. Concatenation of 2 string b. Equal or not c. Exit 3. Read choice, if choice =a go to step4, if choice = b go to step5, if choice = c go to step6 4. Call Concat Far procedure for concatenation of two strings 5. Call Comp Far procedure to compare two strings 6. End

Concat procedure 1. Start 2. Read 2 strings using string read function 3. Assign srcindex = length of sourcestring & destindex = zero, reset Direction flag 4. Use string transfer function. 5. Print string 6. Ret

Comp procedure 1. Read 2 slings using string read function 2. Assign sourceindex=o & destindex=0 reset direction flag 3. Use string compare function 4. Print result 5. Ret

5.6 Assignment Questions: 1. Explain difference between NEAR and FAR procedure of 8086 microprocessor. 2. What is EA? In how many ways EA is specified in the instruction? 3. Explain the use of POP and PUSH instruction in 8086.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 32 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

5.7 Oral Questions: 1. Why we indicate FF as 0FF in program? 2. What do you mean by 20 dup (0)? 3. Explain assembler directives used in program

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 33 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Att (2) Perm(5) Oral(3) Total(10) Sign with Date

Assignment 6

Problem Definition: Write 8086 ALP to perform multiplication of two 8-bit numbers. Use Successive Addition and add and shift method.

6.1 Prerequisites:  Concept of multiplication method

6.2 Learning objectives:  Understanding shift & rotate instruction

6.3 New Concept  Implementation of Shift and Rotation Instructions for performing multiplication

6.4 Theory Multiplying unsigned numbers Multiplying unsigned numbers in binary is quite easy. Recall that with 4 bit numbers we can represent numbers from 0 to 15. Multiplication can be performed done exactly as with decimal numbers, except that you have only two digits (0 and 1). The only number facts to remember are that 0*1=0, and 1*1=1 (this is the same as a logical "and"). Multiplication is different than addition in that multiplication of an n bit number by an m bit number results in an n+m bit number. Let's take a look at an example where n=m=4 and the result is 8 bits Decimal Binary 1010 x0110 10 0000 x6 1010 60 1010 +0000 0111100 In this case the result was 7 bit, which can be extended to 8 bits by adding a 0 at the left. When multiplying larger numbers, the result will be 8 bits, with the leftmost set to 1, as shown.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 34 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Decimal Binary 1101 x1110 13 0000 x14 1101 182 1101 +1101 10110110 As long as there are n+m bits for the result, there is no chance of overflow. For 2 four bit multiplicands, the largest possible product is 15*15=225, which can be represented in 8 bits. Multiplying signed numbers There are many methods to multiply 2's complement numbers. The easiest is to simply find the magnitude of the two multiplicands, multiply these together, and then use the original sign bits to determine the sign of the result. If the multiplicands had the same sign, the result must be positive, if they had different signs, the result is negative. Multiplication by zero is a special case (the result is always zero, with no sign bit). Multiplication and division can be performed on signed or unsigned numbers. For unsigned numbers, MUL and DIV instructions are used, while for signed numbers IMUL and IDIV are used. The format of the multiplication and division instructions does not specify the multiplicand as it is implicitly specified depending on the size of the source Consider the example given below 6 × 13 = 78 Sequential addition from row to row: 0 1 1 0 × 1 1 0 1 Sum: 0 1 1 0 00000110 0 0 0 0 00000110 0 1 1 0 00011110 + 0 1 1 0 01001110 0 1 0 0 1 1 1 0 Product

6.4.2 Sequential Shift/Add-Method Method to avoid adder arrays • shift register for partial product and multiplier with each cycle, 1. Partial product increases by one digit 2. Multiplier is reduced by one digit • MSBs of partial product and multiplicand are aligned in each cycle • not the multiplicand is shifted Partial product and multiplier are

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 35 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Successive Addition Method for 8-bit numbers  Consider that a byte is present in the AL register and second byte is present in BL Register.  We have to multiply the in AL with the byte in BL  Multiply the number using Successive Addition Method.  In this method, one number is accepted and other number is taken as a counter.  The first number is added with itself, till the counter decrements to zero. Result is stored in DX register, Display the result, using display routine

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 36 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

15 x 13 =195

6.5 Algorithm: 1. Start 2. Read multiplication & Multiplier for multiplication 3. Display menu a. Successive Addition b.Add & shift method c.Exit 4. Read choice .if choice =a go to next step, if choice = b go to Sep 9, if choice =c go to step 15 5. Assign sum =0 count= Multiplier 6. Sum =sum Multiplicand 7. Decrement count .if count >0 go to step 8 8. Print sum & go to step 3 9. Assign count =no of digit in multiplier, sum=0, shiftvar=0 10. Shift right Multiplier by 1 11. If set, sum =sum+ (Left shifted multiplicand by shiftvar) 12. Shitvar =shitvar+1 13. If count> 0 go to step 14 14. Print sum & go to step 3 15. Exit

6.6 Instructions needed: 1. MUL-Multiplication specified byte or word to word 2. SHR- Shift logical right byte or word, MSB to LSB and to CF

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 37 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

3. SHL-Shift logical left byte or word, LSB to MSB and to CF 4. JMP-Unconditional jump to the specified location counter 5. JC-Jumps if carry is generated 6. JE/JZ-Jumps if equal or zero.

Directive Recommended: 1) MACRO- Start of MACRO statement 2) ENDM-end

6.7 Assignment Question: 1. Explain MACRO with example. Justify where macro is suitable than procedure. 2. Differentiate between PROC& MACRO 3. What is the difference between a rotate & a shift instruction? Explain with an appropriate diagram. 4. Explain the difference between arithmetic shift & logical shift. 5. Describe execution of CALL instruction.

6.8 Oral Question: 1. Explain the Instruction used in the program 2. With example explain Add and Shift Multiplication 3. With example explain Successive Addition Multiplication 4. Suggest the alternative instructions for JE/JZ (Logic of program should not change) 5. Difference in multiplication by MUL and IMUL

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 38 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Att (2) Perm(5) Oral(3) Total(10) Sign with Date

Assignment 7

Problem Definition: Write 8087ALP to obtain: i) Mean ii) Variance iii) Standard Deviation For a given set of data elements defined in data segment. Also display result

7.1 Prerequisites:  Concept of Mean, Variance and Standard Deviation

7.2 Learning objectives:  Understanding instructions of 8087

7.3 New Concept  Implementation of 8087 Instructions for computing Mean, Variance and Standard Deviation

7.4 Theory:

7.4.1 80X87 Architecture The 80X87 is designed to operate concurrently with microprocessor. The 80X87 executes 68 different instructions. The microprocessor executes all normal instruction & 80X87 arithmetic coprocessor instructions. Both the microprocessor & coprocessor can execute their respective instructions simultaneously or concurrently. The numeric or arithmetic coprocessor is a special-purpose microprocessor i.e. especially designed to efficiently execute arithmetic & transcendental operations. The microprocessor intercepts & executes the normal instruction set, & coprocessor intercepts & executes only the co-processor instructions. The ESC instruction used by microprocessor, to generate a memory address for coprocessor so that coprocessor can execute a coprocessor instruction.

7.4.2 Internal Structure of The 80X87: Figure shows internal structure of arithmetic coprocessor. It is divided into two major sections; control unit & numeric execution unit.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 39 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Control unit (CU) Numeric Execution Unit (NEU) Control register Status Register Exponent Module Shifter

Arithmetic Instruction Decoder Module Data Buffer Operand Queue Temporary Registers

TA 7 G 6 Bus Tracking RE 5 Exceptions G I 4 S 3 TE 2 R 1 0

80-bit wide stack

1. Control Unit: It interfaces the coprocessor to microprocessor system data bus. Both the devices monitor the instruction stream. If instruction is an Escape (coprocessor) instruction, the coprocessor executes it; if not, the microprocessor executes it.

2. Numeric Execution Unit (NEU): It is responsible for executing all coprocessor instructions. The NEU has an 8- register stack that holds operands for arithmetic instructions & the result of arithmetic instructions. Instructions either address data in specific stack data register or use a push & pop mechanism to store & retrieve data on the top of stack. Other registers in the NEU are status, control, tag & exception pointers. A few instructions transfer data between the coprocessor & the AX register in microprocessor. The FSTSW AX instruction is the only instruction available to coprocessor that allows direct communications to microprocessor through the AX register. 8087 does not contain FSTSW AX instruction. The stack within the coprocessor contains eight registers that are each 80 bits wide. These stack registers always contains an 80 bit extended precision floating pt. number. The only time that data appear as any other form is when they reside in the memory system. The coprocessor converts from signed integer, BCD, single precision, or double precision form as data are moved between the memory & coprocessor register stack.

3. Instruction Set: The arithmetic coprocessor executes over 68 different instructions. Whenever a coprocessor instruction references memory, the microprocessor automatically generates memory address for the instruction. The coprocessor uses the data bus for data transfer

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 40 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

during coprocessor instructions and the microprocessor uses it during normal instruction. Each time that assembler encountered one of the coprocessor mnemonic opcode to coprocessor.  Data Transfer Instruction: There are three basic data transfers: floating pt., signed –integer & BCD. The only time that data ever appear in the signed integer or BCD form is in memory. Inside the coprocessor, data always stored as an 80-bit extended –precision floating –pt number.

 Floating point Data Transfer: There are four traditional floating pt data transfer instructions are: FLD (load real), FST (store real), FSTP (store real & pop), FXCH (exchange). A new instruction added in Pentium Pro through Pentium 4 is a conditional floating pt. move instruction that uses opcode FCMOV with a floating pt. condition. The FLD instruction loads floating-point memory data to top of internal stack, referred to as ST (stack top). This instruction stores the data on top of stack & then decrements the stack pointer by one. The FST instruction stores a copy of top of stack into memory location or coprocessor register indicated by the operand. The FSTP (floating pt. store & pop) instruction stores a copy of top of stack into memory or any coprocessor register & then pops data from top of stack. The FXCH instruction exchanges the register indicated by the operand with the top of the stack. For Ex. FXCH ST (2) instruction exchanges the top of stack with register 2.

 Integer Data Transfer Instructions: The coprocessor supports three integer data transfer instructions: 1. FILD (load register), 2. FIST (store integer) 3. & FISTP (store integer & pop). These instructions functions as did FLD, FST, FSTP, except that the data transferred are integer data. The coprocessor automatically converts the internal extended –precision floating-point data to integer data.  BCD Data Transfer Instructions: Two instructions load or stores BCD signed –integer data. The FBLD instruction Loads the top stack with BCD memory data & FBSTP stores top of stack & does a pop.  Arithmetic Instructions: Arithmetic instructions for coprocessor include addition, subtraction, multiplication, division & calculating square roots. The arithmetic related instructions are scaling, rounding, absolute value, & changing the sign. a) Addition: FADD destination, source Adds real numbers from specified source to real number at destination source can be stack element or memory location. Destination must be a stack element. Ex. FADD ; ST+ST (1) ,pop stack result at ST FADDP destination, source Adds ST to specified stack elements and increments stack pointer by one. Ex. FADDP ST (2) ; Add ST (2) to ST. increment Stack pointer so ;ST(20) becomes ST. FIADD source Adds integer from memory to ST stores result in ST.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 41 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Ex. FIADD PRICE ; Integer number from memory + ST. b) Subtraction: FSUB destination, source Subtracts the real number at specified source from the real number at specified destination & puts the results in the specified destination. Ex. FSUB ; ST ST (1)-ST FSUBP destination, source Subtracts ST from specified stack elements & puts result in specified stack element. Then increments stack pointer by one. Ex. FSUBP ST (2) ; ST(2) ST. ST(1) becomes new ST. FISUB source Subtracts integer number stored in memory from ST & stores result in ST. Ex. FISUB DIFF ; ST ST – integer from memory. c) Multiplication: FMUL destination, source: Multiply real number from source by real number from specified destination, & put result in specified stack element. Ex. FMUL FMUL ST, ST (5) ; multiply ST(5) to ST, result in ST. FMULP destination, source : Multiplies real number from specified source by real number from specified destination, puts result in specified stack element, and incremented stack pointer by one. Ex. FMULP ST(2) ; multiply ST(2) to ST. incremented Stack pointer so ST 1 becomes ST . FIMUL source : Multiply integer from memory ST & put result in ST. Ex.FIMUL DWORD PTR[BX] ; integer no. from memory pointed by BX * ST and result in ST. d) Division : FDIV destination, source: Divides destination real by source real, stores result in destination. Ex. FDIV FDIV ST(2), ST ;divides ST by ST(2) stores result in ST. FDIVP destination, source: Same as FDIV, but also increments stack pointer by one after DIV. Ex. FDIVP ST (2), ST ;divides ST by ST(2) result in ST & increments stack ;pointer. FIDIV source Divides ST by integer from memory stores result in ST. Ex. FIDIV PERCENTAGE ; ST ST /integer number. e) Other arithmetic operations: FSQRT: Contents of ST are replaced with its square root. FABS: Replaces ST by its absolute value. Instruction simply makes sign positive. FCHS: Complements the sign of the number in ST.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 42 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

f) Compare Instructions: Compares the contents of ST with contents of specified or default source. The source may be another stack element or real number in memory. FCOM source: Compares ST with real number in another stack element or memory FCOMP source: Identical to FCOM except that stack pointer is incremented by one after the compare operation. g) Instructions which Loads Constants These instructions simply push the indicated constant onto the Stack. FLDZ : Push 0.0 onto stack. FLD1 : Push +1.0 onto stack. FLDPI : Push the value of  onto stack. FLD2T : Push log of 10 to the base 2 onto stack(log2 10) FLD2E : Push log of e to the base 2 onto stack(log2 e) FLDG2 : Push log of 2 to the base 10 onto stack(log10 2) h) Coprocessor Control Instructions: The coprocessor has to control instructions for initialization, exception handling, task switching. The control instructions have two forms. FINIT/FNINIT: Performs a reset operation on the arithmetic coprocessor. It sets register 0 as the top of the stack. FSETPM: Changes the addressing mode of coprocessor to protected addressing mode. This mode is used when micoprocessor is also operated in th e protected mode. As with microprocessor, protected mode can only be exited by a h/w reset or, in the case of 80386 thro’ Pentium 4, with changesto control register. FLDCW: Loads the control register with word addressed by operand. FSTCW / FNSTCW: Stores the control register into word-sized memory operand.

7.5 Algorithm 1. Initialize 8087 2. Make stack top zero 3. Load and add each no to stack top 4. Divide the total by n no of elements 5. Store the average in mean 6. Make stack top zero 7. Load each no. To stack top, Subtract mean from the no.(xi-mean), Square the (xi- mean) and add the contents 8. Store the addition in temp1 9. Load 1 on stack top 10. Load n on stack top 11. Find n-1 12. Store n-1 in temp2 13. Load n-1 on stack top 14. Load sum of (xi-mean)2 on stack top 15. Divide sum by n-1 16. Store as variance 17. Find the square root 18. Store as standard deviation 19. Display mean, variance and standard deviation 20. Stop

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 43 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

7.6 Theory Questions 1. Explain Status and Control Word of 8087 2. State and Explain data types supported by 8087 3. Explain the type of instructions supported by 8087. Give one example of each.

7.7 Oral Question: 1. Explain in Detail math Co-Processor? 2. Explain in detail a. FADD b. FSQRT c. FDIV d. FMUL 3. Explain long form of NDP?

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 44 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Att (2) Perm(5) Oral(3) Total(10) Sign with Date

Assignment 8

Problem Definition: Write 8086 ALP to convert an analog signal in the range of 0V to 5V to its corresponding digital signal using successive approximation ADC and dual slope ADC. Find resolution used in both the ADC’s and compare the results.

8.1 Prerequisite: Concept of: 1. 8255 working 2. Data conversion from analog to digital

8.2 Learning Objectives: 1. Understand the interfacing of ADC to 8086. 2. Understand the interfacing of peripheral ICs like 8255.

8.3 New Concepts: o Interfacing of 8255 PPI with 8086 o Interfacing of 8255 PPI with 0809 ADC 8.4 Theory An analog to Digital Converter: The function of an analog to digital ADC converter is to produce a digital word which represents magnitude of some analog voltage or current

8.4.1 The important specifications of an ADC are:  Resolution  Accuracy  Linearity  Speed  Conversion Time

8.4.2 Types of ADC  Parallel Comparator ADC or Flash ADC  Dual Slope ADC  Successive-Approximation ADC

8.4.2.1 Parallel Comparator ADC or Flash ADC:  Major advantage is its high speed. It has least conversion time compared to other converters  The opcode from the comparators is not a binary code(std), but it can be converted to any desired code with some simple logic

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 45 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

 The disadvantage of flash logic ADC is that more numbers of A comparators are required for a reasonable amount of resolution  2n-1 comparators are required for n-bit resolution. Hence for an 8-bit conversion 255 comparators are needed.  The cost of flash ADC is relatively high.

8.4.2.2 Dual slope ADC  It is used in digital voltmeter  This type of converter can give a no. of bits of resolution  The cost of ADC is low  The accuracy of converter is high as it is not affected by temperature  Disadvantage: slow type speed  It may take 300ms to do a conversion

8.4.2.3 Successive-approximation ADC:  On the other hand 1st clock pulse at start of conversion cycle successive approximation register (S.A.R.) makes MSB 1  DAC applies its equivalent voltage inverting input of the converter  Comparator compares both the inputs and if the inverting input is higher than the other voltage the output of comparator will go low and this will tell S.A.R. to make MSB 0 otherwise it will set.

8.4.3 Working Principle of ADC 0809: 1 The ADC 0809 operates on the successive approximation technique of A to D conversion. 2 It is a CMOS device with 8-analog inputs, an 8 channel multiplexer and microprocessor compatible control logic. 3 As the number of bits n=8, it includes a 256 register voltage divider, a group of analog switches and a successive approximation register (SAR). 4 As there are 8-analog channels, we can connect up to 8 analog inputs to this IC. 5 However due to the use of a multiplexer, at a time only one analog input will be converted into an equivalent 8-bit digital output. The analog input channels can be selected using the three address lines A, B and C.

8.4.4 Features of ADC: 1 Inbuilt 8 analog channels with multiplexer. 2 Zero or full scale adjustment is not required. 3 0 to 5 V input voltage range with single polarity 5 V supply. 4 Output is TTL compatible. 5 High speed. 6 Low conversion time 7 High accuracy. 8 8-bit resolution. 9 Low power consumption (less than 15 mW). 10 Easy to interface with all microprocessors. 11 Minimum temperature dependence

1 Analog Inputs (I/P 0 to I/P 7):

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 46 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Pin numbers 1 to 5 and 26 and 28, designated as I/P0 to I/P7 are the eight analog input of this IC. We can connect signals coming from eight different transudes to these inputs. Each one of these inputs will be converted to an 8-bit equivalent digital from one by one and not all at a time. So one of these eight inputs should be selected for conversion. This selection is done by means of these address pins A, B and C.

2 Address Pins A,B ,C(Pin 23,24,25) : These pins will decide or select one out of eight analog inputs, for conversion into digital form. For example if CBA= 010 then the “IN2” is selected and the analog signal at this input is converted to equivalent digital form.

3 Reference Voltage [VREF(+) and VREF (-) ] : Depending on the desired polarity of the reference voltage, we can connect a positive or negative reference voltage externally to these pins.

4 ALE and Output Enable: The address latch enable (ALE) input is useful in enabling the address latch which stores the address on lines A, B and C. The output enable pin, when activated will make the digital output available on the output pins.

5 Start and EOC: We have to enable the start to begin the A to D conversion. The end of conversion is indicated by EOC output.

6 Digital Output [2-1 to 2-8]: The digital output is available to these pins.

8.5 Interfacing of 8255 with 0809 ADC 0809 is an 8-bit successive approximation ADC. This chip has 8-channel 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. At the time of power on the valid channel address is latched at the rising edge of the ALE signal. 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. The OE should always be high, when data is to be read. After the conversion, EOC is given through PC, indicating end of conversion. The port A and C are defined in the input mode, whereas port B of 8255 is configured in output mode. The data is read through port A of 8255. Positive (DC) and negative (DC) or (ac) voltage is applied as the analog input at channel 0. Hence decoupling capacitors are used to maintain minimum noise level. Internal oscillator can be enabled only when A/D conversion is to be done. The oscillator oscillates till the SOC enables pin PB2 of the 8255.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 47 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

8255PPI ADC0809

PA0-PA7 D0-D7 Analog PC0 EOC Input PB0 SOC

PB1 OE PB2 CLK

Figure 2 Interfacing of 0809 ADC with 8255

8.6 For analog to digital conversion we require 1. Port A, as input port in mode’0’ 2. Port B, as input port in mode’0’ 3. Port C, as input port Hence, control word format is as follows D7 D6 D5 D4 D3 D2 D1 D0 1 0 0 1 1 0 0 1

Control word in hex is 99H

In 8255, addresses are as follows PA- 0011 0000 = 30H PB- 0011 0001 = 31H PC- 0011 0010 = 32H CWR-0011 0011 = 33H

8.7 I/O mapping of 8255 A7 A6 A5 A4 A3 A2 A1 A0 Port A 0 1 1 0 0 0 0 1 61H Port B 0 1 1 0 0 0 1 1 63H Port C 0 1 1 0 0 1 0 1 65H CWR 0 1 1 0 0 1 1 1 67H

8.8 Instructions needed: 1. IN-Copy a byte or word from specified port to accumulator 2. OUT- Copy a byte or word from accumulator to specified port 3. JZ-Jumps if equal to Zero 4. TEST-Logical AND between all bits of two operands for flags only.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 48 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

8.9 Algorithm: 1. Write control word to CWR of the 8255 2. Issue SOC signal by setting PB0 High 3. Enable CLK & ALE by setting PB2 High 4. Check for EOC by polling PC0 bit PC0 = 1 means conversion still in progress PC0 = 0 means EOC 5. Latch the output by setting PB1 High 6. Read port A for obtaining converted data 7. Display output using display routine

8.10 Program:

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 49 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

8.11 Hardware Connections:

PA0-PA7 (input) – digital data from ADC PB0 (output) – Start of Conversion PB1 (output) – Output Enable PB2 (output) – Enable Oscillator PC0 (input) – End of Conversion

8.12 Input and Output:-

Observation Table –

8.13 Assignment Questions: 1. Block diagram of 8255 2. Modes of operation of 8255 3. BSR mode and I/O mode word format of 8255 4. Modes of I/O mode of 8255 5. Explain instructions used in program

8.14 Oral Questions: 1. How the Resolution of ADC is defined as? 2. Which conversion is high speed conversion? 3. What is the CWR? 4. What is the address of Port A and Port B? 5. From which location does the source code starts on 86-Kit?

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 50 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Att (2) Perm(5) Oral(3) Total(10) Sign with Date

Assignment 9

Problem Definition: Write 8086 ALP to interface DAC and generate following waveforms on oscilloscope, (i)Square wave - Variable Duty Cycle and frequency. (ii)Ramp wave - Variable direction, (iii)Trapezoidal wave (iv)Stair case wave

9.1 Prerequisites:  Concepts of Digital Data.

9.2 Learning Objectives:  Understand the interfacing of DAC 0808 with 8086.  Understand the interfacing of peripheral ICs like 8255..

9.3 New concepts: Applications of 8255

9.4 Theory 9.4.1 Digital-Analog Convertor In electronics, a digital-to-analog converter (DAC or D-to-A) is a device that converts a digital (usually binary) code to an analog signal (current, voltage, or electric charge). An analog-to-digital converter (ADC) performs the reverse operation. Signals are easily stored and transmitted in digital form, but a DAC is needed for the signal to be recognized by human senses or other non-digital systems. A common use of digital-to- analog converters is generation of audio signals from digital information in music players. Digital video signals are converted to analog in televisions and cell phones to display colors and shades. Digital-to-analog conversion can degrade a signal, so conversion details are normally chosen so that the errors are negligible. Due to cost and the need for matched components, DACs are almost exclusively manufactured on integrated circuits (ICs). There are many DAC architectures which have different advantages and disadvantages. The suitability of a particular DAC for an application is determined by a variety of measurements including speed and resolution.

9.4.2 Types of DAC’s: The most common types of electronic DACs are:  Pulse-Width Modulator DAC  Oversampling commonly known as Delta sigma DAC  Binary Weighted DAC  R-2R Ladder DAC  Thermometer Coded DAC  Segmented DAC

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 51 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

 Hybrid DAC

The pulse-width modulator, the simplest DAC type. A stable current or voltage is switched into a low-pass analog filter with a duration determined by the digital input code. This technique is often used for electric motor speed control, but has many other applications as well. Oversampling DACs or interpolating DACs such as the delta-sigma DAC, use a pulse density conversion technique. The oversampling technique allows for the use of a lower resolution DAC internally. The binary-weighted DAC, which contains individual electrical components for each bit of the DAC connected to a summing point. These precise voltages or currents sum to the correct output value. This is one of the fastest conversion methods but suffers from poor accuracy because of the high precision required for each individual voltage or current. Switched resistor DAC contains of a parallel resistor network. Individual resistors are enabled or bypassed in the network based on the digital input. Switched current source DAC, from which different current sources are selected based on the digital input. Switched capacitor DAC contains a parallel capacitor network. Individual capacitors are connected or disconnected with switches based on the input. The R-2R ladder DAC which is a binary-weighted DAC that uses a repeating cascaded structure of resistor values R and 2R. This improves the precision due to the relative ease of producing equal valued-matched resistors (or current sources). However, wide converters perform slowly due to increasingly large RC-constants for each added R-2R link. The Successive-Approximation or Cyclic DAC, which successively constructs the output during each cycle. Individual bits of the digital input are processed each cycle until the entire input is accounted for. The thermometer-coded DAC, which contains an equal resistor or current-source segment for each possible value of DAC output. An 8-bit thermometer DAC would have 255 segments, and a 16-bit thermometer DAC would have 65,535 segments. This is perhaps the fastest and highest precision DAC architecture but at the expense of high cost. Conversion speeds of >1 billion samples per second have been reached with this type of DAC. Hybrid DACs, which use a combination of the above techniques in a single converter. Most DAC integrated circuits are of this type due to the difficulty of getting low cost, high speed and high precision in one device. The segmented DAC, which combines the thermometer-coded principle for the most significant bits and the binary-weighted principle for the least significant bits. In this way, a compromise is obtained between precision (by the use of the thermometer-coded principle) and number of resistors or current sources (by the use of the binary-weighted principle). The full binary-weighted design means 0% segmentation, the full thermometer-coded design means 100% segmentation.

9.4.3 Performance DACs are very important to system performance. The most important characteristics of these devices are:  Resolution: This is the number of possible output levels the DAC is designed to reproduce. This is usually stated as the number of bits it uses, which is the base two logarithm of the number of levels. For instance a 1 bit DAC is designed to reproduce 2 (21) levels while an 8 bit DAC is designed for 256 (28) levels. Resolution is related to the Effective number of bits which is a measurement of the

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 52 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

actual resolution attained by the DAC. Resolution determines color depth in video applications and audio bit depth in audio applications.  Maximum sampling rate: This is a measurement of the maximum speed at which the DACs circuitry can operate and still produce the correct output. As stated in the Nyquist–Shannon sampling theorem defines a relationship between the sampling frequency and bandwidth of the sampled signal.  Monotonicity: This refers to the ability of a DAC's analog output to move only in the direction that the digital input moves (i.e., if the input increases, the output doesn't dip before asserting the correct output.) This characteristic is very important for DACs used as a low frequency signal source or as a digitally programmable trim element.  THD+N: This is a measurement of the distortion and noise introduced to the signal by the DAC. It is expressed as a percentage of the total power of unwanted harmonic distortion and noise that accompany the desired signal. This is a very important DAC characteristic for dynamic and small signal DAC applications.  Dynamic range: This is a measurement of the difference between the largest and smallest signals the DAC can reproduce expressed in decibels. This is usually related to resolution and noise floor

9.5 Instructions needed: 1. MOV-Copies byte or word from specified source to specified destination 2. IN-Copy a byte or word from specified port to accumulator 3. OUT- Copy a byte or word from accumulator to specified port 4. INC-Increments specified byte/word by 1 5. DEC-Decrements specified byte/word by 1 6. JZ-Jumps if equal to Zero 7. INT-Interrupt program execution, call service procedure 8. ADD- Adds specified byte to byte or word to word

9.6 Algorithm: 8255 Port Addresses: Port A = 61h Port B = 63h Port C = 65h CWR = 67h Control Word: Mode 0, port A & B as an output port and Port C as an input port 1 0 0 0 1 0 0 1 = 89h

9.6.1 Algorithm: Triangular Wave 1. Write control word to CWR 2. Enable latch by setting PB0 =1 3. Write 00 through AL to port A 4. Increment AL 5. Write value of AL to port A 6. Compare with FFh 7. Repeat if AL is not equal to FFh then go to step 5 8. Write value of AL to port A 9. Decrement AL 10. Compare with 00h 11. Repeat if AL is not equal to 00h then go to step 8

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 53 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

12. Go to step 3 13. Observe Triangular wave on CRO

9.6.2 Algorithm: Square W ave

1. Write control word to CWR 2. Enable latch by setting PB0 =1 3. Write 00 through AL to port A 4. Call delay 5. Write FF to port A 6. Go to step 3 for continuous wave 7. Observe square wave on CRO

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 54 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

9.6.3 Algorithm: Staircase Wave 1. Write control word to CWR 2. Enable latch by setting PB0 =1 3. Write 00 through AL to port A 4. Write Contents of Port A to CRO 5. Call delay 6. Add 33H to port A 7. Go to step 3 for continuous wave 8. Observe Staircase wave on CRO

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 55 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

9.6.4 Algorithm: Ramp Wave

1. Write control word to CWR 2. Enable latch by setting PB0 =1 3. Write 00 through AL to port A 4. Write Contents of Port A to CRO 5. Call delay 6. Increment contents of port A by one 7. Go to step 3 for continuous wave 8. Observe Staircase wave on CRO

9.7 Assignment Questions: 1. Define the following terms for D/A converters: 1. Resolution 2. Accuracy 3. Monotonicity 4. Conversion time. 5. Linearity 2. Explain the R/2R ladder technique of D/A conversion. What are the different sources of error in DAC?

9.8 Oral Questions: 1. How the Resolution of DAC is defined as? 2. What is D/A converter? 3. Name the type of D/A converting techniques with brief example 4. What are the disadvantages of DAC? 5. Give applications of DAC 6. What are sources of errors in DAC?

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 56 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Att (2) Perm(5) Oral(3) Total(10) Sign with Date

Assignment 10

Problem Definition: Write 8086 ALP to program 8254 in Mode 0, modify the program for hardware re-triggerable Mono shot mode. Generate a square wave with a pulse of 1 mS. Comment on the difference between Hardware Triggered and software triggered strobe mode. Observe the waveform at GATE & out pin of IC 8254 on CRO.

10.1 Prerequisite:  Concept of Timer

10.2 Learning Objectives:  Understand the interfacing of 8254 to 8086.

10.3 New Concepts:  Understand the mode 0 of 8254  Understand the mode 3 of 8254

10.4 Theory 8254: Programmable Interval Timer/Counter 10.4.1 Features of 8254  Compatible with All Intel and Most other Microprocessors  Handles Inputs from DC to 10 MHz  8 MHz 8254  MHz 8254-2  Status Read-Back Command  Six Programmable Counter Modes  Three Independent 16-Bit Counters  Binary or BCD Counting  Single a 5V Supply  Standard Temperature Range The Intel 8254 is a counter/timer device designed to solve the common timing control problems in microcomputer system design. It provides three independent 16-bit counters, each capable of handling clock inputs up to 10 MHz. All modes are software programmable. The 8254 is a superset of the 8253.The 8254 uses HMOS technology and comes in a 24-pin plastic or CERDIP package. It is a general purpose, multi-timing element that can be treated as an array of I/O ports in the system software. The 8254 solves one of the most common problems in any microcomputer system, the generation of accurate time delays under software control. Instead of setting up timing loops in software, the programmer configures the 8254 to match his requirements and programs one of the

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 57 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

counters for the desired delay. After the desired delay, the 8254 will interrupt the CPU. Software overhead is minimal and variable length delays can easily be accommodated. Some of the other counter/timer functions common to microcomputers which can be implemented with the 8254 are:  Real time clock  Event-counter  Digital one-shot  Programmable rate generator  Square wave generator  Binary rate multiplier  Complex waveform generator  Complex motor controller

10.4.2 Block Diagram of 8254

Figure 1Block Diagram of 8254

Data Bus Buffer: This 3-state, bi-directional, 8-bit buffer is used to interface the 8254 to the system bus Read/Write Logic: The Read/Write Logic accepts inputs from the system bus and generates control signals for the other functional blocks of the 8254. A1 and A0 select one of the three counters or the Control Word Register to be read from/written into. A ``low'' on the RD input tells the 8254 that the CPU is reading one of the counters. A ``low'' on the WR input tells the 8254 that the CPU is writing either a Control Word or an initial count. Both RD and WR are qualified by CS; RD and WR are ignored unless the 8254 has been

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 58 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

selected by holding CS low. Control Word Register: The Control Word Register is selected by the Read/Write Logic when A1,A0 = 11. If the CPU then does a write operation to the 8254, the data is stored in the Control Word Register and is interpreted as a Control Word used to define the operation of the Counters. The Control Word Register can only be written to; status information is available with the Read-Back Command. Counter 0, Counter 1, Counter 2: The Counters are fully independent. Each Counter may operate in a different Mode.

10.4.3 8254 SYSTEM INTERFACE: The 8254 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 system's 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 A0,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.

Figure 2 Interfacing of 8254 with 8086

10.4.4 Programming the 8254: Counters are programmed by writing a Control Word and then an initial count. The Control Words are written into the Control Word Register, which is selected when A1,A0 = 11. The Control Word itself specifies which Counter is being programmed.

Control Word Format: A1,A0 = 11, CS = 0, RD = 1, WR = 0.  By contrast, initial counts are written into the Counters, not the Control Word Register. The A1,A0 inputs are used to select the Counter to be written into. The format of the initial count is determined by the Control Word used. Write Operations: The programming procedure for the 8254 is very flexible. Only two conventions need to be remembered:  For each Counter, the Control Word must be written before the initial count is written.  The initial count must follow the count format specified in the Control Word (least significant byte only, most significant byte only, or least significant byte and then most significant byte).

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 59 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

 Since the Control Word Register and the three Counters have separate addresses (selected by the A1,A0 inputs), and each Control Word specifies the Counter it applies to (SC0,SC1 bits), no special instruction sequence is required.

Figure 3 Control word Format with valid combinations  A new initial count may be written to a Counter at any time without affecting the Counter's programmedMode in any way. Counting wil l be affected as described in the Mode definitions. The new count must follow the programmed count format.  If a Counter is programmed to read/write two-byte counts, the following precaution applies: A program must not transfer control between writing the first and second byte to another routine which also writes into that same Counter. Otherwise, the Counter will be loaded with an incorrect count.

10.4.5 Modes of 8254 Mode 0: Interrupt On Terminal Count : Mode 1: Hardware Retriggerable One-Shot: Mode 2: Rate Generator: Mode 3: Square Wave Mode: Mode 3: Even Counts: Mode 4: Software Triggered Strobe: Mode 5: Hardware Triggered Strobe (Retriggerable):

10.4.6 Operation Common to All Modes: Programming:  When a Control Word is written to a Counter, all Control Logic is immediately reset and OUT goes to a known initial state; no CLK pulses are required for this. Gate:  The GATE input is always sampled on the rising edge of CLK. In Modes 0, 2, 3, and 4 the GATE input is level sensitive, and the logic level is sampled on the rising edge of CLK. In Modes 1, 2, 3, and 5 the GATE input is rising-edge sensitive.  In these Modes, a rising edge of GATE (trigger) sets an edge-sensitive flip-flop in

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 60 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

the Counter. This flip-flop is then sampled on the next rising edge of CLK; the flip- flop is reset immediately after it is sampled. In this way, a trigger will be detected no matter when it occurs-a high logic level does not have to be maintained until the next rising edge of CLK.  Note that in Modes 2 and 3, the GATE input is both edge- and level-sensitive. In Modes 2 and 3, if a CLK source other than the system clock is used, GATE should be pulsed immediately following WR of a new count value. Counter:  New counts are loaded and Counters are decremented on the falling edge of CLK.  The largest possible initial count is 0, this is equivalent to 216 for binary counting and 104 for BCD counting. The Counter does not stop when it reaches zero.  In Modes 0, 1, 4, and 5 the Counter ``wraps around'' to the highest count, either FFFF hex for binary counting or 9999 for BCD counting, and continues counting.  Modes 2 and 3 are periodic; the Counter reloads itself with the initial count and continues counting from there. Write Operations:  The programming procedure for the 8254 is very flexible. Only two conventions need to be remembered:  For each Counter, the Control Word must be written before the initial count is written.  The initial count must follow the count format specified in the Control Word (least significant byte only, most significant byte only, or least significant byte and then most significant byte).  Since the Control Word Register and the three Counters have separate addresses (selected by the A1,A0 inputs), and each Control Word specifies the Counter it applies to (SC0,SC1 bits), no special instruction sequence is required. Read Operations:  It is often desirable to read the value of a Counter without disturbing the count in progress. This is easily done in the 8254.  There are three possible methods for reading the counters: a simple read operation, the Counter Latch Command, and the Read-Back Command.

10.5 Instructions needed: 12. MOV-Copies byte or word from specified source to specified destination 13. INC-Increments specified byte/word by 1 14. DEC-Decrements specified byte/word by 1 15. JNZ-Jumps if not equal to Zero 16. CMP-Compares to specified bytes or words 17. ADD-Adds specified byte to byte or word to word

10.6 8254 Addresses: Counter0 = 30h Counter1 = 31h Counter2 = 32h CWR = 33h

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 61 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

10.7 MODE '0' Program: Interrupt on terminal count Control Word: Mode 0, binary counter, counter0, LSB & MSB count

0 0 1 1 0 0 0 0 = 30h Algorithm: 1. Write CW to CWR 2. Load LSB count 3. Load MSB count 4. Stop. Procedure: 1) Connect pulse Clk to Clk 0. 2) Connect Gate 0 to Vcc. 3) Execute Program 4) Press pulsar key 7 Times. 5) Connect (Active Low) out0 to IRQ7 (RST7.5) Connections: 1) Connect pulsar clock to clock 2) Gate to Vcc 3) Connect IRQ7 to out after executing of the program & then press the pulsar Key.

Program: Dyna-86>

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 62 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

10.8 MODE ‘3’: Square wave Generator Control Word: Mode 3, binary counter, counter0, LSB & MSB count

0 0 1 1 0 1 1 0 = 36h Algorithm: 1. Write CW to CWR 2. Load LSB count 3. Load MSB count 4. Execute program 5. Observe waveforms 4. Stop. Procedure: 1) Connect pulse Clk to Clk 0. 2) Connect Gate 0 to Vcc. 3) Execute Program 4) After pressing the Pulsar key 5 Times LED will glow low & after 2 Pulse, It will go high. Program

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 63 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

10.9 Theory Questions 1. Control Word Format 2. Write operation of 8254 3. Read operation of 8254 4. Counter Latch Command and Read Back Command

10.10 Oral Questions 1 What are the applications of 8254? 2 Specify the various modes of 8254 3 What is the control word used in mode0 and mode3? 4 List the steps performed for the connections for interfacing of 8254 with 8086 5 Give the components of 8254

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 64 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Att (2) Perm(5) Oral(3) Total(10) Sign with Date

Assignment 11

Problem Definition: Perform an experiment to establish communication between two 8251 systems A and B. Program 8251 system A in asynchronous transmitter mode and 8251 system B in asynchronous receiver mode. Write an ALP to transmit the data from system A and receive the data at system B. The requirements are as follows: Transmission: • message is stored as ASCII characters in the memory. • message specifies the number of characters to be transmitted as the first byte. Reception: • Message is retrieved and stored in the memory. • Successful reception should be indicated.

11.1 Prerequisite:  Concept of Synchronous and Asynchronous Transmission

11.2 Learning Objectives:  Understand the interfacing of 8251 to 8086.

11.3 New Concepts:  Understand the Synchronous and Asynchronous Transmission of 8251

11.4 Theory 8251 Universal Synchronous Asynchronous Receiver Transmitter (USART)  USART stands for Universal Synchronous Asynchronous Receiver Transmitter. It is sometimes called the Serial Communications Interface or SCI.  Synchronous operation uses a clock and data line while there is no separate clock accompanying the data for Asynchronous transmission.  Since there is no clock signal in asynchronous operation, one pin can be used for transmission and another pin can be used for reception.  Both transmission and reception can occur at the same time — this is known as full duplex operation.  Transmission and reception can be independently enabled. However, when the

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 65 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

serial port is enabled, the USART will control both pins and one cannot be used for general purpose I/O when the other is being used for transmission or reception.  The USART is most commonly used in the asynchronous mode. The most common use of the USART in asynchronous mode is to communicate to a PC serial port using the RS-232 protocol.  The USART can both transmit and receive, and we will now briefly look at how this is implemented in the USART.  The USART can be configured to transmit eight or nine data bits by the TX9 bit in the TXSTA register. If nine bits are to be transmitted, the ninth data bit must be placed in the TX9D bit of the TXSTA register before writing the other eight bits to the TXREG register.  Once data has been written to TXREG, the eight or nine bits are moved into the transmit shift register. From there they are clocked out onto the TX pin preceded by a start bit and followed by a stop bit.  The use of a separate transmit shift register allows new data to be written to the TXREG register while the previous data is still being transmitted. This allows the maximum throughput to be achieved.

11.5 Block diagram of the 8251 USART The 8251 is a USART (Universal Synchronous Asynchronous Receiver Transmitter) for serial data communication. As a peripheral device of a microcomputer system, the 8251 receives parallel data from the CPU and transmits serial data after conversion. This device also receives serial data from the outside and transmits parallel data to the CPU after conversion.

Figure 1Block diagram of the 8251 USART

The 8251 functional configuration is programmed by software. Operation between the 8251 and a CPU is executed by program control. Table 1 shows the operation between a CPU and the device.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 66 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Table 1Operation between a CPU and 8251

Control Words There are two types of control word. 1. Mode instruction (setting of function) 2. Command (setting of operation)

1) Mode Instruction Mode instruction is used for setting the function of the 8251. Mode instruction will be in "wait for write" at either internal reset or external reset. That is, the writing of a control word after resetting will be recognized as a "mode instruction." Items set by mode instruction are as follows: • Synchronous/asynchronous mode • Stop bit length (asynchronous mode) • Character length • Parity bit • Baud rate factor (asynchronous mode) • Internal/external synchronization (synchronous mode) • Number of synchronous characters (Synchronous mode) The bit configuration of mode instruction is shown in Figures 2 and 3. In the case of synchronous mode, it is necessary to write one-or two by te sync characters. If sync characters were written, a function will be set because the writing of sync characters constitutes part of mode instruction.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 67 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

2) Command Command is used for setting the operation of the 8251. It is possible to write a command whenever necessary after writing a mode instruction and sync characters.

Items to be set by command are as follows: • Transmit Enable/Disable • Receive Enable/Disable • DTR, RTS Output of data. • Resetting of error flag. • Sending to break characters

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 68 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

• Internal resetting • Hunt mode (synchronous mode)

Status Word It is possible to see the internal status of the 8251 by reading a status word. The bit configuration of status word is shown in Fig. 5.

11.6 Instructions needed: 1 MOV-Copies byte or word from specified source to specified destination 2 ROR-Rotates bits of byte or word right, LSB to MSB and to CF 3 AND-AND each bit in a byte or word with corresponding bit in another byte or word 4 INC-Increments specified byte/word by 1 5 DEC-Decrements specified byte/word by 1 6 JNZ-Jumps if not equal to Zero 7 JNC-Jumps if no carry is generated 8 CMP-Compares to specified bytes or words 9 JBE-Jumps if below of equal 10 ADD-Adds specified byte to byte or word to word 11 CALL-Transfers the control from calling program to procedure

11.7 8251 Addresses Data = 9000h CWR = 9002h a. Mode word: Async mode, Baud rate 1/16, Character length 8-bits, odd parity, and one stop bit

0 1 0 1 1 1 1 0 = 5Eh b. Command word:

Transmit enable & reset error flags 0 0 0 1 0 0 0 1 = 11h

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 69 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

11.8 Algorithm: 1 Send mode word to both 8251 2 Write command word to both 8251 3 Initialize memory pointers 4 Set counter equal to number of bytes to be transferred 5 Check TxRDY status for transmission to begin 6 Write data for transmission using SI 7 Check RxRDY status for reception of data 8 Read received data 9 Save using DI 10 Increment both pointers 11 Decrement the counter 12 Repeat steps 6 to 11 till counter becomes zero. 13 Stop

11.9 Connections: 1. DSRA AND CTSA CONNECTED TO GND 2. RTS B AND DTRB CONNECTED TO GND 3. TXDA TO RXDB 4. CLK TO AUTO CKL

11.10 Program

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 70 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 71 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

11.11Theory Questions 1 Asynchronous Serial Communication with Synchronous Communication. 2 Interfacing diagram of 8251 USART with 8086

11.12 Oral Questions 1 What is the control word used? 2 What is the port address of CWR? 3 What is USART? 4 What is the difference between 8250 and 8251? 5 Write the connections of 8251? 6 After data transfer how to see the contents that are transferred?

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 72 Microprocessor and Interfacing Laboratory Second Year Computer Engineering

Att (2) Perm(5) Oral(3) Total(10) Sign with Date

Assignment 12

Problem Definition: Write a TSR program in 8086 ALP to Implement Real Time Clock (RTC). Read the Real Time from CMOS chip by suitable INT and FUNCTION and display the RTC at the bottom right corner on the screen! Access the video RAM directly in your routine.

12.1 Prerequisite:  Interrupt Vector table (IVT)  Program Segment Prefix (PSP)  COM program  Interrupt Service Routine (ISR).

12.2 Learning Objectives:  Implementation of the TSR  Structure of TSR & Loading of TSR  Conversion of .EXE file to a.COM file

12.3 New concepts:  What is TSR / Memory Resident program  Working of TSR with DOS

12.4 Theory 12.4.1 TSR: Terminate but stay resident programs It is Terminate but stay resident programs. These programs begin when we run program and stay in memory ready for use, even if they are not active on your screen.TSR is divided into resident routine & initialization routine. Objective of initialization routine is to make resident program routine stay resident in memory. It executes only once. Here we modify interrupt vector table (IVD entries so that New addresses point to resident program. When TSR is activated by any interrupt, program control is first transferred to resident program & after execution of resident program; control is transferred to original ISR of requested interrupt.  Get interrupt vector : 35h (interrupt no in AL)  Set interrupt vector : 25h (interrupt no in AL)  Terminate & stay resident : 31h (size of program in DX)

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 73 Microprocessor Interfacing Laboratory Second Year computer Engineering

MS-DOS TSR map High memory

HEAP

STACK 64k block DATA Addressable From DS CODE

Low memory

If a TSR is created in assembly language, the programmer has exact control over the use of memory and can omit the heap area and place the initialization code at the end of the segment (where It can be released after initialization) Variables required by MS-DOS interrupt handlers must be placed at low memory tie beginning of the code segment.

If a TSR is created in C, the small-memory model must be used Because of the severe memory limitations, the programmer should not use C allocation functions (such as malloc and calloc), as these add to the heap. A small heap must be assigned because some C library routines (such as fprintf) Allocate memory from the heap.

12.4.2 Software Interrupt  Software interrupts are used by programs to request system services  A software interrupt occurs when a program calls an interrupt routine using the INT instruction.  The format of the INT instruction is

INT interrupt number.

 The 8086 treats this interrupt number in the same way as the interrupt number generated by a hardware device.  We have already seen a number of examples of this using INT 21h.

How program works A time representation is 00.00:00

 Three steps o obtains the current time (procedure GET TIME) o converts the hours, minutes ,and seconds-into ASCII digits (ignore the fractions of seconds) o display the time and terminates INT 0AH:-real time clock controller. Time of Day: allows a program to get and set the timer tick count.

This interruption allows access to system's clock, for reading and setting the time.  Time Of Day

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 74 Microprocessor Interfacing Laboratory Second Year computer Engineering

Function: - AH = 02h: - READ Time  Input: o None  Output: CF = 0, CF=1- Clock not operating o CH = hours (0 - 23) o CL = minutes (0 - 59) o DH = seconds (0 - 59) o DL = 1/100 seconds (0 - 99)  rains the time: hours, minutes, seconds, and hundredths of seconds

The hour is represented as units; one unit has 55ms. When the system is on the number of unit increases every 55ms. For AT class computers through this interruption BIOS gives access to system's RTC. The RTC run even when the computer is off because of the battery on mainboard. It uses a memory segment from CMOS to store the time. This memory segment is rewritten every 55ms without using the microprocessor.

INT 21h, Function 25h  Set Interrupt Vector Store interrupt vector into vector table o Input: AH = 25h, AL. = Interrupt number. DS: DX = interrupt vector o Output: None The procedure SETUP_INT in program saves an old interrupt vector and sets up a new vector It gets the interrupt number in AL, a buffer to save the old vector at aside, and a buyer containing the new interrupt vector at DS:SI By reversing the two buffers, SETUP_ INT can also be used to restore the old vector  Move Cursor Input: e.g.:- 2140 o DH = new cursor row (0-24) o DL = new cursor column (0-79 for 80x25 mode) Output: none

INT 21h: Function 35h

Terminates execution of the currently executing program, passing a return code to the parent process, but reserves part or all of the program's memory so that it will not be overlaid by the next transient program to be loaded.

Call with: AH = 31H, AL = return code, DX = amount of memory to reserve (in paragraphs)

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 75 Microprocessor Interfacing Laboratory Second Year computer Engineering

Returns: Nothing Example: Exit with a return code of 1 but stay resident, reserving 16 KB of memory starting at the program segment prefix of the process.

MOV AH, 31H ; function number MOV AL, 1 ; return code for parent MOV DX, 0400H ; paragraphs to reserve INT 21H ; transfer to MS-DOS

ORG: - Sets the current origin to a new value.

For example: ORG 0100h tells the assembler to assemble all subsequent code ' starting at address 0100h DD: - allocates and initializes double word of storage.

12.5 Algorithm: 1. Start 2. Write initialization routine 3. Write Resident routine 4. End

Resident Routine 1. Push all register to sick 2. Read time from clock chip by time read function. 3. Set address of video RAM 4. Set specific offset in video RAM 5. Transfer hour, minute & second value to video RAM 6. Pop all register values 7. Transfer control to original service routine address

Initialization Routine 1. Read Interrupt vector address of int_08h (clock interrupt). 2. Save that 32 bit address 3. Replace address of int_08h in IVT by Resident Routine 4. Make the routine resident using DOS function.

12.6 Assignment Questions: 1. What is TSR? Explain the Structure of TSR with suitable example. 2. How it is made Resident in the memory? Can we remove it? If yes how?

12.7 Oral Questions: 1. Explain the Instructions used in the program. 2. Which assembler directives are used in the program? 3. Where interrupt vector table of 8086 is? Is it in the RAM or ROM? 4. What is the use of Interrupt vector table of 8086 microprocessor? 5. What is interrupt in 8086? 6. What is interrupt service routine?

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 76 Microprocessor Interfacing Laboratory Second Year computer Engineering

Att (2) Perm(5) Oral(3) Total(10) Sign with Date

Assignment 12(OR)

Problem Definition: Write a TSR program in 8086 ALP to implement Screen Saver. Screen Saver should get activated if the keyboard is idle for 7 seconds. Access the video RAM directly in your routine.

13.1 Prerequisite:  Concept of Screen Saver

13.2 Learning Objectives:  Implementation Screen Saver application Using TSR

13.3 New Concepts:  Applying the counter and keyboard INT in TSR  Applying the INT 10H in TSR.

13.4 Theory Hardware Interrupt  Whenever a key is pressed, the CPU must be notified to read a key code into the keyboard buffer  The general hardware interrupt goes like this:  a device that needs service sends an interrupt request signal to the processor o The CPU suspends the current task aid transfers control to an interrupt routine. o The interrupt routine services the hardware device by performing some i/0 operation. o Control is transferred back to the original executing task at the point where it was suspended.  Interrupt 9 - Keyboard: generated by the keyboard whenever a key is pressed or released o The service routine reads a scan code and stores it in the keyboard buffer. Acknowledging an Interrupt  Because an interrupt signal may come at any time, the CPU checks for the signal after executing each instruction.  On detecting the interrupt signal, the CPU acknowledges it by sending an interrupt acknowledge signal.  The interrupting device responds by sending an eight-bit number on the data bus, called an interrupt number  Each device uses a different interrupt number to identify its own service routine.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 77 Microprocessor Interfacing Laboratory Second Year computer Engineering

 This process is called hand-shaking

Transferring to an Interrupt Routine  The process is similar to a procedure call  Before transferring control to the interrupt routine, the CPU first saves the address of the next instruction on the stack; this is the return address  The CPU also saves the FLAGS register on the stack; this ensures that the status of the suspended task will be restored.  It is the responsibility of the interrupt routine to restore any registers it uses

INT 10h / AH = 0 - set video mode. Input: AL = desired video mode.

These video modes are supported:

00h - text mode. 40x25. 16 colors. 8 pages.

03h - text mode. 80x25. 16 colors. 8 pages.

13h - graphical mode. 40x25. 256 colors. 320x200 pixels. 1 page. Example:

MOV AL, 13H MOV AH, 0 INT 10H

INT 10h / AH = 2 - set cursor position. Input: DH = row. DL = column. BH = page number (0..7). Example:

MOV DH, 10 MOV DL, 20 MOV BH, 0 MOV AH, 2 INT 10H

INT 10h / AH = 03h - get cursor position and size. Input: BH = page number. Return: DH = row. DL = column. CH = cursor start line. CL = cursor bottom line.

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 78 Microprocessor Interfacing Laboratory Second Year computer Engineering

INT 10h / AH = 05h - select active video page. Input: AL = new page number (0..7). The activated page is displayed.

INT 10h / AH = 09h - write character and attribute at cursor position. Input: AL = character to display. BH = page number. BL = attribute. CX = number of times to write character. Attribute bit color table: Character attribute is 8 bit value, low 4 bits set fore color, high 4 bits set background color.

HEX BIN COLOR

0 0000 black 1 0001 blue 2 0010 green 3 0011 cyan 4 0100 red 5 0101 magenta 6 0110 brown 7 0111 light gray 8 1000 dark gray 9 1001 light blue A 1010 light green B 1011 light cyan C 1100 light red D 1101 light m.agenta E 1110 yellow F 1111 white

13.5 Algorithm: 1. Start 2. Write initialization routine 3. Write Resident routine 4. End

Resident routine Count routine 1. Push all register to stack 2. Increment count 3. If count<=5 second goto step 4 4. Set address of video RAM 5. Transfer ‘Screensaver” message to video RAM 6. Pop all register values 7. Transfer control to original service routine address of int_08 Key press routine 1. Push all register to stack

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 79 Microprocessor Interfacing Laboratory Second Year computer Engineering

2. Set count = 0 3. Pop all register values 4. Transfer control to original service routine address of int_09

Initialization routine 1. Read interrupt vector address of int_08h (clock interrupt) 2. Save that 32 bit address 3. Replace address of int_08h in IVT by count resident routine 4. Read interrupt vector address of int_09h (keypress) 5. Save that 32 bit address 6. Replace address of int_09h in IVT by keypress resident routine 7. Make both routine residents using DOS function.

13.6 Assignment Questions: 1. What will happen on memory if same TSR is loaded ‘n’ time (n=15) 2. Explain the difference between typical.COM program & a TSR program is a TSR.A system program

13.7 Oral Questions: 1. How does the CPU find out a device is signaling? 2. How does it know which interrupt routine to execute? 3. How does it resume the previous task?

SNJB’s Late Sau. KBJ COLLEGE OF ENGINEERING Page 80