0% found this document useful (0 votes)
491 views214 pages

Chapter 6 - 10

This chapter describes 8086 instructions and assembler directives in two sections. The first section provides detailed descriptions of 8086 instructions, including operation, syntax, flags affected, and examples. The second section describes commonly used assembler directives for the Intel 8086 macro assembler and Borland Turbo Assembler. The chapter serves as a reference for instruction details and directives when writing or reading 8086 assembly programs.

Uploaded by

pradeep bhardwaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
491 views214 pages

Chapter 6 - 10

This chapter describes 8086 instructions and assembler directives in two sections. The first section provides detailed descriptions of 8086 instructions, including operation, syntax, flags affected, and examples. The second section describes commonly used assembler directives for the Intel 8086 macro assembler and Borland Turbo Assembler. The chapter serves as a reference for instruction details and directives when writing or reading 8086 assembly programs.

Uploaded by

pradeep bhardwaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 214

8086 Instruction Descriptions

and Assembler Directives

This chapter consists of two major sections. The first ADD AL. BL : Result: AL = 0110 1110 = 6EH. which
section isa dictionary of all the 808618088 Instructions. is incorrect BCD
For each instruction. we give a detailed description of AAA Now AL = 00000100. unpacked BCD 4.
its operation, the correct syntax for the instruction, and CF = I indicates answer is 14 decimal
the flags affected by the instruction. Numerical examples
are shown for those instructions for which they are NOTE: OR AL with 30H to get 34H. the ASCII
appropriate. Instead of putting the binary codes for the code for 4. If you want to send the result back to
instructions here, we have listed them alphabetically in a CRT terminal. The I in the carry flag can be
Appendixcs A and B. Putting the codes together in a rotated into the low nibble of a register. ORed with
table makes them easier to find if you are hand coding 30H to give the ASCIi code for 1. and then sent to
a program. the terminal.
Thc second major section of this chapter is a dictionary
of commonly used 8086 assembler directives. The direc- The AAA Instruction works only on the AL register.
tives described here are those defined for the Intel The AAA instruction updates AF and CF. but OF. PF,
8086 macro assembler, the Microsoft macro assembler SF, and ZF are left undefined.
IMASM). and the Borland Turbo Assembler (TASMI. If
you are using some other assembler, it probably has
similar capabilities, but the names may be different. AAD—BCD-to-Binary Convert before Division
You will probably use this chapter mostlyas a reference
to get the details of an Instruction or directive as you AAD converts two unpacked BCD digits in AU and AL
write programs of your own or decipher someone else's to the equivalent binary number in AL. This adjustment
programs. However, you should skim through the chap- must be made before dividing the two unpacked BCD
ter at least once to give yourself an overview of the digits in AX by an unpacked BCD byte. After the division,
material It contains. You should not try to absorb all of AL will contain the unpacked BCD quotient and AU will
contain the unpacked HCD remainder. PF. SF. and ZF
this chapter at once. Many of the Instructions described
are used and discussed In various example programs are updated. AF, CF. and OF are undefined after AAD.
throughout the book. For these instructions, we have
included references to the appropriate sections in the EXAMPLE;
text.
AX - 0607H unpacked L3CD for 67 decImal
CU 09H. now adjust to binary
INSTRUCTION DESCRIPTIONS AAD : Result; AX 0043 = 4311 6' ......
DIV CII - Divide AX by unpacked DCI) iii
AAA—ASCII Adjust for Addition Quotient; AL 07 unpacked DCI
Numerical data coming into a computer from a terminal Remainder; AH 04 unpacked DCI)
is usually in ASCII code. In this code, the numbers 0 to Flags undefined after DIV
9 are represented b y the ASCII codes 30H to 39H. The
8086 allows y ou to add the ASCII (-odes for two di-cuual NOTE If an attempt Is made to divide b y 0. the
8086 will do a t ype 0 Interrupt. The type 0 Interrupt
digits without maskini off the 3 in the upper nibble
of each After the addition, the AAA instruction Is used response is described in Chapter 8.
to ritaki' sure the result is the correct unpacked UC[). A
si mplt- nit tncrical cxarttple will show how this works. AAM—BCD Adjust after Multiply
fiefore you can multipl y two ASCII digits. you must first
I
mask the upper 4 hits of each. This eaves unpacked
Assume Al. - 0011 0101. ASCII 5 DCL) lone F3CD dtit per b\leJ in each h1e After the two
[II. - 0011 1001. ASCII 9 unpacked [ICE) digits are multiplied, the Instr-iic-

-19 131
tion is used to adjust the product to two unpacked BCL) ADC—Add with Carry—ADC Oestination,Soutce
digits In AX.
ADD—Add—ADD Destination,Source
AAM works only after the multiplication of two un-
packed BCD bytes, and it works oniy on an operand in These instructions add a number from some source to
AL. AAM updates PF. SF. and ZF, but AF. CF. and OF a number from some destination and put the result in
are left undefined. the specified destination. The Add with Carry instruc-
tion, ADC, also adds the status of the carry flag into the
EXAMPLE result. The source may be an immediate number, a
register, or a memory location specified by any one of
AL 00000101 = unpacked BCD S the 24 addressing modes shown in Figure 3-8. The
BI-I = 00001001 = unpacked BCD 9 destination may be a register or a memory location
MULBH ;ALXBH;resuitinAX specified by any one of the 24 addressing modes in Figure
AX = 0000000000101101 OO2DH 3-8. The source and the destination in ari instruction
AAM ; AX = 00000100 00000101 = 0405H, cannot both be memory locations. The source and the
which is unpacked BCD for 45. destination must be of the same type. In other words.
If ASCII codes for the result are they must both be byte locations, or they must both be
desired. use next instruction word locations. If you want to add a byte to a word, you
OR AX.30301-1 Put 3 in upper nibble of each byte. must copy the byte to a word location and fill the upper
:AX = 001 10100 001 101Ot = 3435H. byte of the word with 0's before adding. Flags affected:
which is ASCII code for 45 AF, CF. OF, PF, SF, ZF.

AAS—ASCII Adjust for Subtraction EXAMPLES (CODING):


Numerical data coming into a computer from a terminal
Add immediate number 74H to
is usually in ASCII code. In this code the numbers 0 to ADD AL.74H
9 are represented by the ASCII codes 30H to 39H. The ; contents of AL. Result In AL
8086 allows you to subtract the ASCII codes for two
Add contents of BL plus carry
decimal digits without masking the "3" in the upper
status
nibble of each. The AAS instruction is then used to ADC CL,BL ; to contents of CL.
make sure the result is the correct unpacked BCD. Some
simple numerical examples will show how this works.
Add contents of BX
ADD DX,BX ; to contents of DX
EXAMPLE
Add word from memory at offset
ASCII 9-ASCII 5 (9-5)
ISI I
;AL=O011lQOl 39H=ASCII9 ADD D X.ISII in DS to contents of DX
BL = 00110101 = 35H ASCII 5
SUB AL, 13L ; Result: AL = 00000100 = BCD 04
Add byte from effective
and CF = 0
AAS ADC AL,PRICESIBXI ; address PRICESIBXI plus carry
Result: AL = 00000100 = BCD 04
status to Contents of AL
and CF = 0; no borrow required
Add contents of AL to
ASCII 5-ASCII 9 (5-9) ADD PRICES)BXI,AL ; contents of memory location at
;AssumeAL = 001 10101 = 35H =
effective address PRICESIBXI
ASCII 5
and BL = 00111001 = 39H = ASCII 9
SUB AL, BL ; Result: AL 11111100 4 EXAMPLES (NUMERICAL):
in 2s complement and CF
AAS : Result: AL = 00000100 = BCD 04 Addition of unsigned numbers
and CF = I; borrow needed ;CL = 01110011 = 115 decimal
+ BL = OlO011il = 79 decimal
The AAS instruction leaves the correct unpacked BCD ADD CL.BL ; Result in CL
result in the low nibble 0IAL and resets the upper nibble ;CL = 11000010 194 decimal
of AL to all 0's. If you want to send the result back to a
CRT terminal, you can OR AL with 30H to produce
the correct ASCII code for the result. If multiple-digit Addition of signed numbers
numbers are being subtracted, the CF can be taken into CL = 01110011 = + 115 decimal
account by using the SBB instruction when subtracting + RI. 01001111 = + 79 decimal
the next digits. ADD CL.BL : Result in CL
The AAS instruction works only on the AL register. It CL 11000010 - 62 decimal—
updates AF and CF. but OF. PF, SF. and ZF are left incorrect because result too large to fit
u ndefi ned. in 7 bits

132 CHAPTER SIX


FLAG RESULTS FOR SIGNED ADDITION EXAMPLE EXAMPLE (NUMERiCAL):
CF = 0 No carry Out of bit 7.
PF 0 Result has odd parity. BX= 1011001! 01011110
AF = 1 Carry was produced Out of bit 3. AND BX.00FFH : Mask out upper 8 bits of BX
ZF 0 Result in destination was not 0. Result: BX = 00000000 01011110
SF = I Copies most significant bit of result: indicates CF. OF, PF. SF. ZF = 0
negative result if you are adding signed
numbers. CALL—Call a Procedure
OF 1 Set to indicate that the result of the addition
was too large to fit in the lower 7 bits of the The CALL instruction is used to transfer execution to a
destination used to represent the magnitude subprogram or procedure. There are two basic types of
of a signed number. In other words, the result calls, near andJar. A near call is a call to a procedure
was greater than + 127 decimal, so the result which is in the same code segment as the CALL instruc-
overflowed into the sign bit position and incor- tion. When the 8086 executes a near CALL instruction,
rectly indicated that the result was negative. it decrements the stack pointer by 2 and copies the
If you are adding two signed 16-bit values, the offset of the next instruction after the CALL Onto the
OF will be set if the magnitude of the result is stack. This offset saved on the stack is referred to as
too large to fit in the lower 15 bits of the the return address, because this is the address that
destination. execution will return to after the procedure executes. A
near CALL instruction will also load the instruction
NOTE: PF is meaningful Only for an 8-bit result. pointer with the offset of the first instruction in the
AF is set only by a carry out of bit 3. Therefore, procedure. A RET instruction at the end of the procedure
the DAA instruction cannot be used after word will return execution to the instruction after the call by
additions to convert the result to correct BCD. copying the offset saved on the stack back to IP.
A far call is a call to a procedure which is in a
different segment from the one that contains the CALL
AND—AND Corresponding Bits of Two instruction. When the 8086 executes a far call, it decre-
Operands—AND DestinationSource ments the stack pointer by 2 and copies the contents of
This instruction ANDs each bit in a source byte or word the CS register to the stack. It then decrements the
with the same number bit in a destination byte or word. stack pointer by 2 again and copies the offset of the
The result is put in the specified destination. The instruction after the CALL instruction to the stack.
contents of the specified source will not be changed. The Finally. it loads CS with the segment base of the segment
result for each bit position will follow the truth table for which contains the procedure, and loads IP with the
a two-input AND gate. In other words, a bit in the offset of the first instruction of the procedure in that
specified destination will be a I only if that bit is a 1 in segment. A RET instruction at the end of the procedure
both the source and the destination operands. There- will return execution to the next instruction after the
fore, a bit can be masked (reset) by ANDing it with 0. CALL by restoring the saved values of CS and IP from
The source operand can be an Immediate number. the stack.
the contents of a register. or the contents of a memory
location specified by one of the 24 addressing modes EXAMPLES:
shown in Figure 3-8. The destination can be a register
or a memory location. The source and the destination CALL MULTO A direct within . segment (near or intra-
cannoi both be memory locations in the same instruc- segment) call. MULTO is the name of the procedure. The
tion. CF and OF are both 0 after AND. PF, SF. and ZF assembler determines the displacement of MULTO from
are updated by AND. AF is undefined. Note that PF has the Instruction after the CALL and codes this displace-
meaning only [or an 8-bit operand. ment In as part of the instruction.

CALl. BX : An indirect within-segment near or Intraseg-


ment call. [IX contains the offset of the first Instruction
of the procedure. Replaces contents of IP with contents
EXAMPLES (CODING): of register DX.

AND word in DS at offset ISII CALl. WORD l'TR IBX) An indirect within-segment
with word in CX register near or intrasegment call. Offset of first Instruction of
AND CX.ISU Result In CX register procedure is In two memory addresses In DS. Replaces
contents of IP with contents of word memory location
AND 8l-1.CL : AND byte in CL with b yte in WI in DS pointed to by DX.
Result In BR
CALL SMART_DIVIDE : A direct call to another seg.
AND word in DX with immediate ment—far or Intersegment call. SMART_DIViDE Is the
AND BX.00FFI-j : OOFFFI. Masks upper b yte, leaves name of the procedure. The procedure must be declared
nwer b y te unchanged far with SMART_DIVIDE PROC FAR at Its start (see

8I8, NSTRLCTIQN DESCRIPTIONS AND ASSEMBLER DIREcTISES 133


(hapter SI. The assembler will determine the code CMC—Complement the Carry Flag
segment b.se Lou (lie segment whkh ontaliis the pioee-
dure and the offset of the start of the procedure. It will If the carry flag (CFI is a 0 before this instruction, it will
put these values In as part of the instruction code. be set to a I after the Instruction. If the carry flag is I
before this instruction, It will be reset to a 0 after the
CALL DWORD PTRIBXI An Indirect call to another Instruction executes. CMC affects no other flags.
segment_far or intersegment call. New values for CS
and IP are fetched from four memory locations in DS. EXAMPLE:
The new value br CS is fetched from (BXI and IBX 4- 1 I:
the new IF is fetched from IBX + 21 and 113X + 31. CMC Invert the carry flag

CBW—Convert Signed Byte to Signed Word CMP—Compare Byte or Word—CMP


Destination,Source
This instruction copies the sign of a byte in AL to all
the bits in AH. AH is then said to be the sign extenswn This instruction compares a byte from the specified
of AL. The CBW operation must be done before a signed source with a byte from the specified destination, or a
byte in AL can be divided by another signed byte with word from the specified source with a word from the
the iDly instruction. CBW affects no flags. specified destination. The source can be an immediate
number, a register, or a memory location specified by
one of the 24 addressing modes shown in Figure 3-8.
EXAMPLE
The destination can be a register or a memory location.
However, the source and the destination cannot both
;AX = 00000000 10011011 = - 155 decimal
be memory locations in the same Instruction. The
CBW Convert signed byte in AL to signed word in AX
comparison is actuall y done by subtracting the source
Result: AX = 11111111 10011011 - 155
byte or word from the destination byte or word. The
decimal
source and the destination are not changed. but the
flags are Set to Indicate the results of the comparison.
For further examples of the use of CBW. see the IIDW
AF, OF. SF, ZF. PF. and CF are updated by the CMP
instruction description.
Instruction. For the instruction CMP CX.BX, CF. ZF,
and SF will be left as follows:
CIC—Clear the Carry Flag (CF)
CF ZF SF
This instruction resets the carry flag toO. No other flags CX = BX 0 1 0 Result of subtraction Is 0
arc affected. CX > BX 0 0 0 No borrow required, so CF = 0
CX < BX 1 0 1 : Subtraction required
EXAMPLE borrow, so CF 1

CLC EXAMPLES:

Compare Immediate number


CLD—Clear Direction Flag CMP AL.OIH : OIH with byte in AL

This instruction resets the direction flag to 0. No other Compare byte in CL with
flags are affected. If the direction flag is reset, SI and DI CMPBH.CL byte in BU
will automatically be incremented when one of the string
instructions, such as MOVS. CMPS. or SCAS. executes. Compare word in DS at
Consult the string instruction descriptions (or examples displacement TEMP_MIN
of the use of the direction flag. CMP CX,TEMP_MIN with word in CX

Compare CX with word In DS


EXAMPLE
CMP TEMP_MAX.CX at displacement TEMP_MAX
CLD : Clear direction flag so (hat string pointers
Compare Immediate 49H
autoincrement after each string operation
CMP PRICESIBXI.49H with byte at offset
IBXI in array PRICES
CLI—Clear Interrupt Flag
NOTE: The Compare Instructions are often used
This instruction resets the interrupt flag to 0. No other with the Conditional Jump Instructions, described
flags are affected. If the interrupt flag is reset, the 8086 in a later section. Having the Compare instructions
will not respond to an interrupt signal on its INTR Input. formatted the way they are makes this use very easy
The CLI Instruction, however, has no effect on the to understand. For example, given the instruction
nonmaskable Interrupt input. NMI. sequence

134 CHAPTER SIX


MP BX.CX word, write the instruction as CMPSW. The REPE
JAE TARGET CMPSW instruction will cause the pointers In SI
and Dl to be incremented by 2 after each compare
you can mentally read it as "jump to target If BX if the direction flag is cleared or decremented by 2
Is above or equal to CX. In other words. just if the direction flag is set.
mentally Insert the first operand after the J for
jump and the second operand after the condition.
CWD—Convert Signed Word
to Signed Doubleword
CMPS/CMPSB/CMPSW—Compare CWD copies the sign bit of a word in AX to afl the bits
String Bytes or String Words of the DX register. In other words, it extends the sign
A string is a series of the same type of data items in of AX into all of DX. The CWD operation must be done
sequential memory locations. The CMPS instruction can before a signed word in AX can be divided by another
be used to compare a byte In one string with a byte in signed word with the IDIV instruction. CWD affects no
another string or to compare a word in one string with flags.
a word in another string. SI is used to hold the offset of
a byte or word in the source string, and Dl is used to EXAMPLE:
hold the offset of a byte or a word in the other string.
The comparison is done by subtracting the byte or word DX = 00000000 00000000
pointed to by Dl from the byte or word pointed to by SI. ;AX = 11110000 11000111 = - 3897 decImal
The AF. CF. OF. PF. SF. and ZF flags are affected by the CWD Convert signed word In AX to signed
comparison, but neither operand is affected. After the doubieword in DX:AX
comparison. SI and Dl will automatically be Incremented ;Result:DX 11111111 11111111
or decremented to point to the next elements In the two ;AX = 11110000 11000111 = 3897 decimal
strings. If the direction flag has previously been set to
a I with an STD Instruction, then SI and Dl will For a further example of the use of CWD. see the IDIV
automatically be decremented by I for a byte string or instruction description.
by 2 for a word string. If the direction flag has previously
been reset to a 0 with a CLD Instruction, then SI and
Dl will automatically be incremented after the compare. DAA—Decimal Adjust AL after BCD Addition
They will be incremented by 1 for byte strings and by 2
for word strings. This instruction is used to make sure the result of
The string pointed to by DI must be in the extra adding two packed BCD numbers is adjusted to be a
segment. The string pointed to by SI must be in the legal BCD number. The result of the addition must be
data segment. in AL for DAA to work correctly. If the lower nibble in
The CMPS instruction can be used with a REPE or AL after an addition Is greater than 9 or AF was set by
REPNE prefix to compare all the elements of a string. the addition, then the DAA instruction will add 6 to the
For further discussion of strings, see the discussion at lower nibble in AL. If the result in the upper nibble of
the start of Chapter 5. AL is now greater than 9 or if the carry flag was Set by
the addition or correction, then the DAA instruction will
EXAMPLE: add 601-I to AL. A couple of simple examples should
clarify how this works.
MOV SI.OFFSET FIRST_STRING
Point SI at source string EXAMPLES:
MOV DLOFFSET SECOND_STRING AL = 0101 1001 = 59 BCD
Point DI at destination string BL = 0011 0101 35 BCD
CLI) :DFcleared,soSIandDlwIll ADD AL.BL AL 1000 1110 = 8EH
autoincrement after compare DAA ;Add0110becauselllO>9
MOV CX, 100 Put number of string elements AL 1001 0100 94 BCD
in CX
REPE CMPSB Repeat the comparison of AL = 1000 1000 = 88 BCD
string bytes BL = 0100 1001 = 49 BCD
until end of string or until ADDAL.BL :AL 1101 0001.AF
compared bytes are not equal DAA :Add0ll0becauseAF 1
AL = 1101 0111 = 1)71-i
NOTE: CX functions as a counter which the REPE :1101 >9soadd01100000
prefix will cause to be decremented after each ;AL = O011011l =37BCD,CF
compare. The B attached to CMPS tells the assem-
bler that the strings are of type b yte. If you want The DAA instruction updates AF. CF. PF. and ZF. OF is
to tell the assembler that the strings are of type undefined after a DAA instruction.

5086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 135


A decimal up counter can be implemented using the location peclfied by any one of the 24 addressing mnde
DAA instruction as follows: shown in Figure 3-8..AF. OF, PF. SF. and ZF are updated,
but CF Is not affected. This means that If an 8-bit
MOV COUNT,00H Initialize count in memory destination containing OOH or a 16-bit destination
location to 0 containing 0000H is decremented. the result will be FF11
Other instructions here or FFFFH with no carry (borrowl.
MOV AL. COUNT Bring count Into AL to work on
ADD AL.OiH Can alSo Count up by 2. by 3. or
by some other number using the EXAMPLES
ADD instruction
DAA : Decimal adjust the result DEC CL Subtract I from Contents of CL register
MOV COUNT.AL Put decimal result back
in memory DEC BP : Subtract 1 from contents of BP register

DEC BYTE PTR IBXI: Subtract I from byte at offset IBX(


DAS—Decimal Adjust after BCD Subtraction in DS. The BYTE PTR directive Is necessary to tell the
This instruction is used after subtracting two packed assembler to put in the correct code for decrementing a
BCD numbers to make sure the result is correct packed byte in memory, rather than decrementing a word. The
BCD. The result of the subtraction must be in AL for instruction essentially says, "Decrement the byte in
DAS to work correctly. If the lower nibble In AL after a memory pointed to by the offset in BX."
subtraction Is greater than 9 or the AF was set by the
subtraction, then the DAS Instruction will subtract 6 DEC WORD PTR [BPJ Subtract 1 from a word at offset
from the lower nibble of AL. If the result in the upper (BPJ in SS. The WORD PTR directive tells the assembler
nibble Is now greater than 9 or lithe carry flag was set. to put in the code for decrementing a word pointed to
the DAS Instruction will subtract 60 from AL. A couple by the Contents of BP. An offset in BP will be added to
of Simple examples should clarify how this works. the SS register contents to produce the physical address.

DEC TOMATO_CAN_COUNT Subtract I from byte or


EXAMPLES: word named TOMATO_CAN_COUPfl' in DS. if TOMA-
TO_CAN_COUNT was declared with a DR. then the
AL = 10000110 = 86BCD assembler will code this instruction to decrement a byte.
BH = 0101 0111 = 57 BCD If TOMATO_CAN_COUNT was declared with a DW, then
the assembler will code this instruction to decrement a
SUBAL,Bl-1 ;AL = 00101111 = 2FH,CF = 0 word.
DAS Lower nibble of result is 1111.
so DAS automatically subtracts
:0000 01 10 to giveAL = 00101001
= 29 BCD DIV—Unsigned Divide—DIV Source
This instruction is used to divide an unsigned word by
AL = 0100 1001 = 49 BCD a byte or to divide an unsigned doubleword (32 bits) by
RH = 0111 0010 72 BCD a word.
SUB AL.BH AL = 1101 0111 D7H. CF 1 When a word is divided by a byte, the word must be
DAS Subtracts 01100000 I — 601-1) in the AX register. 'l'he divisor can be in a register or a
because 1101 in upper nibble> 9 memory location. After the division, AL will contain an
:AL=011l0Ill=77BCD.CF,-1 8-bit result (quotient), and All will contain an 8-bit
CF I means borrow was needed remainder, If an attempt is made to divide by 0 or if the
quotient is 100 large to lit in Al. (greater than FF1-I). the
The DAS instruction updates AF, CF. SF. PF. and ZF, 8086 will automatically do a typeD interrupt. Interrupts
but OF is undefined, arc explained In Chapter 8.
A decimal down Counter can be Implemented using When a doubleword is divided by a word, the most
the DAS Instruction as follows: significant word of the doubleword must he in DX. and
the least significant word of the cioiiblcword must be in
MOV AL.COUNT Bring Count Into AL to work on AX. After the division. AX will contain the 16-bit result
SUB AL.OII-1 Decrement, Can also count down (quotient), and DX will contain a 16-bit remainder.
by 2. 3. etc.. using SUB instruction Again, If an attempt is made to divide by 0 or it the
DAS : Keep results in BCD format quotient is too large to fit in AX (greater than FFFFH).
MOV COUNT,A1 Put new count back in memory the 8086 will do a t ype 0 interrupt.
For a DIV. the dividend (numerator) must always be
DEC—Decrement Destination 'Register in AX or DX and AX. but the source of the divisor
or Memory -_DEC Destination (denominator) can be a register or a menlory location
specified by any one of the 24 addressing modes shown
This instruction subtracts 1 from the destination word in Figure 3-8. If the divisor does not divide an integral
or byte The destination can be a regitter or a memory number of times into the dividend, the quotient is

136 CHAPTER SiX


truncated, not rounded. The example below will Illus- H IT—Halt Processing
trate this. All flags are undefined after a DIV In-
struction. The HLT instruction will cause the 808610 stop fetching
If you want to divide a byte by a byte, you must first and executing instructions. The 8086 wIll enter a halt
put the dividend byte in AL and fill AM with all 0's. The state. The only ways to get the processor out of the halt
SUB AH,AJ-1 instruction is a quick way to do this. State are with an interrupt signal on the INTR pin, an
Likewise. if you want to divide a word by a word, put interrupt signal on the NMI pin, or a reset signal on the
the dividend word in AX and fill DX with all 0's. The RESET input. See Chapter 7 for further details about
SUB DX.DX Instruction does this quickly. the halt State.

IDIV—Divide by Signed Byte


EXAMPLES (SYNTAX): or Word—IDIV Source
DIV BL Divide word In AX by byte in BL. This instruction is used to divide a signed word by a
Quotient in AL, remainder in AM signed byte, or to divide a signed doubleword (32 bits)
by a signed word.
DIV CX Divide doubleword in DX and AX by When dividing a signed word by a signed byte, the
word in CX. Quotient in AX, word must be in the AX register. The divisor can be in
remainder in DX. an 8-bit register or a memory location. After the division.
AL will contain the signed result (quotient), and AM will
DIV SCALEIBXI AXJ(byte at effective address contain the signed remainder. The sign of the remainder
SCALE[BX() if SCALEIBX( is of type will be the same as the sign of the dividend. If an attempt
byte or (DX and AX(/(word at effective is made to divide by 0. the quotient is greater than 127
address SCALE (BXI) if SCALE(BX! (7FH), or the quotient is less than - 127(8 1H). the 8086
is of type word will automatically do a type 0 interrupt. Interrupts are
discussed in Chapter 8. For the 80186. 80286, etc., tbis
range is —128 to + 127.
EXAMPLE (NUMERICAL): When dividing a signed doubleword by a signed word,
the most significant word of the dividend (numerator)
AX = 37D7H = 14,295 decimal must be in the DX register, and the least significant
BH = 97H = 151 decimal word of the dividend must be in the AX register. The
DIV BH : AX/MM. AL = quotient = 5EH = 94 decimal divisor can be in any other 16-bit register or memory
AM remainder = 65H = 101 decimal location, After the division. AX will contain a signed
16-bit quotient, and DX will contain a signed 16-bit
remainder. The sign of the remainder will be the same
Since the remainder is greater than half of the divisor.
as the sign of the dividend. Again, if an attempt is made
the actual quotient is closer to 5FH than to the 5EH
to divide by 0. the quotient is greater than + 32.767
produced. However, as indicated before, the quotient is
(7FFFH), or the quotient Is less than —32.767 (8001H).
always truncated to the next lower integer rather than
the 8086 will automatically do a type 0 interrupt. For the
rounded to the closest integer. If you want to round the
80186, 80286. etc., this range is —32.768 to + 32,767.
quotient, you can compare the remainder with (dlvisor/
If the divisor does not divide evenly Into the dividend,
21 and add I to the quotient if the remainder is greater
the quotient will be truncated, not rounded. An example
than (divisor/2).
below illustrates this. All flags are undefined after an
IDly.
If you want to divide a signed byte by a signed byte.
[SC—Escape you must first put the dividend byte in AL and fill AH
with copies of the sign bit from AL. In other words, if
This instruction is used to pass instructions to
AL Is positive (sign bit 0). then AM should be filled
coprocessor, such as the 8087 math coprocessor which with 0's. lfAL is negative (sign bit = Ii. then All should
shares the address and data bus with an 8086. Instruc- be filled with l's. The 8086 Convert Byte to Word
tions for the coprocessor are represented by a 6-bit code
Instruction. CBW, does this by copying the sign bit of
embedded in the escape instruction. As the 8086 fetches
AL to all the bits of AM. AM is then said to contain the
instruction bytes. the coprocessor also catches these
"sign extension of AL." Likewise. If you want to divide
bytes Irom the data bus and puts them in its queue.
a signed word by a signed word, you must put the
However, the coprocessor treats all the normal 8086
dividend word in AX and extend the sign of AX to all the
instructions as NOPs. When the 8086 [etches an ESC
bits of DX. The 8086 Convert Word to Doubleword
instruction, the coprocessor decodes the instruction
Instruction. CWD. will copy the sign bit of AX to all the
and carries out the action specified by the 6-bit code bits of DX.
specified in the instruction, In most cases the 8086
treats the ESC instruction as a NOP. In some cases
EXAMPLES CODIN(
the 8086 will access a data item in memory for the
coprocessor. A section in Chapter Il describes the IDly BL Signed word in AXsigned byte
operation and use of the ESC instruction.
in ML

808(, INSTRUCTION D[SCRJPTlON AND ASSEMBlER DIRECTIVES 137


(DIV BP Signed doublcword In DX and of a 16 bit result or the upper word of a 32-bit iesult
AXlsigried word contains only copies of the sign bit (all 0's or all l's),
in BP then CF and the OF will both be 0. lIthe upper byte of
a 16-bit result or the upper word of a 32-bit result
IDIV BYTE FIR IBXI AX/byte at offset IBX) in DS Contains part of the product. CF and OF will both be 1.
You can use the status of these flags to determine
MOV AL.D1VIDENTJ Position byte dividend whether the upper byte or word of the product needs to
CBW Extend sign of AL into AH be kept. AF, PF, SF, and ZF are undefined after IMUL.
(DIV DIVISOR Divide by byte divisor If you want to multiply a signed byte by a signed word.
you must first move the byte into a word location and
fill the upper byte of the word with copies of the sign
EXAMPLES (NUMERICAL):
bit. If you move the byte Into AL, you can use the 8086
Convert Byte to Word Instruction. CBW. to do this. CBW
A signed word divided by a signed byte
extends the sign bit from AL into all the bits oIAH. Once
:AX = 00000011 10101011 = O3ABH
you have converted the byte to a word, you can do word
39 decimal
times word IMUL. The result of this multiplication will
:BL 11010011 = D3H = - 2DH be in DX and AX.
= - 45 decimal
IDIV BL : Quotient: AL = ECH = - 14Ff - 20
decimal EXAMPLES (CODING):
Remainder: AH = 27(1 = + 39 decimal
IMUL BH Signed byte in AL times signed byte in BH.
NOTE: The quotient is negative because positive result in AX
was divided by negative. The remainder has same
sign as dividend (positive). IMUL AX AX times AX, result in DX
and AX
A signed byte divided by a signed byte
;AL = 11011010 = - 26(1 = 38decimal Multiplying a signed byte
CH = 00000011 = + 3H = + 3 decimal by a signed word
CBW Extend sign of AL through Al-I, MOV CX.MULTIPLIER Load signed word in CX
AX 11111111 1101 1010 MOV AL,MULTIPLICAND : Load signed byte in AL
IDly CH Divide AX by CH CBW Extend sign of AL into Al-I
AL = 11110100 = - OCH = - l2decimal IMUL CX Result in DX and AX
AH = 11111110 = - 2H = - 2declmal
EXAMPLES (NUMERICAL):
Although the quotient is actually closer to 13
(12.666667) than to 12. the 8086 truncates it to 12
69 x 4
rather than rounding It to 13. If you want to round
AL = 01000101 = 69 decimal
the quotient, you can compare the magnitude of the
BL 00001110 14 decimal
remainder with (divisorf2( and add I to the quotient if
IMUL BL AX = 03C6H = + 966 decimal
the remainder is greater than (divisor/2). Note that the
MSB 0. positive result magnitude
sign of the remainder is the same as the sign of the
In true form. SF 0. CF.OF =
dividend (negative). All flags are undefined after (DIV.
–28 >< 59
AL = 11100100 = - 28 decimal
IMUL—Multiply Signed Numbers—IMUL Source BL = 00111011 = + 59 decimal
This instruction multiplies a signed byte from some IMUL 13L AX = F98CH - 1652 decimal
source times a signed byte in AL or a signed word from MSB 1. negative result magnitude
some source times a signed word in AX. The source can in 2's complement. SF.CF .OF = 1
be another register or a memory location specified by
any one of the 24 addressing modes shown in Figure
IMUL-801 86/80188 Only—Integer (Signed)
3-8. When a byte from some source is multiplied by AL,
Multiply Immediate—IMUL Destination
the signed result (product) will be put in AX. A 16-bit
Register,Source,Immediate Byte or Word
destination is required because the result of multiplying
two 8-bit numbers can be as large as 16 bits. When a This version of the IMUL Instruction functions in the
word from some source is multiplied by AX. the result same way as the IMUL instruction described In the
can be as iarge as 32 bIts. The high-order (most signifi- preceding section, except that this version allows u to
cant) word of the signed result Is put In DX, and the multiply an immediate byte or word by a b yte or word
low-order ((east significant) word of the signed result is in a specified register and put the result in a specified
put In AX. If the magnitude of the product does not general-purpose register. If the immediate number is a
require all the bits of the destination, the unused bits byte, It will be automatically sign-extended to 16 bits.
will be filled with copies of the sign bit. If the upper byte The source of the other operand for the multiplicatIon

138 CHAPTER SIX


an be a register or a memory location specified by any shown in Figure 3-8. A?. OF. PLSF. and ZF are affected
'tie of the 24 addressIng modes showi in Figure 3-8. (updated) by this instruction. Note that the carry flag
lnce the result Is put in a 16-bit general-purpose (CF) is not affected. This means that If an 8-bit destina-
egister. only the lower 16 bIts of the product are saved! lion osntalning FTh or a 16-bit destination contaIning
FFFE is incremented, the result will be all 0's with no
EXAMPLE: cany.

MUL CX,BX,07H Multiply contents of BX by 07H EX4vtPLES:


CX lower 16 bits of result
INC BL Add 1 to contents of BL register
INC CX Add I to contents of CX register
IN—Copy Data from a Port—IN
kccumulator,Port INC BYTE PTR IBXI : Increment byte in data segment at
Fhe IN Instruction will copy data from a port to the AL offset contained in BX. The BYTE PTR directive is
or AX register. If an 8-bit port Is read, the data will go necessary to tell the assembler to put in the right code
to AL. If a 16-bit port is read, the data will go to AX. The to Indicate that a byte in memory, rather than a word,
IN Instruction has two possible formats, fixed port and Is to be incremented. The instruction essentially says.
variable port. "Increment the byte pointed to by the contents of BX."
For the fixed-port type, the 8-bit address of a port is
specified directly in the instruction. INC WORD PTR IBXI Increment the word at offset of
IBXI and IBX + II in the data segment. In other words,
increment the word in memory pointed to by BX.
EXAMPLES:
INC MAX_TEMPERATURE Increment byte or word
IN AL,OC8H : Input a byte from port OC8H to AL
named MAX_TEMPERATURE in data segment. Ipere-
ment byte If MAX_TEMPERATURE declared with DB.
IN AX.341-1 Input a word from port 34H to AX
Increment word If MAX_TEMPERATURE declared with
DW.
A_TO_D EQU 4AH
IN AX,A_TO_J) Input a Word from port 4A}1 to AX
INC PRICES IBXI: Increment element pointed to byIBXI
in array PRICES. Increment a word if PRICES was
For the variable-port-type IN Instruction, the port
defined as an array of words with a DW directive,
address Is loaded into the DX register before the IN
Increment a byte if PRICES was defined as an array of
Instruction. Since DX is a 16-bit register, the port
bytes with a DB directive.
address can be any number between 0000H and FFFFFI.
Therefore, up to 6E.536 ports are addressable in this
NOTE: The PTR operator is not needed in the last
mode.
two examples because the assembler knows the
type of the operand from the DB or DW used to
EXAMPLES:
declare the named data inItially.
MOV DX,OFF78H Initialize DX to point to port
IN AL.DX Input a byte from 8-bit port
OFF78H to AL
INT—Interrupt Program Execution—INT Type
The term type in the instruction format refers to a
IN AX.DX Input a word from 16-bit port number between 0 and 255 which identifies the inter-
OFF78H to AX rupt. When an 8086 executes an INT instruction, it will:

The variable-port IN instruction has the advantage that I. Decrement the stack pointer by 2 and push the flags
the port address can be computed or dynamically deter- onto the stack.
mined in the program. Suppose, for example, that an
8086-based computer needs to input data from 10 2. Decrement the stack pointer by 2 and push the
terminals, each having Its own port address. Instead of contents of CS onto the stack.
having a separate procedure to input data from each 3. Decrement the stack pointer by 2 and push the
port, we can write one generalized input procedure and offset of the next instruction after the INT number
simply pass the address of the desired port to the instruction on the stack.
procedure in DX. The IN instructions do not change any
flags. 4. Get a new value for IP from an absolute memory
address of 4 times the type specified In the instruc-
tion. For an INT 8 instruction, for example, the new
I NC—Increment—I NC Destination IP will be read from address 00020H.
The INC instruction adds 1 to a specified register or to 5. Get a new value for CS from an absolute memory
a memory location specified in any one of the 24 ways address of 4 times the type specified in the instruc-

- 20 Rtw. NcTPUCTION DFPI1IONS AND ASSEMBLER DIRECTIVES 139


tion pIus 2. For an INT 8 instruction, for example, cause it does not copy the flags from the stack
the new value of CS will he read from address back to the flag register. See Chapter 8 for further
00022H. discussion .01 Interrupts and the use of IRET.
6. Reset both IF and TF. Other flags are not affected.
JAJJNBE—Jump if Above/Jump
Chapter8 furtherdescr-thes the use of this instruction. if Not Below or Equal
EXAMPLES: These two mnemonics represent the same instruction.
The terms aboue and below are used when referring to
INT 35 New IP from 0008CH. new CS from 0008EH the magnitude of unsigned numbers. The number 0111
Is above the number 0010. If. after a compare or some
tNT 3 This is a special form which has the sine-byte other instruction which affects flags, the zero flag and
code of CCH. Many systems use this as a breakpoint the carly flag are both 0, this instruction will cause
instruction, New IP from 0000CH, new CS from 0000EH. execution to jump to a label given In the Instruction. If
CF and ZF are not both 0, the Instruction will have no
INTO—Interrupt on Overflow effect on program execution. The destination label for
the jump must be In the range of —128 bytes to + 127
if the overflow flag (OF) is set, this instruction will cause bytes from the address of the instruction after the JA.
the 8086 to do an indirect far call to a procedure you JA/JNBE affects no flags. For further explanation of
write to handle the overflow condition. Before doing the Conditional Jump instructions, see Chapter 4.
call, the 8086 wIll:
EXAMPLES:
I. Decrement the stack pointer by 2 and push the flags
onto the stack. CMP AX.4371H Compare by subtracting 4371H
2. Decrement the stack pointerby 2 and push CS Onto from AX
the stack. JA RUN_PRESS Jump to label RUN_PRESS If AX
above 4371H
3. Decrement the stack pointer by 2 and push the offset
of the next instruction after the INTO instruction CMP AX,4371H Compare (AX - 4371H)
onto the stack JNBE RUN_PRESS : Jump to label RUN_PRESS If AX
4. Reset TF and IF. Other flags are not affected. To do not below or equal to 4371H
the call, the 8086 wIll read a new value for IF from
address 000 IOH and a new value of CS from address JAE/JNB/JNC—jump if Above or Equal/Jump
0001 2H. if Not Below/jump if No Carry
Chapter 8 further describes the 8086 interrupt These three mnemonics represent the same instruction.
system. The terms above and below are used when referring to
the magnitude of unsigned numbers. The number 0111
EXAMPLE: Is above the number 0010. If, after a compare or some
other instruction which affects flags, the early flag is 0.
INTO Call interrupt procedure if OF = this instruction will cause execution to jump to a label
given in the instruction. If CF is 1. the instruction will
IRET—Interrupt Return have no effect on program execution. The destination
label for the Jump must be in the range of - 128 bytes
When the 8086 responds to an interrupt signal or to an Co + 127 bytes from the address of the instruction after
Interrupt instruction, it pushes the flags, the current the JAE. JAE/JNB/JNC affects no flags. For further
value of CS. and the current value of IF onto the stack. explanation of Conditional Jump instructions, see
It then kads CS and iP v. tt: the starting address of the Chapter 4.
procedure which you write for the response to that
interrupt. The IRET instruction is used at the end of EXAMPLES:
the Interrupt service procedure to return execution to
the Interrupted program. To do this return, the 8086 CMP AX,4371H Compare (AX - 4371H)
copies the saved value of IP from the stack to IP, the JAE RUN_PRESS Jump to label RUN_PRESS if AX
stored value of CS from the stack to CS. and the stored above or equal to 437lH
value of the flags back to the flag register. Flags will have
the values they had before the interrupt, so any flag CMPAX,4371H : Compare (AX - 437lH)
settings from the procedure will be lost unless they are JNB RUN_PRESS Jump to label RUN_PRESS if AX
specifically saved in some way. not below 4371H

NOTE: The RET struction should not normally ADD AL,BL : Add two bytes, if result within
be used to return Interrupt procedures be- JNC OK : acceptable range. continue
140 CHAPTER 5l

jB/JC/jNAE—Jump if Below/jump does not contain all 0's, execution will simply proceed
if Carry/jump if Not Above or Equal to the next instruction. Note that this instruction does
These three mnemonics represent the same instruction. not look at the zero flag when it decides whether to Jump
The terms above and below are used when referring to
or not. The destination label for this Instruction must
beintherangeol - 128to + I2lbyteefromtheaddreee
the magnitude of unsigned numbers. The number 0111 of the Instruction after the JCXZ instruction. JCXZ
is above the number 0010. II. after a compare or some affects no flags.
other instruction which affects flags, the carry flag is a
1, this instruction will cause execution to Jump to a
label given in the instruction. If CF isO. the instruction EXAMPLE:
will have no effect on program execution. The destination
label for the Jump must be in the range of -128 bytes JCXZSK11LOOP ;IfCX = 0. skIp the process
to + 127 bytes from the address of the instruction NXT:SLJB [81(1,0713 Subtract 7 from data value
after the JB. JB/JC/JNAE affects no flags. For further INC BX Point to next value
explanation of Conditional Jump instructions, see LOOP NXX' Loop until CX 0
Chapter 4. SKlP_LOO: Next instruction

EXAMPLES:
JE/JZ—Jump if Equal/Jump if Zero
CMP AX.4371H Compare (AX - 4371H)
JE RUN_PRESS Jump to label RUN_PRESS If These two mnemonics represent the same instruction.
AX below 4371H If the zero flag Is set, then this instruction will cause
execution toJwnp to a label given in the instruction. If
ADD BX,CX Add two words and jump the zero flag is not 1. then execution will simply go on
JC ERROR.YIX to label ERROR_FIX if CF = 1 to the next instruction after JE or JZ. The destination
label for the JEIJZ inMructlon must be in the range of
AX.4371H - 128to +l27bytesfromtbeaddoftheco
CMP Compare (AX - 4371H) after the JE/JZ instruction. JFIJZ affects no flag..
JNAE RUN_PRESS Jump to label RUN_PRESS if
AX not above or equal to 4371H
EXAMPLES:
JBEJJNA—Jump if Below NXT:CMJ BX.DX Compare (BX-DX)
or Equal/jump if Not Above JE DONF Jump to DONE if BX - DX
These two mnemonics represent the same instruction. SUB BX.AX Ele subtract AX
The terms above and below are used when referring to INC CX Increment counter
the magnitude of unsigned numbers. The number 0111 JMP NXT Check again
is above the number 0010. If. after a compare or some DONE:MOV AX,CX Copy count to AX
other instruction which affects flags, either the zero flag
or the carry flag is 1. this in3tructlon will cause execution IN AL,8FH Read data from port 8FH
tojump to a label given in the instruction. If CF and ZF SUB AL.30H Subtract minimum value
are both 0. the instruction will have no effect on program JZ START_MACHINE Jump to label if result of
execution. The destination label for the jump must be subtraction was 0
in the range of -128 bytes to + 127 bytes from the
address of the instruction after the JBE. JBE/JNA affects
no flags. For further explanation of Conditional Jump ! G/J NLE_Jump if Greater/Jump
instructions, see Chapter 4. i Not Less Than or Equal
EXAMPLES: These tWo mnemonics represent the same instruction.
The terms greater and less are used to refer to the
CMP AX.437lH relationship of two signed numbers. Greater means
: Compare (AX - 437lH) more positive. The number 00000111 is greater than
JBE RUN_PRESS : Jump to label RUN_PRESS If AX the number 11101010. because in signed notation the
below or equal to 437111 second number Is negative. This instruction is usually
CMP AX.43711-1 used after a Compare instruction. The instruction will
Compare (AX - 437111) cause a jump to a label given in the instruction if the
JNA RUN_PRESS Jump to label RUN_PRESS if AX
not above 43711-I zero flag is 0 and the carry flag Is the same as the
overflow flag. The destination label must be in the range
of -128 bytes to + 127 bytes from the address of the
ICXZ-..-Jump if the CX Register Is Zero instruction after the JG/JNLE instruction. If the jump
is not taken, execution simply goes on to the next
This instruction will cause a jump to a label given in instruction after the JO or JNLE instruction. JGIJNLE
the instruction if the CX register contains all 0's. If CX affects no flags.

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIvES 141


EXAMPLES: CM? BL.39H Compare by subtracting 3911 from B
JNGE AGAIN Jump to label if BL not more posiu
CMP BL,39H : Compare by subtracting 3911 from BL than 3911 or BE. not equal to 3911
JO NEXT_I Jump to label If BE. more positive
than 39H
CM? BL,39H : Compare by subtracting JLE/JNG—Jump if Les s Than
3911 from BL or Equal/Jump if Not Greater
JNLE NEXT_I Jump to label if BL not less than
or equal to 39H These two mnemonics represent the same Instruction
The terms greater and less are used to refer to th
relationship of two signed numbers. Greater mean:
JGE/JNL—Jump if Greater Than more positive. The number 00000111 is greater thai
or Equal/Jump if Not Less Than the number 11101010, because in signed notation th
second number is negative. This Instruction is usuail
These two mnemonics represent the same instruction. used after a Compare instruction. The instruction wil
The terms greater and less are used to refer to the cause a jump to a label given in the instruction If th
relationship of two signed numbers. Greater means zero flag is set, or if the sign flag is not equal to the
more positive. The number 0000011! Is greater than overflow flag. The destination label must be In the range
the number 11101010, because in signed notation the of - 128 bytes to + 127 bytes from the address of th
second number is negative. This Instruction is usually instruction after the JLE/JNG instruction, If the Jumi
used after a Compare instruction. The Instruction will Is not taken, execution simply goes on to the nex
cause a jump to a label given in the Instruction If the instruction after the JLEIJNG instruction. JLE/JNG
sign flag is equal to the overflow flag. The destination affects no flags.
label must be in the range of - 128 bytes to + 127 bytes
from the address of the instruction after the JGE/JNL EXAMPLES:
Instruction. If the jump is not taken, execution Simply
goes on to the next instruction after the JGE or JNL
CMP BL,39H Compare by subtracting 39H from BL
instruction. JGEIJNL affects no flags.
JLE NXT_1 Jump to label if BL more negative
than 39H or equal to 3911
EXAMPLES:
CMP BL,39H Compare by subtracting 3911 from BL
CM? BL.39H : Compare by subtracting 39H from BL JNG PRIN'FER : Jump to label if BE. not more
JGE NEXT_i Jump to label if BL more positive positive than 3911
than 3911. or equal to 39H

CMP BL,39H : Compare by subtracting 3911 from 13L JMP—Unconditional jump


JNL NEXT_I Jump to label if BE. not less than 3911 to Specified Destination
This instruction will always cause the 8086 to fetch
JL/JNGE—Jump if Less Than/Jump its next Instruction from the location specified in the
if Not Greater Than or Equal instruction rather than from the next location after the
JMP instruction. If the destination is in the same
'Fhese two mnemonics represent the same instruction. code segment as the JMP instruction, then only the
The terms greater and less are used to refer to the instruction pointer will be changed to get to the destina-
relationship of two signed numbers. Greater means tion location. This is referred to as a near Jump. If the
more positive. The number 00000111 is greater than destination for thejump instruction is in a segment with
the number 11101010, because in signednotation the a name different from that of the segment containing the
second number is negative. This instruction is usually JMP instruction, then both the instruction pointer and
used after a Compare instruction. The instruction will the code segment register contents will be changed to
cause a jump to a label given in the Instruction lithe get to the destination location. This is referred to as a
sign flag is not equal to the overflow flag. The destination far Jump. The JMP instruction affects no flags. Refer to
label must be in the range of - 128 bytes to + 127 bytes Chapter 4 for a detailed discussion of the different forms
from the address of the instruction after the JLJJNGE of the unconditional JMP instruction.
Instruction. if the jump is not taken, execution simply
goes on to the next instruction after the JL or JNGE
EXAMPLES:
instrucuon. JL/JNGE affects no flags.
JMP CONTINUE Fetch next instruction from address
EXAMPLES: at label CONTINUE. lithe label is in the same segment.
an offset coded as part of the instruction will be added
CMP BL,39H Compare by subtracting 3911 from BL to the instruction pointer to produce the new fetch
JL AGAIN Jump to label if BL more negative address, if the label is in another segment. then lP and
than 39H CS will be replaced with values coded in as part of the

142 CHAPTER SIX


instruction. This type of jump is referred to as direct register or memory location. The JNO instruction will
because the displacement of the destination or the cause the 8086 to jump to a destination given in the
destination itself is specified directly in the instruction. Instruction If the overflow flag is not set. The destination
must be In the range of - 128 bytes to + 127 bytes from
JMP BX Replace the contents oT IP with the contents the address of the instruction after the JNO instruction.
of BX. BX must first be loaded with the offset of the If the overflow flag is set, execution will simply continue
destination instruction In CS. This is a near jump. It is with the next instruction after JNO. JNO affects no
also referred to as an indirect jump because the new flags.
value for IP comes from a register rather than from the
Instruction itself, as in a direct jump.
EXAMPLE:
JMP WORD PTR IBXI Replace II' with a word from a
ADD AL,BL Add signed bytes in AL and BL
memory location pointed to by BX in DS. This is an
JNO DONE Process done if no overflow
indirect near jump.
MOV AL.00H Else load error code in AL
DONE: OUT 24H.AL Send result to display
JMP DWORD PTR IS!] Replace IP with a word pointed
to by SI in DS. Replace CS with a word pointed to by SI
+ 2 In DS. This Is an Indirect far jump. JNP/JPO—jump if No Parity/Jump if Parity Odd
If the number of l's left in the lower 8 bits of a data
JNA—See Heading JBE word after an instruction which affects the parity flag
Is odd, then the parity flag will be 0. The JNP/JPO
JNAE—See Heading JB instruction will cause execution to jump to a specified
JNB—See Heading JA[ destination address if the parity flag isO. The destination
address must be in the range of - 128 bytes to + 127
JNBE—See Heading JA bytes from the addres of the instruction after the JNP/
JPO instruction. If the parity flag Is set, execution will
INC—See Heading JAE
simply Continue Ofl to the instruction after the JNP/JPO
JNE/JNZ—Jump if Not Equal/Jump if Not Zero instruction. The JNP/JPO instruction affects no flags.
These two mnemonics represent the same instruction.
If the zero flag is 0, then this instruction will cause EXAMPLE:
execution to jump to a label given in the instruction. If
the zero flag is 1. then execution will simply go on to IN AL,OF8H Read ASCII character from UART
the next insu-uction after JNE or JNZ. The destination OR AL.AL Set flags
label for the JNE/JNZ instruction must be in the range of JPOERROR1 : Even parity expected, send error
- 128 to + 127 bytes from the address of the instruction message if parity found odd
after the JNE/JNZ Instruction. JNE/JNZ affects no flags.

EXAMPLES: JNS—Jump if Not Signed (Jump if Positive)


This instruction will cause execution to jump to a
NXT: IN AL.OF8H Read data value from port specified destination lithe sign flag is 0. Since a 0 in
CMP AL.72 : Compare (AL-72) the sign flag indicates a positive signed number, you
JNE NXT Jump to NXT ifAL 5 72 can think of this Instruction as saying 'Jump if positive."
IN AL.OF9H : Read next port when if the sign flag is set, Indicating a negative signed result.
AL = 72 execution will simply go on to the next instruction after
MOVBX.2734H Load BX as counter JNS. The destination for the jump must be In the range
NXT_ I ADD AX.0002H Add count factor to AX of - 128 bytes to + 127 bytes from the address of the
DEC 8X Decrement BX instruction after the JNS. JNS affects no flags.
JNZ NXT_l: Repeat until BX = 0
EXAMPLE:

JNG—See Heading JLE DEC AL : Decrement counter


JNS REDO : Jump to label REDO if counter has not
JNGE—See Heading JL
decremented to FFH
JNL—See Heading JGE
JNLE—See Heading JG JNZ—See Heading JNE
INO—Jump if No Overflow 10— Jump if Overflow
The overflow flag will be set lithe result of some signed The JO instruction will cause the 8086 to Jump to a
arithmetic operation s too large to fit ii: the destination destination given in the instruciton if the overflow flag

8086 INSTRUCTION DESCRIPTIONS AND ACSEMBLER DIRECTIVES 143


Ii sat. The overflow flag will be set if the magnitude of JZ—See Heading JE
the result produced by some signed arithmetic operation
is too large to fit in the destination register or memory LAHF—.Copy Low Byte of Flag Register to AH
location. The destination for the JO instruction must
be In the range of - 128 bytes to + 127 bytes from the The lower byte of the 8086 flag register is the same as
address of the instruction after the JO instruction. If the flag byte (or the 8085. LAHF copies these 8085
the overflow flag is not set, execution will simply continue equivalent flags to the AH register. They can then be
with the next instruction after JO. JO affects no flags. pushed onto the stack along with AL by a PUSH AX
instruction, An LAHF instruction followed by a PUSH
AX instruction has the same effect as the 8085 PUSH
EXAMPLE: P5W instruction. The LAHF instruction was included in
the 8086 instruction set so that the 8085 PUSH PSW
ADD AL,BL Add signed bytes In AL and BL instruction could easily be simulated on an 8086, LAHF
JO ERROR Jump to label ERROR if overflow changes no flags.
from add
MOV SUM.AL Else put result in memory location LDS—Load Register and OS with Words
named SUM from Memory—LDS Register, Memory
Address of First Word
JP/JPE—Jump if Parity/Jump if Parity Even This instruction copies a word from two memory loca-
tions into the register specified in the instruction. It
If the number of l's left in the lower 8 bits of a data
then copies a word from the next two memory locations
word after an Instruction which affects the parity flag
into the OS register. LDS is useful for pointing SI and
is even, then the parity flag will be Set. If the parity flag
DS at the start of a string before using one of the string
is set, the JP/JPE Instruction will cause execution to instructions. LDS affects no flags.
Jump to a specified destination address. if the parity flag
isO, execution will simply continue on to the instruction
EXAMPLES;
after the JP/JPE Instruction. The destination address
must be In the range of —128 bytes to + 127 bytes
from the address of the instuction after the JP/JPE LOS BX. 143261 Copy contents of memory at displace-
Instruction. The JP/JPE instruction affects no flags. ment 4326H in OS to BL, contents of 4327H to BH.
Copy contents at displacement of 428H and 4329H in
DS to OS register.
EXAMPLE:
LDS SI.STRING_POINTER : Copy contents of rne ioiy
IN AL.F8H : Read ASCfl character from UART at displacements STRING_POINTER arid STRTh
ORAL.AL ;Set flags POINTER + I in DS to Si register. Copy contc ,nts
JPE ERROR2 : Odd parity expected, send error of memory at displacements STRING_POINTER
message if parity found even 2 and STRING POINTER + 3 in OS to DS regis icr,
DS:SI now points at start of desired string.

JPE—See Heading JP
LEA—Load Effective Address—LEA
JPO—See Heading JNP Register,Source
JS.—Jump if Signed (Jump if Negative) This instruction determines the offset of the variable or
memory location named as the source and puts this
This instruction will cause execution to Jump to a offset in the indicated 16-bit register. LEA changes no
specified destination If the sign flag is set. Since a I In flags.
the sign flag indicates a negative signed number, you
can think of this instruction as saying "jump if negative'
or "Jump if minus." If the sign flag is 0, indicating a EXAMPLES:
positive signed result, execution will simply go on to the
next instruction after JS. The destination for the Jump LEA BX,PRICES : Load BX with offset of
must be in the range of —128 bytes to + 127 bytes from PRICES in OS
the address of the instruction after the JS. JS affects
ho flags. LEA BP,SS:STACK_TOP : Load BP with offset of
STACIL.TOP in SS
EXAMPLE LEA CX.IBXIDfl Load CX with EA =
(BX) + (DI)
ADD BL.DH Add signed byte in PH to Signed
byte iii 81,. A program example will better show the context in which
JS TOO_.COLD Jump to label TOO_COLD if result this instruction is used. If you look at the program in
of addition is negative number Figure 4-2 Ic, you will see that PRICES is an array of

144 CHAPTER SIX


bytes in a segment caned ARRAYS. The instruction LEA LODS/LODSB/LODSW—Load String Byte
BX, PRICES will load the displacement of the first into AL or Load String Word into AX
element of PRICES directly Into BX. The instruction
MOVAL. IBXI can then be used to bring an element from This instruction copies a byte from a string location
the array into AL. Alter one element in the array is pointed to by SI to AL. or a word from a string location
processed. BX is Incremented to point to the next pointed to by SI to AX. if the direction flag is cleared (0).
element in the array. Si will automatically be incremented to point to the next
element of the string. For a string of bytes. SI will be
incremented by 1. For a string of words. SI will be
LES—Load Register and ES with Words incremented by 2. If the direction flag (OF) is set (ii. SI
from Memory—LES Register, Memory will be automatically decremented to point to the next
Address of First Word string element. For a byte string. SI will be decremented
by 1, and for a word string, Si will be decremented by
This instruction loads new values into the specified 2. LODS affects no flags.
register and Into the ES register from four successive
memory locations. The word from the first two memory
locations is copied into the specified register, and the EXAMPLE:
word from the next two memory locations is copied into
CLD Clear direction flag so SI
the ES register. LES can be used to point DI and ES at
the start of a string before a string instruction is is autoincremented
executed. LES affects no flags.
MOV SI, OFFSET SOURCE_STRiNG
Point SI at start
EXAMPLES: of string
LODS SOURCE_STRING Copy byte or word from
LES BX,1789AH1 Contents of memory at displacements string to AL or AX
789AH and 789BH in DS copied to BX. Contents of
memory at displacements 789CH and 789DH In DS NOTE: The assembler uses the name of the string
copied to ES register. to determine whether the string is of type byte or
type word. Instead of using the string name to do
LES DI.IBX) Copy Contents of memory. at offset IBXI this, you can use the mnemonic LODSB to tell the
and offset [BX + 1) in DS to DI register. Copy Contents assembler that the 4ring is of type byte or the
of memory at offsets (BX + 21 and IBX + 31 to ES mnemonic LODSW to tell the assembler that
register. the string is of type word.

LOCK—Assert Bus Lock Signal LOOP—Jump to Specified Label if CX 0


Many microcomputer systems contain several micropro- after Autodecrement—LOOP Label
cessors. Each microprocessor has its own local buses This instruction is used to repeat a series of instructions
and memory. The individual microprocessors are Con- some number of times. Th. number of times the instruc-
nected together by a system bus so that each can access tion sequence is to be repeated is loaded into CX. Each
system resources such as disk drives or memory. Each time the LOOP instruction executes. CX is automatically
microprocessor takes control of the system bus only decremented by I. If C?( is not 0. execution will jump to
when it needs to access some system resource. The a destination specified by a label in the instruction. If
LOCK prefix allows a microprocessor to make sure that CX = 0 after the autodeerement, execution will simply
another processor does not take control of the system go on to the next instruction after LOOP. The destination
bus while It is in the middle of a critical instruction address for the jump must be in the range of - 128
which uses the system bus. The LOCK prefix is put in bytes to + 127 bytes from the address of the instruction
front of the critical instruction. When an instruction after the LOOP instruction. LOOP affects no flags. See
with a LOCK prefix executes, the 8086 will assert its Chapter 4 for further discussion and examples of the
bus lock signal output. This signal is connected to an LOOP instruction.
external bus controller device, which then prevents soy
other processor from taking over the system bus. LOCK
affects no flags. See Chapter II for further discussion EXAMPLE:
of this.
MOV BX. OFFSET PRICES
Point BX at
EXAMPLE first element 4narray
MOV CX.40 Load CX with number of
LOCK XCHG SEMAPJ-{ORE.AL The XCHG instruction elements in array
requires two bus accesses. The LOCK prefix prevents NEXT: MOV AL.IBXI Get element from array
another processor from taking control of the system bus ADD AL.07H Add correction factor
between the two accesses. DAA Decimal adjust result

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 145


MOV IBXI.AL Put result back In array and ZF = 1. The destination address for the jump must
INCBX be in the range of —128 bytes to + 127 bytes from the
LOOP NEXT Repeat until all elements address of the instruction after the LOOPNE/LOOPNZ
adjusted instruction. LOOPNE/LOOPNZ affects no flags. See
Chapter 4 for further discussion and examples of the
LOOPNE/LOOPNZ Instruction.
LOOPEJLOOPZ—Loop While
CX * 0 and ZF = 1
EXAMPLE:
LOOPE and LOOPZ are two mnemonics for the same
Instruction. This instruction is used to repeat a group MOV BX,OFFSET ARRAY Point BX to Just
of instructions some number of times or until the zero DEC BX before start of array
flag becomes 0. The number of times the instruction MOV CX, 100 Put number of array
sequence is to be repeated is loaded into CX. Each time elements in CX
the LOOP instruction executes. CX is automatically NEXT: INC BX Point to next
decr.mented by 1. If CX ^ 0 and ZF = 1. execution element in array
will Jump to a destination specified by a label in the CMP IBXI.ODH Compare array
instruction. If CX = 0 after the autodecrement or if element with ODH
ZF = 0. execution will simply go on to the next instruc- LOOPNE NEXT
tion after LOOPE/LOOPZ. In other words, the two ways
to exit the loop are CX = 0 or ZF = 0. The destination NOTE: When the LOOPNE instruction executes.
address for the jump must be in the range of - 128 CX will be decremented by I. If CX 0 0 and ZF =
bytes to + 127 bytes from the address of the instruction 0. execution will go to the label NEXT. If CX = 0
after the LOOPE/LOOPZ instruction. LOOPE/LOOPZ or ZF = I. execution will go on to the next
affects no flags. See Chapter 4 for further discussion instruction after LOOPNE. If CX 0 and ZF = 0
and examples of the LOOPE/LOOPZ instruction. on exit. 0011 was not found in the array. If CX 0
0 on exit from the loop, then BX points to the first
element which Contains ODH. If CX = 0 and ZF =
EXAMPLE:
1 on exit from the loop, the last array element was
ODH.
MOV BX,OFFSET ARRAY Point BX to Just
DEC BX before start of array
MOVCX,l0O Put number of array LOOPNZ—See Heading LOOPNE
elements in CX
LOOPZ—See Heading LOOPE
NEXT: INC BX Point to next
element in array MOV—Copy a Word or Bvte—MOV
CMP (BXI,OFFH Compare array Destination,Source
element with FFH
LOOPE NEXT The MOV Instruction copies a word or byte of data
from a specified source to a specified destination. The
NOTE: The next element Is thecked if the element destination can be a register or a memory location. The
equals FEE! and the element was not the last one source can be a register, a memory location, or an
In the array. If CX 0 and ZF I on exit, all immediate number. The source and destination in an
elements were equal to FFH. If CX 0 0 on exit from instruction cannot both be memoiy locations. The
the loop, then 13X points to the first element that source and destination in a MOV instruction must both
was not FFH. If CX = 0 and ZF = 0 on exit, then be of type byte. or they must both be of type word. MOV
/ the last element was not FFH. instructions do not affect any flags.

LOOPNEILOOPNZ—Loop While EXAMPLES:


CX * 0 and ZF = 0
MOV CX.037AH Put the Immediate number
LOOPNE and LOOPNZ are two mnemonics for the same 037A11 in CX
instruction. This instruction is used to repeat a group
of instructions some nurdber of times or until the zero MOV BL.1437AHj Copy byte In DS at offset
flag becomes a 1. The number of times the instruction 437AH to BL
sequence is to be repeated is loaded into the count

register CX. Each time the LOOPNE/LOOPNZ instruc- MOV AX.X Copy contents of register BX to AX
tion execues. CX is automatically decremented by I. If

CX 0 0 and ZF = 0. execution will Jump to a destination MOV DL.IBXI Copy byte from memory at IBXI
specified by a label In the instruction. If CX 0 after to DL
the autodecrement or If ZF = I. execution will simply BX contains offset of byte in OS
go on to the next instruction after LOOPNE/LOOPNZ. In

other words, the two ways to exit the loop are CX = 0 MOV DS.11X Copy word from BX to DS register

146 CHAPTER SIX


MOV RESULTS(BPj,AX; Copy AX to two memory loca- After the move, SI will be 1 greater than the offset of the
tions—AL to the first location, AH to the second. EA of last byte in the source string. DI will be I greater than
the first memory location is the sum of the displacement the offset of the last byte in the destination string. CX
represented by RESULTS and contents of BP. Physical will be 0.
address = EA + SS.

MOV CS:RESULTS{BPI,AX Same as the above instruc-


MUL—Multiply Unsigned Bytes
tion, but physical address = EA + CS because of the
or Words—MUL Source
segment override prefix CS.
This Instruction multiplies an unsigned byte from some
source times an unsigned byte in the AL register or an
MOVS/MOVSB/MOVSW—Move String Byte unsigned word from some source times an unsigned
or String Word—MOVS Destination String word in the AX register. The source can be a register or
Name,Source String Name a memory location Specified by any one of the 24
This instruction copies a byte or a word from a location addressing modes shown in Figure 3-8. When a byte is
in the data segment to a location in the extra segment. multiplied by the Contents of AL. the result (product) is
The offset of the source byte or word in the data segment put in AX. A 16-bit destination Is required because the
must be in the SI register. The offset of the destination result of multipl ring an 8-bit number by an 8-bit number
in the extra segment must be contained in the Dl can be as large as 16 bits. The most significant byte of
register. For multiple-byte or multiple-word moves, the the result is put in AH. and the least sIgnificant byte of
number of elements to be moved is put in the CX register the result is put in AL. When a word is multiplied
so that it can function as a counter. After the byte or by the contents of AX. the product can be as large as 32
word Is moved, SI and DI are automatically adjusted to bits. The most signIficant word of the result is put in
point to the next source and the next destInation. If the the DX register, and the least significant word of the
direction flag Is 0, then SI and DI will be incremented result is put in the AX register. If the most sIgnificant
by 1 after a byte move and incremented by 2 after a word byte of a 16-bit result or the most significant word of a
move, If the DF is a 1, then SI and Dl will be decrernented 32-bit result is 0. CF and OF wIll both be 0's. Checking
by 1 after a byte move and decrementeu by 2 after a these flags, then, allows you to detect and perhaps
word move. MOVS affects no flags. discard unnecessary leading 0's in a result. AF, PF. SF.
When using the MOVS instruction, you must in some and ZF are undefined after a'MUL instruction.
way tell the assembler whether you wan' to rirove a strIng If you want to multiply a byte by a word, you must
as bytes or as words. There are two ways to do this. The first move the byte to a word location such as an extended
first way is to indicate the names of the source and register and fill the upper by'e of the word with all 0's.
destination strings in the instruction, as. for example.
MOVS STRING_DUMP,STR!NG_CREATE. The assem- NOTE: You cannot use the 8086 Convert Byte to
bler will code the instruction for a byte move if STRING_ Word instruction. CBW. to do this. The CBW
DUMP and STRING_CREATE were declared with a DB. instruction fills the upper byte of AX with copies
It will code the instruction for a word move if they were of the MSB of AL. If the number in AL Is 80H or
declared with a DW. Note that this reference to the greater. CEW will fill the upper half of AX with l's
source and destination strings does not load SI and Dl. instead of with U's. One you get the byte converted
This must be done with separate instructions. The corretly to a word with 0's in the upper byte, you
second way to tell the assembler whether to code the can then do a word times word multiply. The 32-
instruction for a byte or word move Is to add a "B' or a bit result will be in DX and AX.
"W" to the MOVS mnemonic. MOVSB, for example, says
move a string as bytes. MOVSW says move a string as
words. EXAMPLES:
EXAMPLE : AL times BH, result in AX
UL Bit
MOV SI.OF'FSET SOURCE_STRING MUL CX AX times CX, result high word
Load offset of start of source in DX.
string to DS into SI low word in AX
MOV DI.OFFSET DESTINATION_STRING
Load offset of start of MUL BYTE PTR (HXI : AL times byte in DS pointed
destination to by IBXI
string in ES into DI
CLD Clear directIon flag to auto-
increment SI & DI after move MUL CONVERSION_FACTORIBXI Multiply AL times
MOV CX,04H Load length of string into CX byte at effective address CONVERSION_FACTORIBXI if
as counter -- - it wts declared as type byte with DB. Multiply AX tim.'s
REP MOVSB Decrenient CX and copy word at effective address CONVERSION_FACTORJBX 'I
string bytes until CX = 0 it was declared as type word with DW.

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 47


21


Example showing a byte multiplied by a word also be used to hold a place in a program for an
instruction thst will he added later.
MOV AX.MULTIPLICAND_16 : Load 16-bit
multiplicand into AX
MOV CL,MtJLTIPLIER_8 Load 8-bit multiplier NOT—Invert Each Bit
into CL of Operand—NOT Destination
MOV CH.00H Set upper byte of CX The NOT instruction inverts each bit (forms the l's
to au 0's complement) of the byte or word at thc specified destina-
MUL C) AX times CX. 32-bit tion. The destination can be a register or a memory
result in DX and AX location specified by any one of the 24 addressing modes
shown In Figure 3-8. No flags ax-c aflécted by the NOT
NEC—Form 2's Complement—NEC Destination instruction.

This instruction replaces the number in a destination


with the 2's complement of that number. The destination EXAMPlES:
can be a register or a memory location specified by any
one of the 24 addressing modes shown in Figure 3-8. NOT BY Complement contents of
This instruction forms the 2's complement by sub- BX register
a:Ung the original word or byte in the indicated
destination from zero. You way want to try this with a NOT bYTE PTR BXI : Complement memory byte at
couple of numbers to conviric yourself that it gives the offset IBXI in data segment
same result as the tnvert each øh and add I algorIthm.
Aa shown in some of the Ioilowtng examples, the NEG
instruction is useful for ch .. ogtng the sign of a signed OR-1e"icay OR Corresponding Bits of Two
won" or byte. An attempt to NC a byte location con Operind —Oct Destination,Source
tair.ing - 128 or a word loca'oo containing —32,763
will produce no change in the destination contents This ins trucuon ORs each bit in a source byte or word
because the maximum poslilve signed number in 8 btt witn the cn eesx . nding bit in a destination byte or word.
is + 127 and the msxie,un oc . ti'' igoed nmbtr i rhe tesuit is put in the specified destination. The
l hits Is I32,767. o' be ------.iete iha the conients ot the specified source will not be changed. The
cperatko could nc s.oe. 1 -------B rev:u for each bit will follow the truth table for a two-
updatesAF,CF,t). 'c inp:it JR gate. In other words, a bit In the destination
will bn'-ome a I if that bit Is a I in the source operand
c' th:t bit is a I in the original destination operand.
EXAMPLES.
a bit In the destination operand can be set
I b' simp BRing that bit with a I in the same bit
NEC AL
.:-, r.:)t,.lU soree o perand. A bit ORed with Ois not changed.
' he "-oixrc operand can be an Immediate number.
contents of a register, or the contents of a memory
NF.G BX R.'ae-:.d i LX wub ir:
iccatuon specified by one of the 24 addressing modes
stu ..rn in Figure 3-8. The destination can be a register
or a nernory location. The source and the destination
NFG BYrE -I'rlBx .:bc'e Ly:e t ffs FP'i t.
'.'annot boi.h be memory locations in the same instruc-
,". 'vlth Pa s compne.
tlo. CF and OF are both 0 after OR, PF, SF, and ZF are
undated by the OR instruction. AF Is undefined after
NEG WORD PTh '": tjac- ..c,d at Jset IBP iu
OR. Note that PF has meaning only for the lower 8 bits
SS with b 2s complement a ree.xit.
NOTE: The BYTE PTR and WORD PTR dtrc.th'es
are required In the last two exames to tell tue I y AMPLLS (SYNTAX):
assembler whether to code the instruction for
a byte operation oi a word operatior The )BPI OR AH.CI. CL ORed with Al-), result in Al-I.
reference by itself does not indicate the type of the
CL not changed
operand.
OR HP.S1 SI ORed with BP, result in BP.
NOP—Perform No Operation SI not changed

'this host! uction simply uses up three clock cycles and OR SJ.BP BP ORed with SI. result In SI.
Increments the instnwtlon pointer to point to the flex' BP not changed
Instruction. NOP affects no flags. The NOP Instruction
can be used to increase the delay of a delay loop, as OR BL.80H BL ORed with Immediate 80H.
shown in Figure 4-27a. When hand coding. a NOP can Set MSB of BI. to a I

148 CHAPTER SIX


OR CX. TABLELBXIISII EXAMPLES:
CX ORed with word from
effective address TABLEIBXISII POP DX Copy a word from top of stack to DX
in data segment. Word in Increment SP by 2
memory is not changed
POP DS Copy a word from top of stack to DS
Increment SP by 2
EXAMPLE (NUMERiCAL):
POP TABLE EBXI Copy a word from top of stack to
CX = 00111101 10100101
memory in DS with EA =
ORCX,OFFOOH OR CX with immediate E'FOOH
Result in CX TABLE + lBXl
11111111 10100101
Note upper byte now all l's. lower
byte unchanged
POPF—Pop Word from Top
:CF = 0,OF= 0,PF= 1,SF= I,
of Stack to Flag Register
ZF = 0 This instruction copies a word from the two memory
locations at the top of the stack to the flag register and
increments the stack pointer by 2. The stack segment
OUT—Output a Byte or Word to a Port—OUT register and the word on the stack are not affected. AU
Port,Accumutator AL or AX flags are affected.
The OUT instruction copies a byte from AL or a word
from AX to the specified port. The OUT instruction has PUSH—PUSH Source
two possible forms. fixed port and variable port.
The PUSH instruction decrements the stack pointer by
For the fixed-port form, the 8-bit poit address Is
2 and copies a word from a specified source to the
specified directly in the Instruction. With this form, any
location in the stack segment where the stack pointer
one of 256 possible ports can be addressed.
then points. The source of the word can be a general-
purpose register, a segment register, or memory. The
EXAMPLES: stack segment register and the stack pointer must be
initialized before this instruction can be used. PUSH
OUT 3BH,AL Copy the contents of AL to port 3BH can be used to save data on the stack so tlat it will not
be destroyed by a procedure. It can also be used to put
OUT 2CH.AX ; Copy the contents of AX to port 2CH data on the stack so that a procedure can access it there
as needed. No flags are affected by this InstructIon. Refer
For the variable-port form of the OUT instruction, the to Chapter 5 for further discussion of the stack and the
contents of AL or AX w!tI be copied to the port at an PUSH instruction,
address contained in DX. Therefore, the DX register
must always be loaded with the desired port address
EXAMPLES:
before this form of the OUT instruction is used. The
advantage of the variable-port form of addressing is
described in the discussion of the IN instruction. The PUSH BX : Decrement SP by 2. copy UX
OUT instruction does not affect any flags. to stack

EXAMPLES: PUSH 'DS Decrement SP by 2. copy DS


to stack
MOV DX,OFFF8I-I : Load desired port address In DX
OUT DX.AL Copy contents of AL to port FPF8H PUSH AL Illegal, must push a word
OUT DX.AX Copy contents of AX to port FFF8H
PUSH TABLE (BXI Decrement SP by 2. copy word
from memory In DS at
EA = TABLE + (BXI to stack
POP—POP Destination
The POP Instruction copies a word from the stack PUSHF—Push Flag Register on the Stack
location pointed to by the stack pointer to a destination This instruction decrements the stack pointer by 2 and
specified in the Instruction, The destination can be a copies the word in the flag register to the memory
general-purpose register, a segment register, or a mem- locatIon(sl pointed to by the stack pointer. The stack
ory location. The data in the stack is not changed. After segment register Is not affected. No flags are changed.
the word is Copied to the specified destination, the stack
pointer is automatically incremented by 2 to point to
the next word on the stack. No flags are affected by th
RCL—Rotate Operand Around to the Left
POP instruction,
through CF—RCL Destination,Count
This Instruction rotates all the bits In a specified word
NOTE: POP CS is Illegal. or byte some number of bit positions to the left. The

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 149


operation is circular because tIi MSB f the operand is RCR—Rotate Operand Around to the Right
rotated Into the carry flag and the bit in the carry flag through CF—RCR Qestination,Couflt
is rotated around Into the LSB of the operand. See the This instruction rotates all the bits in a specified word
following diagram. or byte some number of bit positions to the right. The
operation Is circular because the LSB of the operand is
CF4-MSB( LSB rotated into e carry flag and the bit in the carry flag
is rotated around into the MSB of the operand. See the
following dlagran.

The "C" in the middle of the mnemonic should help you CF - MSB - LSB
remember that CF is in the rotated loop and help
distinguish this instruction from the ROL instruction.
For multibit rotates, CF will contain the bit most recently
rotated out of the MSB. The "C" in the middle of the mnemonic should help you
The destination operand can be in a register or in a remember that CF is in the rotated loop and should help
memory location specified by any one of the 24 ad- distinguish this instruction from the ROR instruction.
dressing modes shown in Figure 3-8. If you want to For multibit rotates. CF will contain the bit most recently
rotate the operand one bit position, you can specify this rotated out of the LSB.
by putting a I in the count position of the instruction. The destination operand can be in a register or in a
To rotate more than one bit position, load the desired memory location specified by any one of the 24 ad-
number into the CL register and put "CL" in the count dressing modes shown in Figure 3-8. If you want to
position of the instruction. rotate the operand one bit position, you can specify this
by putting a 1 in the count position of the instruction.
NOTE: The 80186. 80286. 80386. etc., allow you To rotate more than one bit position, loa the desired
to specify a rotate of up to 32 bit positions with number into the CL register and put "CL" In the count
either an immediate number in the instruction or position of the instruction.
a number in CL.
NOTE: The 80186, 80286, 80386, etc.. allow you
RCL affects only CF and OF. After RCL. CF will contain to specify a rotate of up to 32 bit positions with
the bit most recently rotated out of the MSB. OF will be either an immediate number in the instruction or
a I after a single-bit RCL if the MSB was changed by a number In CL.
the rotate. OF is undefined after a multibit rotate.
The RCL instruction is a handy way to move CF into RCR affects only CF and OF, After RCR. CF will c'ntain
the LSB of a register or memory location to save it after the bit most recently rotated Out of the MSB. OF will be
addition or subtraction. a I after a single-bit RCR if the MSB was changed by
the rotate. OF will be undefined after multibit rotates.

EXAMPLES (SYNTAX):
EXAMPLES (CODING):
RCL DX,1 Word in DX 1 bit left, MSB to
CF. CF to LSB RCR BX. I Word in BX right 1 bit
CF to MSB, LSB to CF
MOV CL.4 Load number of bit positions to
rotate into CL MOV CL,04F1 Load CL for rotating
RCL SUMIBXI.CL : Rotate byte or word at effective 4 bit positions
address SUMIBXI 4 bits left RCR HYFE PTR IBXI ; Rotate byte at offset IBXI in
Original bit 4 now in CF. original DS 4 bit positions right
CF now in bit 3 CF = original bit 3. Hit 4
= original CF

EXAMPLES (NUMERICAL): EXAMPLES (NUMERICAL):

;CF0.BH 10110011 :CF l.BLOOII1000


RCLBH.1 Result: HF! 01100110 RCR BL.1 Result: BL = 10011100, CF
CF = I. OF 1 because MSB changed OF = I because MSB
changed to I
;CF 1,AX 00011111 10101001
CF 0. WORD PTR IBXI
MOV CL,2 Load CL for rotating 2 bit positions = 01011110 00001111
RCL AX,CL Result: CF = 0, OF undefined MOV CL.02H Load CL for rotate 2 bit
;AX 01111110 10100110 positions

150 CHAP1'ER SIX


RCR WORD PTR LBXI. CL Rotate word in DS at just before the string instruction. The 80186,
offset IBXI 2 bits right 80286. etc., will remember all the prefixes and
CF = original bit 1. start up correctly after an interrupt during a string
Bit 14 = original CF instruction.
WORD PTR (BX]
10010111 10000011
RET—Return Execution from Procedure
to Calling Program
REP/REPEIREPZ/REPNE/REPNZ—(PrefiX) Repeat The RET instruction will return execution from a proce-
String Instruction until Specified Conditiqns Exist dure to the next instruction after the CALL instruction
REP is a prefix which is written before one of the which was used to call the procedure. If the procedure
string instructions. It will cause the CX register to be Is a near procedure (in the same code segment as the
decremented and the string instruction to be repeated CALL instruction), then the return will be done by
until CX 0. The instruction REP MOVSB. for example. replacing the Instruction pointer with a word from the
will continue to copy string bytes until the number of top of the stack. The word from the top of the stack is
bytes loaded into CX has been copied. the offset of the next instruction after the CALL. This
REPE and REPZ are two mnemonics for the same offset was pushed onto the stack as part of the operation
prefix. They stand for Repeat if Equal and Repeat if Zero, of the CALL instruction. The stack pointer will be
respectively. You can use whichever prefix makes the incremented by 2 after the return address is popped off
operation clearer to you in a given program. REPE or the stack.
REPZ is often used with the Compare String instruction If the procedure isa far procedure (in a different code
or with the Scan String instruction. REPE or REPZ will segment from the CALL instruction which calls it). then
cause the string instruction to be repeated as long as the instruction pointer will be replaced by the word at
the compared bytes or words are equal (ZF 1) and CX the top of the stack. This word is the offset part of the
is not yet counted down to zero. In other words, there return address put there by the CALL instruction. The
are two conditions that will stop the repetition: CX = 0 stack pointer will then be incrementea by 2. The code
or string bytes or words not equal. segment register is then replaced . with a word from the
new top of the stack. This word is the segment base part
of the return address that was pushed onto the stack
EXAMPLE: by a far call operation. After the code segment word
is popped off the stack, the stack pointer is again
REPE CMPSB Compare strIng bytes until end of string incremented by 2.
or until string bytes not equal. See the discussion of the A RET Instruction can be followed by a number, for
CMPS instruction for a more detailed example of the use eenmple. RET 6. In this case the stack pointer will be
of REPE. incremented by an additional six addresses after the lP
or the IF and CS are popped off the stack, This form is
REPNE and REPNZ are also two mnemonics for the used to increment the stack pointer over parameters
same prefix. They stand for Repeat if Not Equal and passed to the procedure on the stack.
Repeat if Not Zero, respectively. REPNE or REPNZ Is The RET instruction affects no flags.
often used with the Scan String instruction. REPNE or Please refer to Chapter 5 for further discussion of the
REPNZ will cause the string instruction to be repeated CALL and RET instructions.
until the compared bytes or words are equal (ZF = 1)
or until CX = 0 (end of string).
ROt—Rotate All Bits of Operand Left, MSB
EXAMPLE to [SB—ROt Destination,Count
This instruction rotates all the bits in a specified word
REPNE SCASW Scan a string of words until a word in or byte to the left some number of bit positions. The
the string matches the word In AX or until all of the operation can be thought of as circular; because the
string has been scanned. See the discussion of SCAS data bit rotated Out of the MSB is circled back into
'for a more detailed example of the use of this prefix the LSB. The data bit rotated out of the MSB Is also
copied to CF during ROL. In the case of multiple bit
The string instruction used with the prefix determines rotates. CF will contain a copy of the bit most recently
which flags are affected. See the individual instructions moved out of the MSB. See the following diagram.
for this information. Also see Chapter 5 for further
examples of the REP instruction with string instruc-
tions. CF4—MSB4 LSB

NOTE: Interrupts should be disabled when multi-


ple prefixes are used, such as LOCK, segment
override, and REP with string instructions on the The destination operand can be in a register or in a
8086/8088. This is because, during an interrupt memory location specified by any one of the 24 ad-
response. the 8086 can remember only the prefix dressing modes shown in Figure 3-8. If you want to

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 151


rotate the operand one bit position, you can specify this The destination operand can be in a register or in a
by putting a 1 in the count position of the instructIon. memory location specified by any one of the 24 ad-
To rotate more than one bit position, load the desired dressing modes shown in Figure 3-8. If you want to
number in the CL register and put 'CL' In the count rotac the operand one bit position, you can specify this
position of th instruction. by putting a I in the count position of the instructici.
NOTE: The 80186. 80286. 80386. etc.. allow you To rotate more than one bit position. load the desired
to specify a rotate of up to 32 bit positions with number in the CL register and put 'CL" in the count
either an immediate number in the instruction or position of the instruction,
a number in CL.
NOTE: The 80186. 80286. 80386, etc., allow you
ROL affects on l y CF arid OF. After ROL. CF will contain to specify a rotate of up to 32 bit positions with
the bit most recently rotated out of the MSB. OF will be either an Immediate number or a number in CL.
a I after a single bit ROL if the MSB was changed by
the rotate. ROR affects only CF and OF. After ROR. CF will contain
The ROL Instruction can be used to swap the nibbles the bit most recentiy rotated out of the LSB. For a single-
In a byte or to swap the bytes In a word. It can also be bit rotate, OF will be a I after ROR if the MSL3 is changed
used to rotate a bit into CF. where it cn be checked by the rotate.
and acted upon b the Conditional Jump instructions The ROR instruction can be used to swap the nibbles
JC (Jump if Cariy) and JNC (Jump if No Carry). In a byte or to swap the bytes in a word. It can also be
used to rotate a bit into CF. where it can be checked
EXAMPLES (SYNTAX): and acted upon by the Conditional Jump instructions
ROL AX! Word in AX I bit position left. JC (Jump if Carry) and JNC (Jump if No Carry).
MSB to LSB and CF

MOV CL.04H Load number of bits to rotate in CL EXAMPLES (SYNTAX):


ROL BL.CL Rotate BL 4 bit positions
(swap nibbles) ROR BL,1 Rotate all bits in BL right 1 bit position
LSB to MSB and to CF
ROL FACFORIBXI. I MSB of word or byte In DS at
EA = FACFORJBXI MOV CL,081-1 Load CL with number of bit
1 bit position left into CF positions to be rotated
JC ERROR Jump if CF = 1 to error routine ROR WORD PTR IEIXLCL Rotate word In DS at offset
(BXI 8 bit positions right
EXAMPLES (NUMERICAL): (Swap bytes In word)

;CF=0,BH= 10101110
ROLBH,l ;Result:CF,OF= l.BH = 01011101 EXAMPLE S (NUMERICAl.):

BX = 01011100 11010011 CF = 0, BX = 00111011 01110101


CL 8. set for 8-bit rotate ROR BX, 1 Rotate all bits of BX 1 bit position right
ROL BX,CL Rotate BX 8 times left (Swap bytes) CF l,BX = 10011101 10111010
:CF = 0,BX= l101OOlIOlOIIlOO
OF undefined ;CF=0,AL=1011OOIlOFl
MOV CL.04H Load CL for rotate 4 bIt positions
ROR AL.CL Rotate all bits of AL 4 bits right
ROR—Rotate II Bits of Operand Right, [SB :CF=0.AL=OOlIloll.OF'=?
to MSB—ROR Destination,Count
This instruction rotates all the bits of the specified word
or byte some number of bit positions to the right. The SAl-IF—Copy AH Register
operation is described as a rotate rather than a shift to Low Byte of Flag Register
because the bit moved out of the LSB is rotated around
Into the MSB. To help visualize the operation, think of The lower byte of the 8086 flag regsiter corresponds
the operand as a loop with the LSB connected around exactly to the 8085 flag byte. SAHF replaces this 8085
to the MSB. The data bit moved out of the LSB is also equivalent flag byte with a b yte from the AH register.
copied to CF during ROR. See the following diagram. In SAl-IF is used with the POP AX instruction to simulate
the case of multiple-bit rotates, CF will contain a copy the 8085 POP PSW instruction. As described under the
of the bit most recently moved out of the LSB. heading LAHF, an 8085 PUSH P5W instruction will be
translated to an LA}IF—PUSH AX sequence to run
on an 806. An 8085 POP PSW .nstn.Jction will be
CF MSB –LSl3 translated to a POP AX—SAl-IF sequence to run on an
8086. SAHF changes the (lags in the lower b yte of the
flag register.

152 CHAPTER SIX


SAL'SHL—Shift Operand Bits Left, Put Zero SAL BYTE PTR IBXI. 1 Shift byte In DS at offset
in LSB(s)—SAL/SHL Destination.Count IBX4
1 bit position left. 0 in
SAL and SElL are two mnemonics for the same instruc- [SB
tion. This instruction shifts each bit in the specified
destination some number of bit positions to the left. As Example of SAL
a bit is shifted out of the LSB position, a 0 is put in the instruction's
LSB position. The MSB will be shifted into CF. In the use to help pack BCD
case of multiple-bit shifts. CF will contain the bit most IN AL,COUNTER_DIGIT Unpacked BCE) from
recently shifted in from the MSB. Bits shifted into CF counter to AL
previously will be lost. See the following diagram. MOV CL,04H Set Count for 4 bit
positions
SAL AL,CL : Shift BCE) to upper
CF't— MSB( LS8-0 nibble,
0's in lower nibble. Ready
toOR
The destination operand can be a byte or a word. It can another BCE) digit into
be in a register or in a memory location specified by any lower nibble of AL
one of the 24 addressing modes shown In Figure 3-8.
If the desired number of shifts is one, this can be
specified by putting a 1 in the count position of the EXAMPLE (NUMERICAL):
instruction. For shifts of more than 1 bit position, the
desired number of shifts is loaded Into the CL register, ;CFO.BX= 11100101 11010011
and CL is put In the count position of the instruction. SAL BX. 1 : Shift 13X register oontents I bit p1tion left
The advantage of using the CL register is that the :CF I,BX= 11001011 10100110
number of shvfta can be dynamically calculated as the ;0F0,PF= ?.SF 1,ZFO
program executes.

NOTE: The 80186. 80286. 80386. etc., allow you


SAR—Shift Operand Bits Right. New MSB =
to specify a shift of up to 32 bit positions with
Old MSB—SAR Destination,Cwn
either an Immediate number in the instruction or This instruction shifts each bit Ir the specified destina-
a number In CL. tion some number of bit positions to the right. As a bit
is shifted out of the MSB position, a copy of the old MSB
The flags are affected as follows: CF contains the bit Is put in the MSB position. in other words, the sign
most recen'ly shifted in fron MSB. For a count of one. bit is copied into the MSB. The [SB will be shifted into
OF will be 1 If CF and thc current MSB are not the same. CF. in the case of multiple bit shifts. CF will contain the
For multiple-bit shifts, OF is undefined. SF and ZF will bit most recentiS' shifted in from the LSB. Bits shifted
be updated to reflect the condition of the destination. into CF previously will be lost. See the following diagram.
PF will have meaning only for an operand in AL. AF is
undefined.
The SAL or SHL instruction can aiso be used to MSB—*MSB ) SB
[ —CF
multiply an unsigned binary number by a power of 2.
Shifting a binary number one bit position to the left and
putting a 0 in the LSB multiplies the number by 2. The destination operand can be a byte or a word. It can
Shifting the number two bit positions multiplies it by be in a register or In a memory location specified by any
4. Shifting the number three bit positions multiplies It one of the 24 addressing modes shown in Figure 3-8.
by 8. etc. For this specific type of multiply, the SAL If the desired number of shifts Is one, this can be
specified by putting a 1 In the count position of the
method is faster than using MUL but you must make
instruction. For shifts of more than one bit position,
sure that the result does not become too large for the
destination. the desired number of shifts Is loaded into the CL
register, and CL Is pu4 in the count position of the
Instruction.
EXAMPLES (SYNTAX):
NOT E: The 80186. 80286, 80386. etc.. allow you
SAL BX,1 : Shift word In BX I bit to specify a shift of up to 32 bIt positions with
position left, either an ImmedIate number In the instruction or
0 in LSB a number In C).

MOV CL,02H Load desired number of The flags are affected as follows: CF contains the bit
shifts In CL most recently shifted In from the [SB. For a count of
SAL BP,CL : Shift word In BP left (CL) one, OF will be a I If the two MSBs are not the same.
bit After a multibit SAR. OF will be 0. SF and ZF will be
positions. 0's In 2 LSBs updated to show the condition of the destination. PF

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 153


will have meaning only for an 8-bit destination, AF will borrow flag will be set if a borrow was required to do the
be undefined after SAR. subtraction. The Subtract Instruction. SliD. subtracts
The SAR instruction can be used to divide a signed just the contents of the specified source from the con-
byte or word by a power of 2. shifting a binary number tents of the specified destination. The Subtract with
right one bit position divides it by 2. ShiftIng a binary Borrow instruction, SBB. subtracts the contents of the
number right two bit positions divides It by 4. Shifting source and the contents of CF from thecontents of the
it right three positions divides it by 8. etc. For unsigned Indicated destination. The source may be an immediate
numbers, a 0 is put in the MSB after the old MSB is number, a register. or a memory location specified by
shifted right. (See discussion of SHR Instruction.) For any of the 24 addressing modes shown in Figure 3-8.
signed binary numbers, the sign bit must be copied into The destination can also be a register or a memory
the new MSB as the old sign bit is shifted right. This is location. However, the source and the destination cannot
necessary to retain the correct sign in the result. SAR both be memory locations In an instruction. The source
shifts the operand right and copies the sign bit into the and the destination must both be of type byte or both
MSB as required for this operation. Using SAR to do a be of type word. If you want to subtract a byte from a
divide by 2. however, gives slighuy different results than word, you must first move the byte to a word location
using the IDE'.' instruction to do the same Job. IDE'.' such as a 16-bit register and fIll the upper byte of the
always truncates a signed result toward 0. For example. word with 0's. AF, CF. OF, PF, SF, and ZF are updated
an IDIV of 7 by 2 gives 3, and an IDly of —7 by 2 gives by the SUB instruction.
— 3. SAR always truncates a result in a downward
direction. Using SAR to divide 7 by 2 gIves 3, but using
SAR to divide —7 by 2 gives —4. EXAMPLES (SYNTAX):

SUB CX,BX CX - BX. Result in CX


EXAMPLES (SYNTAX):
SBB CH.AL Si.±tract contents of AL and
SAR Dl.1 Shift word in Dl one bit position right, contents of CF from
new MSB = old MS8 contents of CH. Result In CH

MOV CL,02H Load desired number of SUB AX,3427H Subtract Immediate number
shifts In CL 34271! from AX
SAR WORlD PTR IBPLCL Shift word at offset IBPI
in stack segment right SBB BX,(3427H( Subtract word at displacement
two bit positions. Two MSE3s 3427H in DS and contents
are now copies of of CF from DX
original MSB
SUB PRICES) BXI.04H Subtract 04 from byte at effective
EXAMPLES (NUMERICAL): address PRICESIBXI if PRICES declared with DB. Sub-
tract 04 from word at effective address PRICES)BXJ If
;AL = 00011101 = + 29 decimal CF 0 PRICES decarcz '!'. DW.
SAR AL.I Shift signed byte in AL right
to divide by 2 SBB CX,TABLEIBXI S.ibtract word from effective ad-
AL = 0000! 110 = + 14 decimal. CF = 1, dress TABLE[BXI and status of CF from CX.
:OF=0,PF= 0,SF=0.ZFO
SBB TABLE)BX],CX Subtract CX and status of CF from
BH = 11110011 - 13 decimal word In memory at effective address TABLEIBXI.
SAR BH, 1; Shift signed byte In BH right to
divide by 2 EXAMPLES )NUMERICAL):
:BH = 11111001 = - 7decimal.CF
:OF = 0,PF= l,SF= I. ZF=0 Example subtracting unsigned numbers
CL = 10011100 = 156 decimal
:BH 00110111 = 55 decimal
SBB—Subtract with Borrow—SBB SUB CL, BH : Result: CF,AF.SF.ZF = 0, OF.PF = 1
Destintion,Source CL = 01100101 = lOt decimal
SUB—Subtract—SUB Destination,Source
First example subtracting signed numbers
These instructions subtract the number in the Indicated CL = 00101110 + 46 decimal
source from the number in the Indicated destination BH = 01001010 + 74 decimal
and put the result In the indicated destination. For SUB CL. BH : Results: AF,ZF 0. PF
subtraction, the carry flag (CF) functions as a borrow CL 11100100 = —28 decimal
flag. The carry flag will be Set after a subtraction If the CF = I. borrow required
number in the specified source is larger than the number SF = 1, result negative
in the specified destination. In other words, the carry/ OF = 0. magnItude of result fits in 7 bIts

1 54 CHAPTER SIX
Second example subtracting NOTE: Scanning is repeated as long as the bytes
signed numbers are not equal and the end of the string has not
CL 10100001 - 95 decimal been reached. If a carriage return ODH is found.
:BH=01001100 +76decimal ZF = 1. and Dl will point at the next byte after the
SUB CL. BH Results: CF.ZF = 0. AF.PF 1 carriage return In the string. If a carriage return
CL 01010101 = + 85 decimal is not found, then CX = 0 and ZF 0. The
SF 0. result positive! assembler uses the name of the string to determine
OF 1, invalId result whether the string is of type byte or type word.
Instead of using te name, you can tell the assem-
bler the type of string directly by using the mne-
The overflow flag being set indicates that the magnitude monic SCASB for a byte string and SCASW for a
of the expected result, —171 decimal, is too large to fit word string.
in the 7 bits used for the magnitude in an 8-bit signed
number. If the Interrupt on Overflow Instruction, INTO.
has been executed previously, this error will cause the SHL-See Heading SAL
8086 to perform a software Interrupt procedure. Part of SHR-.---Shift Operand Bits Right, Put Zero
this procedure is a user-written subroutine to handle in MSB(s)—SIIR Destination.Coun(
the error.
This instruction shifts each bit in the specified destina-
NOTE: The SBB instruction allows you to sub- tion some number of bit positions to the right. As a bit
tract two multibyte numbers because any borrow is shifted right out of the MSB position, a Ols pufin its
produced by subtracting less significant bytes is place. The bit shifted Out of the LSB position goes to
Included in the result when the SBB instruction CF. In the case of a multiple-bit shift. CF will contain
executes. Although the preceding examples were the bit most recently shifted in from the LSB. Bits
for 8-bit numbers to save space, the principles are shifted into CF previously \wili be lost. See the following
the same for 16-bit numbers. For 16-bit signed diagram.
numbrs, however, SF isa copy of bit 15. and the
least significant 15 bits of the number are used to
represent the magnitude. Also. PF and AF function O—SMSB >LSB—i'CF
only for the lower 8 bits.

The destination operand can be a byte or a word In a


register or in a memory location specified by any one of
SCAS/SCASB/SCASW—Scan a String Byte
or a String Word the24 addressing modes shown in Figure 3-8.
If the desired number of shifts is one, this can be
SCAS compares a byte in AL or a word in AX with a byte specified by putting a 1 in the count position of the
or word pointed to by DI in ES. Therefore, the string to instruction. For shifts of more than one bit position.
be scanned must be in the extra segment, and DI must the desired number of shifts is loaded Into the CL
contain the offset of the byte or the word to be compared. register. and CL is put in the count position of the
If the direction flag is cleared (0). then Dl will be instruction. 1
incremented after SCAS. If the direction flag is set (I),
then Dl will be decremented after SCAS. For byte strings. NOTE: The 80186. 80286, 80386. etc.. allow you
Dl will be incremented or decremented by 1, and for to specify a shift of up to 32 bit positions with
word strings. Dl will be incremented or decremented by either an Immediate number in the instruction or
2. SCAS affects AF, CF. OF, PF. SF. and ZF. but it does a number in CL.
not change either the operand In AL (AX) or the operand
in the string. This instruction is often used with a The flags are affected by SFIR as follows: CF contains
repeat prefix to find the first occurrence of a specified the bit most recently shifted in from the LSB. For a
byte or word in a string. count of one, OF will be a lii the two MSBs are not both
0's. For multiple-bit shifts, OF is meaningless. SF and
EXAMPLE: ZF will be updated to show the condition of the destina-
tion. PF will have meaning only for the lower 8 bits of
Scan a text string of 80 characters the destination. AF is undefined.
for a carriage return. ODH. The I-1R instruction can be used to divide an unsigned
Put offset of string into DI binary numberby a power of 2. Shifting a binary number
MOV DI.OFFSET TEXT_STRING one bit position to the right and putting 0 In the MSB
MOV AL.ODH Byte to be scanned for into AL divides the number by 2. ShilLing the number two bit
MOV CX,80 CX used as element counter positions to the right divides ii by 4. Shifting it three
CLD Clear DF so Dl auioincrements bit positions to the right divides it by 8. etc. When an
REPNE SCAS TEXT_STRING odd number Is divided with this method, the result will
Compare byte in string with be truncated. In other words, dividing 7 by 2 will give a
byte in AL result of 3.

- 22 8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECtIVES 155


EXAMPLES (SYNTAX): pointed to by Dl. In effect, It replaces a string element
with a byte from AL or a word from AX. After the copy,
SHR BP, I Shift word in BP one bit position right, Dl is automatically incremented or decrernented to point
0 in MSB to the next string element in memory. lithe direction
flag (OF) is cleared, then Dl will automatically be Incre-
MOV CL,031-( Load desired number of shifts into CL mented by I for a byte string or incremented by 2 for a
SHR BYFE P1'R EBXI Shift byte In OS at offset word string. If the direction flag is set. Dl wiU be
IBXI 3 bits right. automatically decremented by I for a byte string or
0's in 3 MSBs decremented by 2 for a word string. STOS does not
affect any flags.
Example of StiR used to help unpack
two BCD digits In AL to BH and BL EXAMPLES:
MOV BL.AL Copy packed BCD to BL

AND BLOF1-I Mask out upper nibble. Low BCD Point DI at start of destination string
digit now in BL MOV DI,OFFSET TARGET_STRING
MOV CL.04H Load count for shift In CL STOS TARGET_STRING

StiR ALCL Shift AL four bit poaitlorls right and Assembler uses string name to determine
put 0's in upper 4 bits whether string is of type byte or type word. If
MOV B!-1,AL Copy upper BCD nibble to BH byte string, then string byte replaced with
contents of AL. If word string, then string word
EXAMPLES (NUMERICAL): replaced with contents of AX
Point Dl at Start of destination string.
:SI 10010011 1010110l,CF = 0
StiR SI,! Result: SI = 01001001 11010110 MOV DI.OFFSET TARGET_STRING
SlOSH
CF = 1, OF 1. PF = ?, SF = 0, ZF = 0
'8" added to STOS mnemonic directly tells
assembler to replace byte in string with byte
STC—Set the Carry Flag to a 1
from AL. STOSW would tell assembler directly to
STC does not affect any other flags. replace a word in the string with a word from AX..

STO—Set the Direction Flag to a 1 SUB—See Heading SBB

STD is used to set the direction flag to a 1 so that SI TEST—AND Operands to Update Flags-_TEST
and/or DI will automatically be clecremented to point Destination,Source
to the next string element when one of the string This instruction ANDs the contents of a source byte or
instructions executes, tithe direction flag is set. SI and' word with the contents olthe specified destination word.
or DI will be decremented by I for byte strings, and by Flags are updated, but neither operand is changed. The
2 for word strings. STD affects no other flags. Please TEST instruction is often used to Set flags before a
refer to Chapter 5 and the discussIon of the REP prefix Conditional Jump instruction.
in this chapter forexamples of the use of this instruction, The source operand can be an immediate number.
the contents of a register, or the contents of a memory
STI—Set Interrupt Flag (IF) location specified by one of the 24 addressing modes
shown in Figure 3-8. The destination operand can be in
Setting the interrupt flag to a 1 enables the INTR a register or in a memory location. The Source and the
interrupt input of the 8086, The instruction will not destination cannot both be memory locations in an
take effect until after the next instruction afte STI. instruction. CF and OF are both 0's after TEST. PF. SF.
When the INTR input is enabled, an interrupt signal on and ZF will be updated to show the results of the
this Input will then cause the 8086 to interrupt program ANDing. PF has meaning only for the lower 8 bits of the
execution, push the return address and flags on the destination. AF will be undefined.
stack, and execute an interrupt service procedure. An
IRET instruction at the end of the interrupt Service EXAMPLES (SYNTAX):
procedure will restore the flags which were pushed Onto
the stack, and return xcciition to the interrupted TEST AL.B1-( AND 8)-I with AL. no result stored.
program. STI does not affect any other flags. Update PF. SF. ZF
Please refer to Chapter 8 for a thorough discussion of
interrupts. TEST CX.000IH : AND CX with immediate number
00011-I. no result stored.
STOS/STOSB/STOSW__Store Byte Update PF. SF. ZF
or Word in String
TEST BP.IBXIDI) : AND word at offset IBXIDII in
The STOS instruction copies a byte from AL or a word OS with word in HP. no result
from AX to a memory location in the extra. segment stored. Update PF. SF. and ZF

156 CHAPTER SIX


Example of a polling sequence XLAT/XLATB—Translate a Byte in AL
using TEST
AGAIN; IN AL.2AH ; Read port with strobe The XLATB instruction is used to translate a byte from
connected to LSB one code to another code. The instruction replaces a
TEST AL.OIH ; AXE) immediate 01Ff with AL byte in the AL register with a byte pointed to by BX in
to test if LSB of AL is 1 or 0 a lookup table in memory. Before the XLATB Instruction
ZF = 1 1fLSB of result isO can be executed, the lookup table containing the values
No result stored for the new code must be put in memory, and the offset
JZ AGAIN ; Read port again if LSB 0 of the starting address of the lookup table must be
loaded in BX. The code byte to be translated is put in
AL. To point to the desired byte in the lookup table, the
EXAMPLES (NUMERICAL):
XLATB instruction adds the byte in AL to the offset of
the start of the table in BX. It then copies the byte from
;AL = 01010001
the address pointed to by (BX + AL) back into AL.
TEST AL,80H ; AND immediate 80H with AL to teat
XLATB clnges no flags. The section "Converting One
;if MSB of AL is I orO
Keyboard Code to Another" in Chapter 9 should clarify
ZF 1 if MSB of AL = 0. the use of the XLATB instruction.
AL = 01010001 (unchanged)
PF 0, SF 0, EXAMPLE: -
ZF I because AND1ng produced 00
808 routine to Convert ASCII code
byte to EBCDIC equivalent.
WAIT—Wait for Test Signal or Interrupt Signal ASCII code byte is in AL at start.
EBCDIC code in AL at end
When this Instruction executes, the 8086 enters an idle MOV BX,OFFSET EBCDIC_TABLE
condition in which it is doing no processing. The 8086 Point BX at start of EBCDIC
will stay in this idle state.until the 8086 TEST input table in DS
pin is made low or until an interrupt signal is received XLATB Replace ASCII in AL with
on the INTR or the NMI interrupt input pins. if a valid EBCDIC from table
interrupt occurs white the 8086 is in this idle state, the
8086 will return to the Idle State after the 4nterrupt The %LATB instruction can be used to convert any code
service procedure executes. It returns to the idle state of 8 bits or less to any other ccde of 8 bits or less.
because the address of the WAIT instruction is the
address pushed on the stack when the 8086 responds
to the interrupt request. WAIT affects no flags. The XOR—Exdusive OR Corresponding Bits of Two
WAIT instruction is used to synchronize the 8086 with Operands—XOR Destination,Source
external hardware such as the 8087 math coprocessor.
In Chapter 11 we describe how this works. This instruction Exclusive-ORs each bit in a source byte
or word with the same number bit in a destination byte
orword. The result replaces the Contents of the specified
XCHG—XCHG Oestination,Source destination. The contents of the specified source will
not be changed. The result for each bit position will
The XCHG instruction exchanges the contents of a follow the truth table for a two-input Exclusive OR gate.
register with the contents of another register or the In other words, a bit in the destination will be set to a
contents of a register with the contents of a memory I if that bit in the source and that bit in the original
iocation(s(. The XCHG cannot directly exchange the destination were not the same. A bit Exclusive-ORed
contents of two memory locations. A memory location with a 1 will be inverted. A bit Exclusive-ORed with a 0
can be specified as the source or as the destination by will not be changed. Because of this, you can use the
any of the 24 addressing modes summarized in Figure XOR instruction td selectively Invert or not invert bits
3-8. The source and destination must both be words, or In an operand.
they must both be bytes. The segment registers cannot The source operand can be an immediate number.
be used in this instruction. No flags are affected by this the contents of a register, or the contents of a memory
instruction. location specified by any one of the addressing modes
shown in Figure 3-8. The destination can b a register
or a memory location. The source and destination cannot
EXAMPLES:
both be memory locations in the same instruction. CF
and OF are both 0 after XOR. PP. SF'. and ZF are
XCHG AX.DX ; Exchange word In AX with word in DX
updated. PP has meaning only for an 8-bit operand. AF Is
undefined after XOR.
XCHG BL.CH : Exchange byte in BL with byte in CII
EXAMPLES (SYNTAX):
XCHG AL.PRICES 113X1 Exchange byte in AL with
byte in memory at XOR CL.B11 Byte in BH Exclusive-ORed with byte
EA = PRICES (BX! in DS in CL. Result in CL BH not changed

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 157


XOR BP,D1 Word In Dl Exciusive-ORed with word i-un. Refer to Chapter 3 for further discussion of the DR
in BP. Result in BP. DI not changed directive and to Chapter 4 for a discussion of how you
can access variables named with a DR in your programs.
XOR WORD PTR IBXIOOFFH Here are a few more examples of DR statements.
Exclusive-OR immediate number OOFFH with
word at offset IBXI in data segment. Result1r PRICES DB 49H,98H.29H : Declare array of 3 bytes
memory location IBXI named PRICES and initialize 3 bytes as shown.

NAME_HERE OB THOMAS': Declare array of 6 bytes


EXAMPLE (NUMER1CALI: and initialize with ASCII codes for letters in THOMAS.
BX = 0011110! 01101001 TEMPERATURE_STORAGE DB 100 DUPI?) : Set aside
CX = 00000000 11111111 100 bytes of storage in memory and give it the name
XOR BX.CX Result: BX = 00111101 10010110 TEMPERATURE_STORAGE. but leave the 100 bytes
Note bits in lower byte are inverted
uninitialized. Program instructions will load values into
CF,OF.SF.ZF 0. PF = 1. AF =
these locations.

PRESSURE_STORAGE DB 20H DUPIO) : Set aside 20H


ASSEMBLER DIRECTIVES bytes of storage in memory, give it the name PRES-
SURE_STORAGE, and put 0 in all 20H locations.
The words defined in this section are directions to the
assembler, not Instructions for the 8086. The assembler
directives described here are those for the intel 8086 00—Define Doubleword
macro assembler (ASMS6). the Borland Turbo Assembler
The DD directive is used to declare a variable of type
(TASM). and the IBM macro assembler (MASM). If you
doubleword or to reserve memory locations which
are using some other assembler, consult the manual for
can be accessed as type doubleword. The statement AR-
it to find the corresponding directives.
RAY_POINTER DD 2562926lH. for example, will define
a doubleword named ARRAY_POINTER and initialize
ASSUME the doubleword with the specified value when the pro-
gram is loaded Into memory to be run. The low word.
The ASSUME directive is used to tell the assembler the 926lH. will he put in memory at a lower address than
name of the logical segment It should use for a specified the high word. A declaration of this type Is often used
segment. The statement ASSUME CS:CODE. for exam- with the LES or LOS instruction. The instruction LES
ple. tells the assembler that the instructions for a DI.ARRAY_POINTER. for example, will copy the low
program are in a logical segment named CODE. The word of this doubleword. 926lH. into the DI register
statement ASSUME DS:DATA tells the assembler that and the high word of the doubleword, 2562H, into the
for any program instruction which refers to the data extra segment register.
segment. it should use the logical segment called DATA.
If. for example, the assembler reads the statement MOV
AX.IBXI after it reads this ASSUME, it will know that DQ.—Define Quadword
the memory location referred to by [BXI is in the logical
segment DATA. You must tell the assembler what to This directive Is used to tell the assembler to declare a
assume fr any segment you use in a program. If you variable 4 words in length or to reserve 4 words of
use a stack in your program. you must tell the assembler storage in memory. The statement BIG_NUMBER DQ
the name of the logical segment you have set up as a 243598740192A92BH. for example. will declare a vari-
stack with a statement such as ASSUME SS:STACK_. able named BIG_NUMBER and initialize the 4 words set
HERE. For a program with string Instructions which aside with the specified number when the program is
loaded Into memory to be run. The statement STORAGE
use Dl, the assembler must be told what to assume for
DQ 100 DUP(0) reserves 100 quadwords of storage and
tht extra segment with a statement such as ASSUME
initializes them all to 0 when the program is loaded Into
ES STRING_DESTINATION. For further discussion of
memory to be run.
the ASSUME directive, refer to the appropriate section
of Chapter 3.
01—Define Ten Bytes
DB—Define Byte DT is used to tell the assembler to define a variable
The DB directive is used to declare a byte-type variable. which Is 10 bytes In length or to reserve 10 bytes of
or to Set aside one or more storage locations of type byte storage In memory. The statement PACKED_BCD
in memory. The statement CURRENT_TEMPERATURE DT I 1223344556677889900 will declare an array
DR 42H. for example, tells the assembler to reserve I named PACKED_BCD which is 10 bytes in length.
byte of memory for a variable named CURRENT_TEM- It will initialize the 10 bytes with the values
PERATURE and to put the value 42H in that memory 11223344556677889900 when the program is loaded
location when the program i loaded into RAM to be Into memory to be run. This directive Is often used when

158 CHAPTER SIX


declaring data arrays for the 8087 math coprocessor. with the SEGMENT directive to "bracket" a logical
discussed in Chapter 11. The statement RESULTS DT segment containing instructions or data. Here's an
20H DUPtO) will declare an array of 20H blocks of 10 example.
bytes each and initialize all 320 bytes to 00 when the
program is loaded into memory to be run. CODE SEGMENT Start of logical segment
containing code
Instruction statements
OW—Define Word CODE ENDS End of segment named
The DW directive is used to tell the assembler to define CODE
a variable of type word or to reserve storage locations of
type word in memory. The statement MULTIPLIER DW EQU—Equate
437AH. for example, declares a variable of type word EQU is used to give a name to some value 'or symbol.
named MULTIPLIER. The statement also tells the assem- Each time the assembler finds the given name in the
bler that the variable MULTIPLIER should be initialized program, it will replace the name with the value or
with the value 437A}I when the program is loaded into symbol you equated with that name. Suppose, for exam-
memory to be run. Refer to Chapter 3 for further ple. you write the statement CORRECTION_FACTOR
discussion of the DW directive and how you can access EQU 03H at the start of your program. and later in
variables named with a DW in your programs. Here are the program you write the instruction statement ADD
a few more examples of DW statements. AL,CORRECTION_FACTOR. When it codes this instruc-
tion statement, the assembler will code it as if you had
THREE_LITFLE._WORDS DW 1234H.3456H,5678H
;Declare array of 3 words and initialize with specified written the instrucUon ADD AL.03H The advantage of
using EQU in this nianner is that if CORRECTION_FAC-
values.
TOR is used 27 times in a program. and you want to
STORAGE DW 100 DUP(0) Reserve an array of 100 change the value, all you have to do is change the EQU
words of memory and initialize all 100 words with 0000. statement and reassemble the program. The assembler
Array Is named STORAGE. will automatically put in the new value each time it finds
the name CORRECTION_FACTOR, If you had used 03H
STORAGE DW 100 DUP(?) Reserve 100 words of storage instead of the EQU approach. then you would have had
in memory and give it the name STORAGE, but leave to try to find all 27 instructIons and change them
the words uninitialized. yourself. Here are some more examples.

CONTROL_WORD EQU 11001001 Replacement


END—End Program MOV AL,CONTROL_WORD assignment
The END directive is put after the last statement of a
program to tell the assembler that this is the end of DECIMAL...ADJUST EQU DAA Create clearer
the program module. The assembler will ignore any mnemonic for DAA
statements after an END directive, so you should make ADD AL,BL Add BCD numbers
sure to use only one END directive at the very end of DECIMAL_ADJUST Keep result in BCD format
your program module. A carriage return is required after
the END directive. STRING_START EQU IEXI Give name to IBXI

EVEN—Align on Even Memory Address


ENDP—End Procedure
As the assembler assembles a section of data declaratIons
This directive is used along with the name of the or instruction statements, it uses a location counter to
procedure to indicate the end of a procedure to the keep track of how many bytes it is from the start of a
assembler. This directive, together with the procedure segment at any time. The EVEN directive tells the
directive. PROC. is used to "bracket" a procedure. Here's assembler to incremert the location counter to the next
an example. even address if ills not already at an even address, The
8086 can read a word from memory in one bus cycle If
SQUARE_ROOT PROC Start of procedure the word is at an even address, lithe word starts at an
Procedure instruction odd address, the 8086 must do two bus cycles to get the
statements 2 bytes of the word. Therefore, a series of words can be
SQUARE_ROOT ENDP End of procedure read much more quickly if they are at even addresses.
When EVEN is used in a data segment. the location
Chapter 5 shows more examples and describes how counter will simply be incremented to the next even
procedures are written and called. address If necessary. When EVEN is used In a code
segment. the location counter will be incremented to
the next even address if necessary. A NOP instruction
ENDS—End Segment will be inserted In the location Incremented over. Here's
This directive is used with the name of a segment to an example which shows why you might want 10 use
indicate the end of that logical segment. ENDS is used EVEN in a data segment.

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 159


DATA_.HERE SEGMENT sembler that DMSOR is a variable of type word which
Locatloif counter will point is in another assembly module or EXTRN. -
to 0009 after assembler
reads next statement
SALES_AVERAGES DB 9 DUPI?) GROUP—Group-Related 5egments
declare array of 9 bytes
The GROUP directive is used to tell the assembler to
EVEN Increment location
group the logical segments named after the directive
Counter to 000AI-I
into one logical group segment. This allows the contents
INVENTORY_RECORDS DW 100 DUP(0)
of all the segments to be accessed from the same group
Array of 100 words starting
segment base. The assembler sends a message to the
on even address for
linker and/or locator telling It to link the segments so
quicker read
DATA_HERE ENDS that the segments are physically in the same 64'Kbyte
segment. An example of the GROUP directive would be
SMALL_SYSTEM GROUP CODE.DATA,STACK_SEG.
An appropriate ASSUME statement to follow this would
EXTRN
be ASSUME CS:SMALL_SYSTEM, DS:SMALL_SYS-
The EXTRN directive is used to tell the assembler that TEM. SS SMALL_SYSTEM.
the names or labels following the directive are in some
other assembly module. For example. if you want to call
a procedure which is in a program module assembled
INCLUDE—Include Source Code from File
at a different time from that which contains the CALL This directive is used to tell the assembler to insert a
instruction, you must tell the assembler that the proce- block of source code from the named file into the current
dure is external. The assembler wiU then put information source module. This shortens the source code. An
In the object code file so that the linker can connect the alternative is to use the editor block commands to copy
two modules together. For a reference to an external the tile into the current source module.
named variable, you must specify the type of the variable,
as in the statement EXTRN DIVISOR:WORD. Constants
defined with an EQU in another module are identified LABEL
as type ABS in an EXTRN statement. For a reference to
a label, you must specify whether the label is near (in a As the assembler assembles a section of data declarations
or instruction statements, it uses a location counter to
code segment with the same name) or far (in a code
keep track of how many bytes it Is from the start of a
segment with a different name). The statement EXTRN
segment at any time. The LABEL directive Is used to
SMART_DIVIDE:FAR tells the assembler that SMART_
give a name to the current value in the location counter.
DIVIDE isa label of type far In another assembly module.
Names or labels referred to as external in one module The LABEL directive must be followed by a term which
specifies the type you want associated with that name.
must be declared public with the PUBLIC directive in
the module in which they are defined. lithe label is going to be used as the destination for a
jump or a call, then the label must be specified as type
EXTRN statements should usually be bracketed with
near or type far. If the label is going to be used to
SEGMENT_ENDS directives which identify the segment
reference a data item, then the label must be specified
in which the external name or label will be found. Here's
an example of how to do this. as type byte, type word, or type doubleword. Here's how
we use the LABEL directive for a jump address.
PROCEDURES_HERE SEGMENT
ENTRY_POINT LABEL FAR Can jump to here from
EXTRN SMART_DIVIDE:FAR : Found in segment
another segment
PROCEDURES_HERE
PROCEDURES_HERE ENDS
NEXT: MOV AL.BL Cannot do a far jump
directly to a label
Refer to Chapter 5 for a thorough discussion of the
use of the EXTEN and PUBLIC directives. with a colon

Here's how we use the LABEL directive for a data


reference.
GLOBAL—Declare Symbols
as PUBLIC or EXTRN
STACK_SEG SEGMENT STACK
The GLOBAL directive can be used in place of a PUBLIC DW 100 DUP(0) Set aside 100 words
directive or in place of an EXTRN directive. For a name for stack
or symbol defined in the current assembly module, the STACK_TOP LABEL WORD : Give name to next
GLOBAL directive Is used to make the symbol available location after last
to other modules. The statement GLOBAL DIVISOR, for STACK_SEG ENDS word in stack
example, makes the variable DIVISOR public so that it
can be accessed from other assembly modules. To initialize stack pointer, then. MOV SP.OFFSET
The statement GLOBAL DIVISOR:WORD tells the as- STACK_TOP.

160 CI-iAPTER SIX'


LENGTH—Not Implemented in IBM MASM might be used in a data segment to leave 100 bytes of
space for future use.
LENGTH is an operator which tells the assembler to
determine the number of elements in some named data
item, such as a string or an array When the assembler PROC—Procedure
reads the statement MOV CX.LENGTH STRING!, for The PROC directive is used to identify the start of a
example, it will determine the number of elements in
STRING! and code this number in as part of the procedure. The PROC directive follows a name you give
Instruction. When the instruction executes, then, the the procedure. After the PROC directive, the term near
length of the string will be loaded into CX. If the string or the term jar is used to specify the type of the
was declared as a string of bytes, LENGTH will produce procedure. The statement SMART_DIVIDE PROC FAR,
the number of bytes in the string. If the string was for example, identifies the start of a procedure named
declared as a word string. LENGTH will produce the SMART_DMDE and tells the assembler that the proce-
number of words in the string. dure is far (in a segment with a different name from
the one that contains the instruction which calls the
procedure). The PROC directive is used with the ENDP
NAME directive to "bracket" a procedure. Refer to the ENDP
discussion for an example of this. Also refer to Chapter
The NAME directive Is used to give a specific name to 5 for a thorough discussion of how procedures are
each assembly module when programs consisting of written and called.
several modules are written. The statement NAME
PC_BOARD, for example, might be used to name an PTR—Pointer
assembly module which contains the Instructions for
controlling a printed-circuit-board-making machine. The PTR operator is used to assign a specific type to a
variable or to a label. It is necessaly to do this In any
instruction where the type of the operand is not cl.ar.
OFFSFT When the assembler reads the Instruction INC (BX). for
OFFSET is an operator which tells the assembler to example, It will not know whether to Increment the byte
determine the offset or displacement of a named data pointed to by fiX or to increment the word pointed to
item (variable) or procedure from the start of the segment by RX. We use the PTR operator to clarify how we want
which contains It. This operator is Usually used to load the assembler to code the instruction. The statement
the offset of a variable into a register so that the variable INC BYTE PTR {B(I tells the assembler that we want to
can be accessed with one of the indexed addressing Increment the byte pointed to by BX, The statement INC
modes. When the assembler reads the statement MOV WORD PTR IBXJ tells the assembler that we want to
BX.OFFSET PRICES, for example, it will determine the Increment the word pointed to by BX. The PTR operator
offset of the variable PRICES from th€ start of the assigns the type specified before PTR to the variable
segment in which PRICES is defined and code this specified after PTR.
displacement in as part of the instruction. When the The PTR operator can be used to override the declared
instruction executes, this computed displacement will type of a variable. Suppose, for example, that we have
be loaded into fiX. An instruction such as ADD AL.(BXI declared an array of words with the statements WORDS
can then be used to add a va'ue from PRICES to AL. DW 437A1-1, 08972H, 7C4 iH. Normally we would access
the elements in this array as words. However. if we want
to access a byte in the array, we can do it with an
ORG—Originate instruction suh as MOV AL. BYTE PTR WORDS.
We also use the ErR operator to clarify our intentions
As the assembler assembles a section of data declarations when we use indirect Jump instructions. The statement
or instruction statements, it uses a location counter to JMP IBXI. for example, does not tell the assembler
keep track of how many bytes It is from the start of a whether to code the instruction for a near jump or for
segment at any time. The location counter is automati- a far jump. If we want to do a near jump. we write the
cally set to 0000 when the assembler starts reading a instruction as JMP WORD VFR IBXI. If we want to do a
segment. The ORG directive allows you to set the location far jump, we write the instruction as JMP DWORD PTR
counter to a desired value at any point in e program. IBXJ. Please refer to Chapter 3 for further discussion of
The statement ORG 2000H tells the assembler to set the 'the 8086 jump instructions.
location counter to 2000H, for example.
A "S' is often used to symbolically represent the Public
current value of the location counter. The S actually
represents the next available byte location where the Large programs are usuall y written as several separate
assembler can put a data or code byte. The S is often modules, Each module is individuall y assembled, tested,
used In ORG statements to tell the assembicr to make and debugged. When all the Wiodules are working cor-
some change in the location counter relative to its rectly. their object code files arc linked together to form
Current value. The statement ORG S i- 100 tells the the complete program. In order for the modules to link
assembler to increment the value of the location counter together correctly , any variable name or label referred to
by 100 from its current value. A statement such as this in other modules must be declared public in the module

8118€ INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 161


in which it Is defined. The PUBLIC directive is used to CODE SEGMENT PUBLIC tells the assembler that this
tell the assembler that a speciñed name or label will segment may he put together with other segments
be accessed from other modules. An example is the named CODE from other assembly modules when the
statement PUBLIC DIVISOR.DIVIDEND, which makes modules are linked together.
the two variables DMSOR and DIVIDEND available to
other assembly modules.
If an instruction in a module refers to a variable or SHORT
label in another assembly module, the assembler must
be told that it is external with the EXTRN directive. The SHORT operator is used to tell the assembler that
Refer to the discussion of the EXTRN directive to see only a I-byte displacement is needed to code a Jump
how this is done. instruction. If the jump destination is after the Jump
instruction in the program. the assembler will automati-
cally reserve 2 bytes for the displacement. Using the
SHORT operator saves 1 byte of memory by telling the
SEGMENT assembler that it needs to reserve only 1 byte for this
particularjump. In order for this to work, the destination
The SEGMENT directive Is used to indicate the start of
must be in the range of —'128 bytes to + 127 bytes from
a logical segment. Preceding the SEGMENT directive is
the address of the instruction after the jump. The
the name you want to give the segment. The Statement
statement JMP SHORT NEARBY_LABEL is an example
CODE SEGMENT, for example, indicates to the assem-
of the use of SHORT.
bler the start of a logical segment called CODE. The
SEGMENT and ENDS directives are used to "bracket" a
logical segment containing code or data. Refer to the TYPE
ENDS directive for an example of how this is done.
Additional terms are often added to a SEGMENT The 'FYPE operator tells the assembler to determine the
directive Statement to indicate some special way in type of a specified variable. The assembler actually
which we want the assembler .to treat the segment. The determines the number of bytes in the type of the
statement CODE SEGMENT WORD tells the assembler variable. For a byte-type variable, the assembler will give
that we want the contents of this segment located on a value of 1. For a word-type variable, the assembler will
the next available word (even) address when segments give a value of 2. and for a doubleword-type variable. it
are combined and given absolute addresses. Without will give a value of 4. The TYPE operator can be used in
this WORD addition, the segment will be located on the an instruction such as ADD BX,TYPE WORI1.ARRAY.
next available paragraph (16-byte) address, which might where we want to increment BX to point to the next
waste as much as 15 bytes of memory. The statement word in an array of words.

'162 CHAPTER SiX


8086 System Connections,
Timing, and Troubleshooting

As we showed you in Chapter 2, a microcomputer you need to write programs. Now we will look at the bus
consists of a CPU. memory, and ports. These parts are signals. timing, and circuit connections of an 8086 and
connected together by thiee major buses: the address an 8088. In a later chapter we will show the hardware
bus, the control bus, and the data bus. In Chapters 3 connections for the 80286 and 80386 microprocessorS.
through 6, however, we made little mention of the
hardwate of a microcomputer because we were mostly System Overview
concerned in these chapters with how a microcomputer
is programmed. In this chapter we come back to take a Figure 7-1 a shows a block diagram of a simple 8086-
closer look at microcomputer hardware. based microcomputer. This diagram is a closer look at
the generalized microcomputer in Figure 2-5. First, find
the 8086 CPU, the ROM; and the RAM in Figure 7-la.
OBJECTIVES Next, look for the ports, represented by the block labeled
MCS . 80 PERIPHERAL. As we discuss in detail later.
At the conclusion of this chapter. you should be able to: there .is a wide variety of port devices available. Some
examples are parallel port devices such as the 8255A.
I. Draw a diagram showing how RAMs, ROMs, and serial port devices. special port devices which interface
ports are added to an 8086 C pu to make a simple with CRTs. port devices which interface with keyboards.
microcomputer. and port devices which Interface with floppy disks.
2. Describe how addresses sent Out on the 8086 data Next, find the control bus, address bus, and data bus
bus are demultiplexed. in Figure 7-la. The basic control bus consists of the
signals labeled M/lO, PD, and WR at the top of the figure.
3. Describe the 2lgnal sequence on the buses as a If the 8086 is doing a read from memory or from a port.
simple 8086-based microcomputer fetches and exe- the RD signal will be asserted, If the 8086 is doing a
cutes an Instruction. write to memory or to a port, the WR signal will be
4. Describe how a logic analyzer is connected to micro- asserted. D urinL a read from memory or a write to
computer signal lines and how it Is used to make memory, the MflO signal will be high, and during port
state and timing measurements. operations the M/lO signal will be low. As we show you
in detail later, the RD. WR, and M/1O signals are used
5. Describe how address decoding circuitry gives a to enable addressed devices.
specific address to each device in a system and The address bus and the data bus are shown separately
makes sure that only one device is enabled at a time. on the right side of Figure 7-la. but where they leave
the 8086, the two buses are shown as a single bus
6. Calculate the access time required for a memory
device or port to work correctly in an 8086 microcom- labeled ADDR/DATA. The reason for this is that, in.
order to save pins, the lower 16 bits of addresses are
puter system.
multiplexed on the data bus. Here's an overview of how
7. List a series of steps you might take to troubleshoot this works.
a malfunctioning microcomputer system that once As a first st.ep in any operation where It accesses
worked. memory or a port. the 8086 sends out the lower 16 bits
of the address on the data bus. External latches such
as the 74LS373 octal devices shown in Figure 7-la are
ASIC 8086 MICROCOMPUTER SYSTEM used to 'grab" this address and hold it during the rest
of the operation. To strobe these latches at the proper
Introduction time, the 8086 outputs a signal called Address Latch
In previous chapters we worked with what is often called Enable or ALE. Once the address is stored on the outputs
of the latches, the 8086 removes the address from the
the programmer's model of the 8086. This model shows
features such as internal registers. number of address address/data bus and uses the bus for reading or writing
lines, number of data lnes. and port addresses, which data.

163
—23

^ IsssvctocxI I w.I._-
I—•lcu( iiwiI
RIASY iiitA
NWT I
T
GIlD oTiI--, =
'w I-----,
r—
I
i
I ALE
I
lSOPU GNO-
745373
GENERATOR AOtAD1 AOOR/DATA OCTAL
ADDRESS
I Al-AlE LATCH
(2 OR 3)
L__J 11111

53..,I
TRANSCEIVER
(2)

OPTIONAL cso, E 00
FOR INcMAEED
DATA 5(5 DRIVE 2)42 RAM (41 2716-2PR014(2) II ISCS-lO
I I PERIPHERAL
1) (2)
XE I IKXI 2KXS J 2KXS

(a)
FIGURI 7-1 (a) Block diagram of a simple 8066-based microcomputer. (See
also ne.d page.)

Another section of Figure 7-Ia to look at briefly Is the bus Is being used for other operations. For example, you
block labeled 8286 Transceiver. This block represents certainly don't want data bus buffer outputs enabled
bidirectional three-state buffers. For a vely small system Onto the data bus while the 8086 Is putting out the
these buffers are not needed, but as more devices are lower 16 bIts of an address on these lines. The 8086
added to a system, they become necessary. Here's why. asserts the DEN signal to enable the three-state outputs
Must of the devices—such as ROMs, RAMs, and ports— on data bus buffers at the appropriate time In an
connected on microprocessor buses have MOS inputs. operation.
so on a dc basis they don't require much current. The final section of Figure 7-la to look at is the 8284A
However, each Input or output added to the System data clock generator in the upper left corner. This device uses
bus. for example, acts like a capacitor of a few picofarads a crystal to produce the stable-frequency clock signal
connected to ground. In order to change the logic State which steps the 8086 through execution of its iñstruc-
on these signal lines from low to high, all this added tions In an orderly manner, The 8284A also synchronizes
capacitance must be charged. To change the logic state the RESET ilgnal and the READY signal with the clock
to a low, the capacitance must be discharged. If we so that these signals are applied to the 8086 at the
connect more than a few devices on the data bus lines. proper times. When the RESET input Is asserted, the
the 8086 outputs cannot supply enough current drive 8086 goes to address FFFFOH to get Its next Instruction.
to charge and discharge , the circuit capacitance fast The first Instruction of t)e system start-up program Is
enough. Therefore, we add external high-current drive usually located at this address. So asserting this signal
buffers toö The Job. is a way to boot, or start, the system. We will discuss
Buffers used on the data bus must be bidirectional the use of the READY input In the next section.
because the 8086 sends data out on the data bus and Now that you have an overview of the basic system
also re*ds data In on the data bus. The Data Transmitl connections For an 8086 microcomputer. let's take a
Recetue stgnal. DT/. from the 8086 sets the direction look at the signal present on the buses as an 8086 reads
In which data will pass through the buffers. When data from memory or from a port.
OuR Is asaerted iigh. the buffers will be set up to trans-
mit data from the 8086 to ROM. RAM, or ports. When
D/R Is asserted low, the buffers will be set up to allow 8086 Bus Activities During
data toT.come Into the 8086 from ROM, RAM. or ports.
a Read Machine Cycle
The buffers used on the data bus must have three- FIgure 7-lb shows the sIgnal activities on the 8086
state outputs so the outputs can be floated when the microcomputer buses during simple read and write
164 CHAPTER SEVEN

I- (4+N.7)-T,
13 13 TWMT 1. T T 13
F

ALE ___r-___r-

MnoJ(
XI __

A0DR/STA1'US

ADOR/DATA

READY

OuR

DEN

(b)
___I..
FIGURE 7-1 (continued) (b) Basic 8066 system timing. (Intel Corporation)

operations. Don't be overwhelmed by all the lines on this tion cycle. An instruction cycle consists of one or more
diagram. Their meanings should become dear to you as machine cycles.
we work through the diagram. To summarjze this, an instruction c ycle is made un
The first line to look at in Figure 7-lb is the clock of machine cycles, and a machine cycle is made up of
waveform. CLK. at the top. This represents the crystal. states. The time (or a State Is determined by the fre-
controlled clock signal sent to the 8086 from an external quency of the clock signal. In this section we discues
clock generator device such as the 8284 shown in the the activities that occur on the 8086 mIcrocomputer
top left corner of Figure 7-la. One cycle of this clock is buses during a read machine cycle.
called a state. For reference purposes, a state is measured The best way to analyze a timing diagram such as the
from the (ailing edge of one clock pulse to the (ailing one in Figure 7-lb is to think of time as a vertical line
edge of the next clock pulse. The time intervAl labeled moving from left to right across the diagram. With this
T in the figure is an example of a state. Different technique you can easily see the sequence of activities
versions of the 8086 have maximum clock frequencies on the signal lines as you move your Imaginary time line
of between 5 MHz and 10 MHz, so the minimum time across the waveforms.
for one State will be between 100 and 200 es depending During T 1 of a read machine cycle the 8086 first
on the part used and the crystal used. asserts the M/lO signal. It will assert this signal high if
A basic microprocessor operation such as reading a it is going to do a read from memory during this cycle.
byte from memory or writing a byte to a port is called a and it will assert M/lO low If it Is going to do a read from
machine cycle. The times labeled T In Ffgure 7-lb are a port during this cycle. The timing diagram in Figure
examples of machine cycles. As you can see in the figure. 7-lb shows two crossed waveforms for the MilO signal
a machine cycle consists of several states. because the signal may be going low or going high for
The time a microprocessor requires to fetch and a read cycle. The point where the two waveforms cross
execute an entire instruction is referred to as an Inst ruc- indicates the time at which the signal becomes valid for

8086 SYSTEM CONNECTIONS, TIMiNG, AND TROIIBIESHOOTINC 165


this machine cycle. Likewise, in the resi of the timing with the next machine cycie. As long as Murphy's law is
diagram. crossed lines are used to represent the time still in force, the garbage read in will probably cause the
when Information ona line or group of lines is changed. entire program to crash. A section later in the chapter
After asserting M/lO. the 8086 sends out a high on shows you how to calculate whether a particular ROM.
the Address Latch Enable signal (ALE). This signal Is RAM. or port device has a short-enough access time to
connected to the enable input (STBI of the 74S373 octal work properly In a given 8086 system. For now, however.
latches, as shown In Figure 7-Ia. so these latches will we Just need you to understand the concept so we can
be enabled when ALE is high. As you can also see show you one way that an 8086 can accommodate a
In Figure 7-la, the data Inputs of these latches are slow device.
connected to the 8086 ADO—ADI5. Al6—A19. and Bus To refresh your memory. look again at the block
High Enable IBHE) lines. After the 8086 asserts ALE diagram in Figure 7-Ia to find an input on the 8086
high. it sends Out on these lines the address of the CPU labeled READY. When this pin is high. the 8086 Is
memory location that it wants toread. Since the latches 'ready" and operates normally.. If the READY input is
are enabled by ALE being high. this address information made low at the right time in a machine cycle, the 8086
passes through the latches to their outputs. The 8086 will insert one or more WAIT states between T 3 and 1,
then makes the ALE output low, which disables the in that machine cycle. The read timing diagram in
latches. The address held on the latch Outputs travels Figure 7-lb shows an example of this. An external
along the address bus to memory and port devices. hardware device is set up to pulse READY low before the
Note In the timing diagram in Figure 7-lb how the rising edge of the clock in T 2 . After the 8086 finIshes T
activitiy on the ADDRIDATA lines Is represented. The of the machine cycle, it enters a WAIT State. During a
first point at which the two waveforms cross represents WAIT state, the signals on the buses remain the same
the time at which the 8086 has put a valid address on as they were at (he start of the WAIT state. The address
these lines. These two waveforms do not Indicate that of the addressed memory location Is held on the output
all 16 lines are going high or going low at this point. of the latches, so it does not change, and as you can see
After ALE goes low, the address information is held from the timing diaam in Figure 7-lb. the control bus
on the latches, so the 8086 no longer needs to send out signals, MIlO and RD, also do not change during the
the addresses, Therefore, as shown by a dashed line on WAIT state. T5 r-. The memory or port devIce then has
the ADDRIDATA line in Figure 7-lb. the 8086 floats the at least one more clock cycle to get its data output. If
ADO—AD 15 lines so that they can be used to input data the READY input is made high again during T 3 or during
from memory or from a port. At about the same time, the WAIT State. as shown in Figure 7-lb. then after one
the 8086 also removes the BHE and A16—A19 informa- WAIT state the 8086 will go on with the regular T, of
tion from the upper lines and sends out some status the machine cycle.
information on those lines. If the 8086 READY input is still low at the end of a
The 8086 Is now ready to read data from the addressed WAIT state, then the 8086 will insert another WAI'I'
memory location or port, so near the end of state T2 state, The 8086 will continue inserting WAIT states until
the 8086 asserts its RD signal low. If you trace the the READY input is made high again.
connection of the RD signal in Figure 7-la. you should To summarize, inserting the WAIT state(s) freezes the
see that this signal Is used to enable the addressed action on the buses. This gives the addressed device one
memory device or port device. When enabled, the ad- or more extra clock cycles to put out valid data. As an
dressed device will put a byte or word of data on the example of how this is used, we can use slower (cheaper)
data bus. In other words, assertigtje RD signal low ROM In a system by adding a simple circuit which pulses
causes the addressed device to put data on the data the READY input low each time the ROM is addressed.
bus. This cause-and-effect relationship is shown on the No WAIT states will be Inserted in the read machine
uming diagram ingure 7-lb by an arrow going from cycle for reading data from faster devices such as the
the falling edge of RD to the "bus reserved for data in" RAM In the system.
section of the ADDR/DATA waveforms. The bubble on Note in Figure 7-la that a READY Input signal is
the tail of the arrow Is always put on the signal transition usually passed through the 8284A clock generator IC so
or- level that causes some action, and the point of the that the READY signal actually applied to the 8086 Is
arrow always indicates the action caused. Arrows of this synchronized with the system clock, -
sort are only used to show the effect a signai from one Now let's look back at Figure 7-lb to see how DEN and
device will have on another device. They are not usually DT/R function during a read machine cycle. During Tr
used to indicate signal cause and effect within a device. of the machine cycle the 8086 asserts DT/R low to put
Now, referring to Figure 7-lb again, find the section the data buffers In the receive mode. Then, after the
of the ADO—AD15 waveform marked off as memory 8086 finishes using the data bus to send out the lower
access time near the bottom of the diagram. This time 16 address bits. ii asserts DEN low to enable the data
represents the time It takes br the memory to output bus buffers. The data put on the data bus by an
valid data after it receives an address and an RD signal. audressed port or memory will then be able to come in
If the access time for a memory device is too long, the through the buffers to the 8086 on the data bus.
memory will not have valid data on Its outputs soon The activities on the 8086 buses during a read ma-
enough in the machine cycle for the 8086 to receive Ii chine cycle can be summarized as follows. The 808I
correctly. The 8086 will then treat whatever garbage asserts MO high If the read Is to be from memory and
happens to be on the data bus as valid data and go on asserts MJIO low If the read Is going to be from a port.

166 CHAPTER SEVEN


At about the same time, the 8086 asserts ALE high to Remember that during WAIT states the signals on the
enable the external address latches. It then sends out data bus, address bus, and control bus are held constant.
BHE and the desired address on the ADO—A19 lines. so the addressed device has one or more extra clock
When the 8086 pulls the ALE line low, the address cycles to accept the data from the data bus. lithe READY
information is latched on the outputs of the external input is made high before the end of the WAIT state, the
latches. After the 8086 is through using the ADO—AD 15 8086 will go on with state T, as soon as it finishes the
lines for an address. it removes the address from these WAIT state, If the READY input is still low just before
lines and puts the lines in the input mode (floats them). the end of the WAIT state, the 8086 will insert another
The 8086 then asserts its RD signal low. The RD signal WAIT state. It will continue to insert WAIT states until
going low turns on the addressed memory or port, which READY is made high. The point here is that the 8086
then outputs the desired data on the data bus. To can be forced to insert as many WAIT states as are
complete the cycle the 8086 brings the RD line high necessary for the addressed device to accept the data.
again. This causes the addressed memory or port to lithe system Is large enough to need buffers on the
float its outputs on the data bus. If the 8086 READY data bus, then DTIR will be connected to the direction
input is made low before or duringT 2 of a machine cycle. input on the buffers. During a write cycle, the 8086
the 8086 will insert WAIT states as long as the READY asserts DTIR high to put the buffers in the transmit
input is low. When READY is made high. the 8086 wIll mode. When the 8086 asserts DEN low to enable the
continue with T, of the machine cycle. WAIT States can buffers, data output from the 8086 will pass through
be used to give slow devices additional time to put out the buffers to the addressed port or memory location.
valid data, If a system is large enough to need data bus Work your way across the timing diagrams for the
buffers, then the 8086 DT/R signal connected to these read and write machine cycles in Figure 7-lb until you.
buffers will set them for input during a read operation feel that you understand the sequence of activities that
or set them for output during a write operation. The occurs.
8086 DEN signal , will enable the buffers at the appro-
priate time in the machine cycle.
A Closer Look at the 8086
8086 Bus Activities During Figure 7-2. p. 168, shows a pin diagram for the 8086.
a Write Machine Cycle You don't need to learn the detailed functions of all these
Now that we have analyzed the 8086 bus activities for a pins. The main reason for showing you this is so that
read machine cycle, let's take a look at the timing if you want to look at some of the 8086 sIgnals with a
diagram for a write machine cycle in the right-hand side scope or logic analyzer, you know which pins to connect
of Figure 7-lb. Most of this diagram should look very to. We also want to make a few comments about some
familiar to you because it is very similar to that for a of the pins to give you a clearer idea of how an 8086-
read cycle. based microcomputer functions.
During T of a write machine cycle the 8086 asserts
MIlO low lithe write is going to be to a port, and It NOTE: For reference, part of an 8086-data sheet
asserts M/lO high if the write is going to be to memory. showing all the pin descriptions is shown in Appen-
At about ihe same time, the 8086 raises ALE hig dix A.
enable the address latches. The 8086 then outputs BHE
and the address that It will be writing to on ADO.-A19. First, in Figure 7-2, find on pin 40 and ground on
incidentally, when writing to a port, lines Al6-Al9 will pins I and 20. Next, find the clock input, labeled CLK.
always be low, because the 8086 only sends out 16-bit on pin 19. As we showed you in the preceding sections,
port addresses. After the address has had time to pass an 8086 requires a clock signal from some external clock
through the latches, the 8086 brings ALE low again to generator to synchronize internal operations in the
latch the address on the outputs of the latches. Resides processor. Different versions of the 8086 have maximum
holding the address, these latches also function as clock frequencies ranging from 5 MHz to 10 MHz.
buffers for the address lines. After the address informa- Now look for the address/data bus lines. ADO—ADIS.
tion Is latched, the 8086 removes the address informa- Remember from the previous section that the 8086 has
tion from ADO-AD 15 and outputs the desired data on a 20-bit address bus and a 16-bit data bus and that the
the data bus. It then asserts its WR signal low. The WR lower 16 address lines are multiplexed Out Ofl the data
signal is used to turn on the memory or port that the bus to minimize the number of pins needed. The 8086
data is to be written t. After the addressed memory or sends out a signal called Address Latch Enable, or ALE.
port has had time to accept the data from the data bus. on pin 25 to strobe the external address latches. The
the 8086 raises the WR signal line high again and floats upper 4 bits of the 20-bit address are sent out on
the data bus. the Lines labeled Al 61S3 through Al 9/S6. The double
If the memory or port device cannot accept the data mnemonic on these pins shows that address bits A16
word within a normal machine cycle, external hardware through Al9 are seni out on these lines during the first
can be set up to pulse the READY input low each time part of a machine cycle, and status information, which
that memory or a port device is addressed. lithe READY Identifies the type o operation being done In that cycle,
input is pulsed low before or during T 2 of the machine is sent out on these lines during a later part of the cycle.
cycle, the 8086 will insert a WAIT state after state T3. Having found the address bus and the data bus, now

8086 SYSTEM CONNECTIONS, TIMING. AND TR0USI.ESHOOTING 167


the microcomputer to execute after a reset or when the
G NO 40
power is first turned on.
AD 14 36 *015
Finally, notice that the 8086 has two interrupt inputs.
*013 35 * 16/53 the nonmaskable interrupt (NMI) input on pin 17 and

*012 37 Al 7/S4 the Interrupt (INTR) input on pin 18. A signal. can be

*011 36 A IS/SI applied to one of these inputs to cause the 8086 to

*010 6 35 A 19/SI stop executing its current program and go execute an

*09 34 BHE/S7 interrupt procedure which takes care of the condition

ADS 8 33 MN/MX that caused the interrupt. You might. for example.
AD, 9 32 A0 connect a temperature sensor from a steam boiler to an
interrupt input on an 8086. II the boiler gets too hot.
*09 ID 31 R0/GTO (HOLD)
then the temperature sensor will assert the interrupt
*05 it CPU RO/Orl (HLDA(
input. Ttils will cause the 8086 to stop executing its
A04 12 29 LOCK (WR)
*03

13

26
current program and go execute an interrupt-service
(M/I)
procedure, which turns oIl' the fuel supply to the boiler.
*02 14 27 Sl (01/RI
A return instruction at the end of the interrupt-service
Aol 15 28 (DEN) procedure sends execution back to the interrupted pro-

ADO t6 25 050 (ALE) gram. In the next chapter we discuss interrupts further

NM) I, 24 051 (INTA) and show you how to write interrupt-service procedures.

INIR 18 23 TEST Now we show you how to use a logic analyzer to observe

CLK 19 22 READY and make measurements on microprocessor bus signals

OND 20 21 RESET such as those we discussed in the preceding section.
40 LEAD
FIGURE 7-2 8086 pin diagram. (Intel Corporation) USING A LOGIC ANALYZER TO OBSERVE
MICROPROCESSOR BUS SIGNALS

look for the control bus, gnaJ pins. Pin 32 of the 8086
Introduction
in Figure 7-2 is labeled RD. This signal will be asserted It is difficult to observe microprocessor bus signals with
low when the 8086 is reading data from memory or from a standard scope because you can only look at two signal
a port. Pin 29 has the labels WR and LOCK next to it lines at a time. A logic analyzer such as the Tektronix
because it has two functions. The function of this pin 1230 shown in Figure 7-3 allows you to observe and
and the functions of the other pins between 24 and 31 make measurements on 16 to 64 signal lines at once.
depend on the mode in which the 8086 is operating. Tht- least expensive version of the 1230 allows you to
The operating mode of the 8086 is determined by the look at up to 16 signals at once, but expansion boards
logic level applied to the MN/MX input, pin 33. If pin 33 is can be added to increase the number of input signal
asserted high, then the 8086 will function in minimum lines to 32, 48. or 64. Hewlett-Packard, Gould, and
mode, and pins 24 through 31 will have the functions several other companies make comparable stand-alone
shown in parentheses next to the pins in Figure 7-2. In logic analyzers.
minimum mode, for example, pin 29 will function as Personal computers can be adapted to function as
WR. which will go low any time the 8086 writes to a port logic analyzers by installing plug' In units such as the
or to a memory location. The RD. WR. and M/lO signals
form the heart of the control bus for a minimum-mode,
8086 system. The 8086 is operated in minimum mode
In systems such as the SOK-86 where it is the only
microprocessor on the system buses.
If the MN/MX pin is asserted low, then the 8086 is in
maximum mode. In this mode, pins 24 through 31 wIll
have the functions described by the mnemonics next to
the pins in gure 7-2 In this mode, the control bus
signals (SO. SI. and S21 are sent Out in encoded form
on pins 26. 27, and 28. An exterçial bus controller device
decodes these signals to produce the control bus signals
required for a system which has two or more micropro-
cessors sharing the same buses. In Chapter Ii we
discuss 8086 maximum-mode operation and show its
use in multiple-microprocessor systems.
Another important pin on the 8086 is pin 21. the
RESET input. If this input is asserted and then released,
the 8086 will, no matter what it was doing. fetch its
next instruction from physical address FFFFOH. At this FIGURE 7-3 Tektronix 1230 logic analyzer. (Courtesy
address then, you put the first instruction you want of Tektronix Inc.)

168 CHAPTER SEVEN


MicroCase Inc. p. Analyst 2000 or the Bitwise Designs. memory will then represent a sequence of addresses
Inc. Logic 20. output by the 8086. As another example, you could clock
One method of connecting signal lines to the analyzer the analyzer on the RD signal from an 8086. With this
inputs is with a pod and test clips such as those shown clock signal the analyzer will take a sample each time
in front of the analyzer in Figure 7-3. Another method the 8086 does a read operation, so the samples stored
commonly used with microcomputers is a special cable in the analyzer memory will represent the sequence of
with a plug which is inserted in the microprocessor data words read in from memory or from ports.
socket on the Circuit board. The microprocessor is To make precise timing measurements with an ana-
plugged into a socket on top of the plug. lyzer, you use a clock signal from an internal. clystal-
Before we describe how to make measurements with controlled oscillator, in this case the analyzer will take
a logic analyzer, we will review the basic operation of a a sample each time a pulse from the internal clock
logic analyzer. oscillator occurs. If. for example, you choose an internal
clock frequency of 50 MHz, the analyzer will take a
Review of Logic Analyzer Operation sample every 20 ns. You can then determine the time
between two events by counting the number of samples
FIgure 7-4 shows a functional block diagram of a simple and multiplying the number by 20 ns.
logic analyzer. Since logic analyzers are used to detect If the analyzer is receiving either an internal or an
and display Only l's and Os. a comparator is put on external clock, it will be continuously taking samples of
each input. The reference input of the comparator is set the input data and storing these samples in the internal
for the logic threshold of he devices In the system you RAM. A trigger signal tells the analyzer when to stop
arc looking at. If you are looking at TTL or CMOS taking samples and display the samples stored in the
signals, for example, you set the threshold to 1.4 V. The RAM. As shown by the block diagram in Figure 7-4. you
comparators then make sure that the signals to the rest can use some external signal to trigger the analyzer, or
of the analyzer circuitry are clear-cut l's or 0's. you can use a word recogntzer in the analyzer to produce
The analyzer takes a "snapshot" of the logic levels on a trigger signal. A word recognizer compares the binaiy
the data inputs each time it receives a clock pulse. word on the input signal lines with a word you set with
The samples are stored in an internal RAM. Different switches Or a keyboard. When the two words match, the
analyzers store between 256 and 1024 samples for each word recognizer sends out a trigger sial.
input channel. Since the analyzer is continuously taking samples.
As shown by the block diagram in Figure 7-4, the you can set the analyzej for a pretrigger display. a center
analyzer can be clocked by an internally produced signal trigger display, or a posuslgger display. For an analyzer
or some external signal. II you are using an analyzer to that displays 256 samples, pretrigger means that the
look at 8086 address and data lines, for example, you display will show the 256 samples that were taken .Just
could use ALE as a clock signal. The analyzer will then before the trigger occurred. For center trigger mode. 128
take a Sample each time the 8086 puts out an address samples taken before the trigger and 128 samples taken
and pulses ALE. The samples stored in the analyzer after the trigger' will be displayed. Posttrigger mode

INTERNAL ASYNCHRONOUS CLOCK INPUT

EXTERNAL CLOCK I
INPUTS

CLK
ADJUSTABLE DISPLAY
THRESHOLD MEMORY SCAN CRT
COMPARATORS -
CIRCUIt DISPLAY

TRIGGER

WORD
COMPARATOR
AND
TRIGGER WORD TRIGGER
SELECTION CIRCUITRY
SWITCHES

EXTERNAL TRIGGER INPUT

FIGURE 7-4 Block diagram of simple logic analyzer.

6086 SYSTEM CONNECTIONS, TIMING, AND TROUBLLSHOOTING 169


31 4s,i 48 nE Cur: 'T' Ilk


• 513 Cursor 526 2,1 to Curior = •52SiS Fyi
9511 F3
-EITh'--FF1'
ITh Fm —j=
0514 FFF4 iai4 1
9515 FTF6 IA I
951 F03C Ic I
951? rolE 1
9519 1140 -_1
S519 £992 ii
9529 £898
9521 1144 itt'?
9522 FBA
0523 1148 I
0524 £944
9525 F99C PA1'I
0526 1194 I
952? F94E Ft
0528 rooe P4111___________________________________________
9529 £802 I
8539 1804 hur:) Cro,-., rII. Set Ref NtIS qe:S4,

(a)

However, a hexadecimal listing such as that in Figure


7-5a makes it easier to recognize if a microcomputer is
1022_90009 0999 ExT-ru------ putting Out addresses in the right sequence. Some
1023 00009 9000 EfT FE! analyzers, such as the Tektronix 1230. allow you to take
09195 9039 NOV OL.899 OPC FE! IN!! a series of samples from a functioning system, store
I25 95110 14ff Oil! DX.#L OPC FiT INTO
1025 99111 8411 NOV DX,IF1Z8 OPC FE! INTO these samples in a second memory in the analyzer, and
1926 09112 FF18 EXT lET INTO then compare them with a series of samples taken from
1927 0711* 8899 I/O Ill INTO a nonfunctioning system. We have found this feature
1928 09114 CFBB NOV11 CX,)! OPC FIT II4TR
OPC FE! lIlT! quite helpful in troubleshooting malfunctioning instru-
1959 09126 CIBI NOVI AL.CL
1030 00118 9124 011DB AL.ISY OPC FIT 111111 ments which have poor documentation.
1931 09114 ID? XL*T OPC lET INTO The timing diagram format shown in Figure 7-5b is
1031 00118 ED? OUT DX,OL OPC FE! INTO most useful when making time measurements with an
1932 OSIIC CIBO 804(1 4L,CL ONC ITT INTO
JIB? 99119 04)1 804) C1.,184 OFC FE! III!! internal clock. As we mentioned before, you can measure
1034 0014* 9159 NEW 2) iN!! times by simply couiiog the number of clock pulacs
1935 99129 CE'! ROLl *L,CI. OPC Ut INTO between two events and ultiplying by the time per
JI3 01118 0159 I/O 142 InTO
1037 90122 0124 ON)) OL,197 OPC FIT INTO clock pulse. Some analyzers. such as the Tektronix
1938 09124 ED? XL*T OPC 3'!! INtO 1230. allow you to determine the time between two
1038 09125 if)? OUT JILOL OPC FE.! INTO events by placing a cursor on each event and reading
the time between cursors directly on the screen.
Ic) The disassembly format shown in Figure 7-5c allows
/ you to determine if microprocessor Is fetching and
FIGURE 7-5 L6gic analyzer display formats. (a) State executing a sequence of instructions correctly. To pro-
listing showing sequences of addresses output by SDK- duce this type of display, the logic analyzer must have
86 after reset. (b) Timing diagram display showing time additional hardware and software for the specific micro-
between address output by 8086 and data output from processor that you are working with.
RAM. (C) Disassembly listing showing execution part of The following are the three major points you have to
SDK-86 display program. think about when you connect a logic analyzer up to do
a trace:

I. The data inputs of the analyzer are connected to the


means that the analyzer will take 256 more samples system signals you want displayed in the trace.
after the trigger and display them.
Figure 7-5 shows some of the formats in which a logic 2. The clock signal specified for the analyzer tells It
analyzer can display the samples stored in its RAM. The when to take data samples and store them in its
series of displayed data samples is often called a trace. memory. To produce a trace which shows the se-
quence of States that a system steps through, you
The state table list shown in Figure 7-5a is useful for
observing, for example, a sequence of addresses sent usually use an external clock. When you are using
Out or a sequence of data words read in by a microproces- an external clock, you specify the clock edge which
sor. To determine whether a particular address line is occurs when valid data is on the data inputs. For
shorted, you might tell the analyzer to display the table making timing measurements you usually use the
in binary so you can see the individual is and Os. crystal-controlled internal clock.

170 CHAPTER SEVEN


3. The trigger specified for the analyzer tells it when to MAKING A TRACE OF A SEQUENC€
stop taking samples and display the set of samples OF DATA WORDS
stored in its memory. Usually you will use the
internal word recognizer to trigger the analyzer when As a second example of using an analyzer to look at
a specified word is present on the data inputs. microcomputer signals, suppose that you want to do a
trace which shows the sequence of data wcrds read in
from memory as the 8086 executes a test program. For
Now that you have an overview of logic analyzer opera- this trace you connect the analyzer data inputs to the
tion, here are some specific examples of how you observe 8086 ADO-AD 15 pins, because the data comes in on
8086 bus signals and timing. Exercises in the lab these lines.
manual which goes with this book give still more detailed To determine what signal to clock the analyzer on and
examples. which edg, of that signal to specify, you again look
closely at the 8086 timing waveforms in Figure 7-lb.
From these waveforms you should see that the 8086 RI)
MAKING A TRACE OF A SEQUENCE signal is asserted during a Memory Read operation, so
OF ADDRESSES this is an appropriate signal to connect to the analyzer's
External Clock input. The ris.ng edge of the RI) signal
The first step in using a logic analyzer to look at occurs when valid data is on the data bus, so set the
microcomputer signals is to decide what specific signals analyzer to clock on a rising edge.
you want to look at and connect the analyzer data inputs Since you want a trace of the data words read in from
to those signals. If you want to do a trace which shows memory by the 8086, you need to look at the test
the sequence of addresses that the 8036 outputs as it program to determine what to trigger the analyzer on.
executes a test program, you connect the data Inputs of For this example, assume the simple test program shown
the analyzer pod to the 8086 ADO-AD15 pins. here Is entered In memory and run. -
The next step is to decide what signal to clock the
analyzer on. To make this decision, you look carefully 00100 EB HEREJMP HERE Endless io which does nothing
at the 8086 timing waveforms in Figure 7-lb to find a 00101 FE
signal edge which occurs when valid addresses are on 00102 90 NOP Just more wont to fetch
the ADO-ADI5 lines. One possible signal to use for 0010390 NOP
clocking the analyzer is the 8086 CL.K signal shown at 00104 04 ADD AL.55H
the top of the waveforms in Figure 7-lb. This signal has
a falling edge when the address Is valid on ADO-AD 15. Since the 8086 has a 16-bit data bus, it can read in
but it also has falling edges when the lines are floating a word (2 bytes) at a time if the word starts on an even
and when the data from or to memory is on the lines. address. When reading in the code bytes for this program
In other words, if the analyzer is clocked on this signal, then, the 8086 will send out address 0010011 and assert
the trace will show a mixture of data, addresses, and both A0 and BHE. The byte containing EBH will come
garbage. which you have to sort out. into the 8086 on ADO-AD7, and the byte containing
A better choice for an analyzer clock signal Is the 8086 FEH will come into the 8086 on AD8 .-ADl5. The first
ALE signal, because this signal is present only when data word read in from memory then is FEEBH, so this
addresses are on the ADO-AD15 lines. To use ALE as a is the word you set the analyzer to trigger on.
clock signal, connect the External Clock input of the When the trace is completed, it will show the sequence
analyzer to the 8086 ALE pin. To determine which edge of words FEEBH. 909011, ' and 045511 over and over. The
of the ALE signal to clock the analyzer on, look closely only part of this program that the 8086 executes is the
at the 8086 timing waveforms in Figure 7-lb. At the HERE:JMP HERE instruction represented by the codes
time when the positive edge of the ALE signal occurs. EBH and FEH. While the 8086 is decoding the JMP
the 8086 has not yet output the address, so clocking instruction, however, it fetches the codes for the follow.
the analyzer on this edge will not grab the addresses. ing instructions and stores them in Its queue, ready to
The falling edge of the ALE signal occurs when the be used. This is analogous to the way a helper sets up
address is solidly settled on the ADO-ADI5 lines. so you a stack of bricks for a bricklayer, so the bricklayer does
should set the analyzer to clock on the falling edge of not have to wait for the helper to go to the truck and
ALE. get each brick as needed. In this program, however, the
The final step is to determine what to trigger the JMP instruction tells the 8086 to go back and fetch the.
analyzer on. Since you want to make a trace of a sequence JMP instruction again. The words 9090H and 045511
of addresses, the logical choice here is to choose an are fetched from memory and stored in the 8086 queue.
internal trigger and set the internal word recognizer to but they are never used.
produce a trigger when the first program address is
present on the data inputs. For example, if the first
program instruction is in memory at 0010011. you would USING A CLOCK QUALIFIER IN LOGIC
set the analyzer to trigger when this address is present. ANALYZER MEASUREMENTS
When you specify the trigger position, set the anal zer In the preceding example we showed you how to produce
for "begin so that the trace listing starts with the a trace of the data words read in from memory by an
specified addre&,. The example logic analyzer trace in 8086. Now suppose that you are- executing a program
Figure 7-5a shows this type of display. which reads ata words from memory and data words
24 8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTiNG 171
Irom ports. if1u simply clock the analyzer on the rising and display lB chann.l In the timing mode which you
edge of the RD stgnalas you did (or the preceding use for this type of measurement. If you have an analyzer
example, the trace will contain both the data words read such as this, you can connect the analyzer data Inputs
from memory and the data words read from ports. You to the ADO-ADI5 pins on the 8086. The upper four
can use the MJ1O signal to produce a trace which address lines. Al6-Al9, do not change during the
Contains only the words read from memory or only the execution of this example program. so you dont need
words read from ports. to look at them.
Remember from our previous discussions that when When making timing measurements with a logic
the 8086 writes a word to a memory location or reads a analyzer. you almost always use the crystal-controlled
word from a memory location, it will assert Its M/lO internal clock to tell the analyzer to take samples so that
signal high. When the 8086 wrItes a word to port or you know the exact time between samples. For an SDK-
reads a word from a port, it wifi assert the MO signal 86 board the memory access time for the RAM that
low. contains the sample program will be around 100 ns.
To produce a trace of only the data words read from To get the best possible resolution for your timIng
ports.-you connect the RI) signal to the External Clock measurement, then, you should set the analyzer clock
Input of the analyzer and connect the MJlO signal to an period for the shortest time possibie on your analyzer.
input on the analyzer labeled Clock Qualifier. The The shortest period for the Tektronix 1230 with a 16-
principle here is that if this input Is used, the analyzer channel display is 40 ns per clock, so we will use this
will respond to a clock signal only if a specified level is setting.
present on that input. For this example, you want the To choose the trigger word for this measurement, look
analyzer to take a sample on the rising edge of the RD again at the timing waveforms in Figure 7-lb. The
if MflO is low. Therefore, you will specify a low as the address goes out on the data bus and later the data
active level for the clock qualifier input. Depending on comes back in. Since the address is the first activity,
the analyzer, the active level for the clock qualifier Input you set the word recognizer In the analyzer to trigger on
may be set in amenu. by a switch on the pod, or by the first address that Is sent out.
connecting the qualifier signal to a specific input on the Once you do a trace, you can determine the memory
data pod. access time by counting the number of sample points
To produce a trace of only the data words read from between the address of 01 OOH appearing on the bus and
memo you can clock on the rising edge of RD. connect the data word of FEEBU appearing on the bus. Figure
the MflO signal to the Clock Qualifier input, and specify 7-5b shows an example of this type of display. If your
a high for the clock qualifier. The point here Is that by analyzer has cursors, you can position one cursor at the
carefully choosing the clock signal and the qualifier time when the address becomes valid, position the other
signal, you can usually produce a trace of Just the data cursor at the time when the data becomes valid, and
you want. read the time difference between the two from the on-
screen display.
MEASURING MEMORY ACCESS TIME
Note that the resolution of this measurement is only
WITH A LOGIC ANALYZER
40 ns, because that is the time between samples. In
As shown In the 8086 timIng wavefOrms In Figure 7-lb. other words, any changes that take place between sample
one type of memory access time Is the time It takes for points will not be shown in the display until the next
a memory device to produce valid data on its outputs set of samples is taken. On many analyzers you can
after an address is applied to its address inputs. With a specify a shorter sampling period if you reduce the
little thought you can use a logic analyzer to measure number of signal lines being traced. With the Tektronix
the actual memory access time in a system. 1230. for example, you can use a sample clock with a
The first step In this measurement is toenter and run period as short as 10 ns If you can get by with sampling
a test program which reads from the desired memory only four signal lines. We usually start by doing a trace
device over and over. For this example, we will use the of, for example, all 16 lines, and then from the 16 we
same program we used in the preceding example. To choose four which show the desired transitions. With
make it easy to.refer to. we repeat it here. Just these four lines we can decrease the sample period
to 10 ns and thereby increase the resolution of our
00100 ES HERE:JMP HERE Endless mop which dom nothing measurement.
00101 FE We obviously can't describe here all the ways to use a
00102 90 NOP Just more weeds to fetch logic analyzer. If you have one, consult the manual for
0010090 NOr' it to learn some of the finer points of its use. Also, the
00104 04 ADt) AL5SH lab manual that is available (or use with this book has
some exercises to help you gain more skill with an
The next step Is to think about what signals to connect ahalyzer. The point here was to show you hOw to use
to the analyzer data Inputs. To determine the time the analyzer as a "window" Into what is going on In a
betweè, a valid address from the 8086 and valid data system. By carefully choosing the signals you look at,
from the memory drvice. you obviously need to look at the signal you clock on. and the word you trigger on.
the address/data lines. The number that you can trace you can often solve difficult problems. For this reason,
display depends on the particular analyzer you are a logic analyzer is a valuable tool when developing a new
using. The basic Tektronix 1230 analyzer will sample microcomputer-based product. -

172 CHAPTER StVEN


Now that you know how to observe and make measure- comes with 2 Kbytes of RAM and sockets where you can
ments on microcomputer bus signals, let's take a closer add another 2 Kbytes. The board also has six 8-bit
look at an 8086 system. parallel ports which you can program to be Inputs or
outputs. To get a better Idea of the hardware functions
on the board and the devices used to implement these
AN EXAMPLE MINIMUM-MODE functions, let's look at the detailed block diagram of the
SYSTEM, THE SDK-86 SDK-86 in Figure 7-7, p. 174.
Whenever you are 4pproaching a system that is new
The previous sections showed how a clock generator. to you, it is a good idea to study the detailed block
address latches, and data bus buffers are connected to diagram of the system carefully before you start digging
an 8086 to form what we might call the minimum-mode into the actual schematics. The schematics for even a
CPU group. As shown In Figure 7-la, this group of ICs small system such as this are often spread over many
generates the address bus, data bus, and control bus sages. Without the overview that the block diagram
signals needed for an 8086 minimum-mode system. In gives. it is very difficult for you to set how all the
this major section of the chapter we discuss how this schematic pieces fit together.
CPU group is connected with ROM. RAM. ports, and 'be first parts to look at In Figure 7-7 are the 8086
other devices to form a system. The system we use (or CPtI and the 8284 clock generator. Note that the 8284
this discussion is the Intel SDK-86 system design kit, has 14.7456-MHz crystal connected to it. According
an 8086-based unit suitable for building the prototypes to the data sheet for the 8284, the frequency of the
ol small microcomputer-based instruments. crystal connected to the 8284 will be divided by 3 to
Figure 7-6 shows a photograph ol an SIDK-86 board. produce the clock signal sent to the 8086. Therefore.
From the photograph you can see that, in addition to the actual 8086 clock frequency for this board will be
the microcomputer iCs. the board has a hexadecimal 4.9 15 MHz. Another clock signal called PCLK, which is
keypad, some 7-segment displays, and a large open area also produced by the 8284. has a frequency of half the
for adding more ROM. RAM. ports, or interface circuitry. clock frequency, or In this case 2.45 MHz. This signal
A monitor program in ROM on the board allows you to Is used as a general-purpose clock signal throughout
enter, execute, and debug machine code programs using the system. The hardware RST signal and the RDY
the onboard hex keypad or an external CRT terminal signal are also passed through the 8284 to synchronize
connected to the serial port on the board. The board them with the clock signal before they are sent to the

t' D T) 0
DEDrFis KEYBOARD
.EfI .-L. DISPLAY
CONTR0LLcR
n /

PARALLEL
PORTS
FIGURE 7-6 Intel SDK-86 microprocessor Oevelopment board. (Intel
Corporation).

8081, SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 173


=
oC
-
.2 C0

oE
C
. ,—'

-C
. -—

. C
•" 0

,- .
N
.
- .
o.9

-
e LI It-...

E
I/)

_c
. . •, 0
C
I I/I
.0
- - a =
' a
t- •IO

11 , C

'In CC

0 r -

174 /
8086- As you can see in Figure 7-7, considcrable circuitry are sockets for another four 2142.. The initial four
is connected to the RDY I input so that several conditions devices occupy the address space from 00000H to
can cause a WAIT state to be inserted in a machine cycle. OO7FFH. If four more 2142. are added, they will be
The structure labeled W27 through W34 above the WAIT- In the address space 00800H—OOF?FH. Another 3625
state generator in Figure 7-7 represents wire-wrap pins PROM is used here as a RAM decoder. As with the PROM
which can be jurnpered to specIf r the number of WAIT decoder, the purposes of this device are to turn on a
states desired in a machine cycle. We will discuss this memory device which corresponds to a particular ad-
in detail later. dress sent Out Ofl the address bus and to make sure that
By this time you may have noticed that the symbols only one device at a time Is outputting data on a data
for the 8284. 8086, and WAIT-state generator each have bus line. The 8086 can read or write a byte or It can
a small box containing a 2 in their lower right corner. read or write a word. Therefore, 16 data lines are
This number tells you that the detailed schematic for connected to the RAM block.
these parts will be found on sheet number two of the Now lets find the system ports In the block diagram
set of schematics. Figure 7-8 on pages 176-184 shows in Figure 7-7. Two 8255As at the top of the page
the complete schematic set for the SDK-86 board, so give the system programmable parallel ports. The term
you can check this out if you wish. programmable in this case means that, as part of your
The next parts to look for in the block diagram of the program. you send the 8255A a control byte. The control
SDK-86 are the address latches, which you know are byte tells the 8255A whether you want a particular group
needed to grab address information during Ti of a of lines on the device to function as outputs or as inputs.
machine cycle. The box Just below the 8086-in the In Chapter 9 we show you how to make up and send
diagram Indicates that three 74S373s are used for these control words. The two 8255As in this system can
address latches. ADO—ADI5, A16—A19, and BHE are be used individually to input or output parallel bytes.
connected to the inputs of these latches. As expected. They can also be used together to input or output words.
ALE is used to enable the latches. The information held For byte input or output operations, onjy ,, one of the
on the of the latches after ALE goes low is AO— devices will be turned on by asserting its CS input low.
A19 and BHE. The /20 after A0—Al9 on the output of For word input or output operations, both 8255As will
the latches indicates that there are 20 lines In this be turned on by asserting their CS inputs low. The high
group. A heavy black line is used to distinguish the byte of a word to be output, for example, will then be
demultiplexed address bus from the data bus. sent to one of the ports In the PORT I 4vice. The low
Next. follow the address lines to the right on the byte of the word to be output will go to the corresponding
diagram to find the ROM In the system. The box labeled port in the PORT 2 device. To be more specific. If the
PROM indicates that four 2316 or 276 devices are used high byte of an output word goes to port P1A. then the
for ROM in the s"stem. Each of these devices holds 2 low byte of that word will go to port P2A, In a later
I(bytes of memory. Also indicated in the PROM box in section of the chapter. we show hw the addresses work
the diagram are the absolute addresses where these out for these ports.
devices are located. Two of the EPROMs occupy the Most systems need a serial port so they can communi-
address space from FE000H to FEFFFH, and the other cate with CRT terminals, modems, and other devices
two occupy the address space from FF0001! to FFFFFH. which require data to be sent and received in serial
The 3625 PROM decoder connected to these EPROMs form. As shown in the lower left corner of Figure 7-7.
has two related purposes. The first is to produce a signal the SDK-86 uses an 8251A as a serial port. The letters
which turns on the desired ROM when you send out an USART on this device stand for universal synchronous)
address in the range assigned to that device. The second asynchronous receiver transmitter, which is quite a
purpose Is to make sure that only one device is out- mouthful. Chapter 13 discusses the Initialization and
putting signals onto the data bus at a time. We discuss use of the 8251A. For now, just think of this device
in detail later how address decoders are connected to as two back-to-back shift registers. One shift register
give a desired address to a particular device in a system. accepts a parallel byte from the system data bus and
Note that the enablepuL CS2, of the decoder PROM shifts it out the TxD output in serial form. The other
is connected to the RD signal from the 8086. This is shift register shifts in serial data from the RxD input
done so that the PROM decoder will be enabled only if and Converts It to parallel bytes which can be read by
the 8086 Is doing a read operation. Can you see why the 8086 on the system data bus. The 825 IA has only
you would not want a ROM to be turned on If you eIght data inputs, so data can only be written to or read
accidentally sent out, an address in its range during a from the 8251A a byte at a time. Therefore, only the
write operation? The answer Is that attempting to write lower 8 bits of the data bus are connected to it. Each of
to the outputs of a ROM can burn out both the ROM the shift registers in the 825 IA requires a clock signal
and the buffer outputs. The 1A26) in the PROM decoder with a frequency of 16 or 64 times the rate at which you
box of the block diagram. incidentally, indicates that want to shift data bits in or out. The clock for the
the 3625 IC will be numbered A26 on the schematic transmit shift register is called TxC, and the clock for
sheet where it is found. the receive shift register is called RxC on the block
Follow the address bus to the upper right corner of diagram. These are tied together because you usually
the block diagram in Figure 7-7 to find how RAM is want to send and receive data at the same rates. The
implemented in this system. The board comes with 2 clock for these inputs Is produced by dividing the 2.45.
Kbytes of static RAM contained in four 2142s. but there MHz PCLK signal from the 8284 clock generator. Wire-

8086 SYSTEM CONNECTiONS, 1IMlNG, AND TROUBLESHOOTING 175


7. I 6 j 5 4 1 I 2

Al -' 07
ES 07
*2 51 06
oe
A3 A2 05
05
3ZC2 *4 04
53 04

I -
AS .04 03
03 U
AS AS O2
Al
\6 10 Di o
(AS
Ag
3ZB2 AiS __________________________________________________________
-
"1

8 A??
0S JJ
9 2716
All
19 .,•
32C2 AS 18 . VPP 21
3ZA2
20
45V
12
F0000-FDFFF 7.2K AS 07
41 Al 16
15
FCO55-FCFFF I I *2 05
14
I 00-07 2ZC3
_____________ I *3 04
13
5 L - A4 03-
1Al2 — AS
5 4 3 2 A5 02
11 OS-DIS 2Z83
A13—.-.--6 Al 14 19
A14— *2 01 AS 0I C
I
Al5—..i *3
3Z82 Al6 02 13

2
Al 00
— A4 12 k5
*8 A36
All 03 22 *9 2716 5v
A5 19
1 11 CSY MO 21
*18 AS 04 18
17 CE --
OE
A19 — Al ic
2ZA3 u,i - A8 A26 - 20
15 3625 8 1/ DIS
22A3 RD *0 01 8255A
CS2 7 76 26 7
Al 06
-
CSI 6 IS 8251A 26 4
*7 05 -
5 14 8284 ¶8 9
*3 04 -
4 13 8279 46
P7 Pt A4 03
_____________________ 3 010 2116 74
A5 02
11 ¶2
2 I/O 2747 70 ¶0 B
j4j82 Cl--CS, AS 01
CS-Cl 7. C26-C26. I *1 08 18 9
C53 00 3625
* C28-C32
22, 10% j'C34C38
23
*8 8286 20 10
6 84 22 A30
ISV *9 2716 14L500 4 7
C40-052

GNO J4I1j I 9
410
IS --
CE OS
V

J20
2/ -
__J 7±ii±

74LSIO 14 7
8 1 /4LS14 14 1
A
12 lO 0/
7 16 74LS20 ¶4 7
Al 06
15 74530 - 14 7
A2 05
*3 oo 741S74 14 7
A4 74101*6 16 8
jJi2 V 3
03
II
AS 02- 74L5I64 14 7
INPUT 2
66 01 /415244 20 10 A
I 9
*INPUT 7 00 74LS393 14 7
23
*8 *3/ /445 16 8
A9 2716 40133 16
AlO 2/ '40313 20 10
-12 V IREFI 78
II 01
4 ALL DIODES 1N9148
3. ALL TRANSISTORS 0712905 -'----------___ - 20
2 ALL CAPACITANCE VALUES ARE IN 08, 80 20% , 50 V
I. ALL RESISTANCE VALUES ARE IN OHMS 5% 1/4 WATT
NOTES. UNLESS OTHERWISE SPECIFIED
FIGURE 7-8 SDK-86 complete schematics; see also pages 177-184. Sheet 11)1
9. (Intel Corporation)
176 CHAPTER SEVEN

6 4
I
5V

APIt API
22 K *75
2ZAB M/i i-?4LS1O LS4
52*3 OFF BOARD j)l2 ii 74L$
13 I, ___________ ____________
. __________ 64 62 64
• W27
64 64 1 MI
1W34
2.2 K 14.7446 MHZ
c ____ ______ 55 57 59 61 63 65 61? 691 WAIT STATE
I I SELECTOR
I C7...L
IPF_l'
LI4 J I Li1
bA 08 OC GD GE Q 00 Gui
F'''4_1: X2 14LS164
0 AS
.STM
H 1NESET RDY1
111 t iE 13
Ci8 CLA 114* INS I •sv
RPS I UP ._! EFI
2.2K T 1
osc Aii
1Z.9Z POLK 701K 8264CSVNC It -
1 -
— - API
744.S4 j A9 22K
RDY2 CLK 8__82 2
_E° W41 13 74LS20.
- ROY RST
W468 _____
15 III
5208 ______ _
7206 RESET OUT
9208 19 r'"
119
Ji
I v
2I 211 I
ROY RST CLK
A0_
4ZA7
09
______________
+5 V MN/MX AD ' , DI
AD: 07
AD 'I _________ _______________ 03
12C2, 3ZC5. 4Z05,

5ZC7, SZA2. 7ZD8,
AD 04 9ZD8
1 *21 AO 05
Rfl tR2. 74LS14. A03 11 _______ ____________ 06
NMI AD - 07
AL - ALE 3ZC5. 4ZA8
S2 Lc33
INTA "T'IUF HLD ., HLDA 3Z05.4ZA6
8 ________ _____________
AD 09
ADI 010
*01' - . IZC2.3ZB5.4Z6.
a *oi 012 SZC7.62A2
J2 it ADi; .- 013
INTR ADi-: 014
TEST ADI 015
HOLD A16/S AI8fS3'
*17/S *17/54 ' 3ZA5.4ZAO
W37J, Al6/S Al0/55 J
us *19/S A19/S8"I
• -8HE/S
34 - - )3ZA5
OHE,S1J
28 __________ _________________ - 1ZC7, 2208, 4286.
Mill) - N/b SZA7. 6Z87, 1288
- _________ _______________ h- IZB7, 4266, 5201,
8666 MC D 6287, 72C8, 9206
All
- 29
W - - 4Z68, 5Z01, 6Z87,
WA 7208, 9208
A INTA OT/r' 27 _________________________ DT/RZ86

BZA3 OFF BOARD BuFFE::: 4Z16

4282

FIGURE 7.8 (continued) Sheet 2 of 9. 8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 177

S 4 3 I 2 I

fl
09 AG l207.6ZD7,7ZC8
Dl Al 1ZDJ, 5Z07, 6ZC7, 7ZCS, 9208
02 A2 1Z07.5Z07,6ZCI
D3 A3 'I
2ZC3 1ZD7,6ZC7.7ZC8 C
04 A4 .3'
05 AS ') 14 J3
06 A6 1207, 52C8, 6ZB8. 7ZC8
Dl Al)
2283 ALE

2Z83 HLDA

08 A6
09 A g ' 1ZO7,5281,67B7,7ZC8
010 MO)
Dli All 1ZO1, 5ZB1. 6207, 7288
2Z83 012

013
Al2 ',, 1ZC7, 5Z8?, 6207, 7288 T B
Al 3)
014 A14
12C7, 5287, 6ZC7, 7ZB8
015 MS }

Al 6/53 A16
Al 7/S4 All
IZC7,5ZA7,6ZC7
2283 A18/S5 A18
Al 9/S6 A19J
BHE/S7 ii 1Z07. 6207, 7ZCB
/
I A

FIGURE 78 (continued) Sheet 3 of 9.

wrap jumper pins. W19-W25. allow you to select the time per bit Is 416 s. for example, then the baud rate
desired TxC and RxC frequency from a divider chain in Is 2400 baud. Common baud rates for serial data
the 74LS393 baud rate generator. Baud rate is a way transmission are 300. 600, 1200. 2400. 9600, and
of specifying the rate at which data bits are shifted in 19,200.
or out of a serial device. Baud rate for a device such as The final port device to discuss here Is the 8279 in
the 825 IA is defined as I over the time per bit. lithe the bottom center of the SDK-86 block diagram (Figure

1 78 CHAPTER SEVEN

4 3 2
5 I I.

J2
808
Dl
—.-.-1A6 101
Dl
02 -1 A5 IS 102
1A4 141 103
0 03
2ZC3 104
04
SOS
D5
Dl 5DB
07 507

Al
.12
2^A3 BUFFER ON ii
12 508
08 lB
Dl J—ID9
BIl
019
Dli 24 B011
2ZB3 28 B012
012
D13 28 8013
014 Al I 5014
Al 32 BDIS
015
•5 V 1 8288
- Al

9 A25
ã 5Z87

.14
BMIO
(O BRO/
I RD BWR/
2ZA3'
DEN !.I Al 48 BDEN/
OuR 9A1

3I9
ULOA 2Z58
74L514
- 2A3 1Y3 44 BHLOA
- 2Z03 13 2A2 22 Se BALE J3
17 - 2A4 3 8$NTAI
2ZC3 INTA 2v4
1AI lvi 18 - 8S3
(Ai6/S3
1A2 i'7 16 - 954
2ZB3 ' AI71S4
I A18/S5 \A3 1Y3 14 - 8S5
1A4 1v4
A8 9
A - i 2A1 211 -
A8
16 26 74LS244
11 1
FIGURE 7-8 (continued) Sheet 4 of 9.

and turns on that digit. The process is continued until


7-7). The 8279 is a specialized tnputloutput device all digits have been lit, and then the 8279 cycles back
which has two major functions. The first function is to
to the first digit again. In Chapter 9 we discuss in detail
scan the hex keypad. detect when a key is pressed. is that
debounce the signal from a pressed key. and store the how you use an 8279. The main point for now
this device takes care of scanning a keyboard and
code for the pressed key in an Internal RAM. where it
refreshing a display so that you don't have to do these
can be read by the 8086. The second major function of
operations as part of your program.
the 8279 is to refresh the multiplexed display on the
eight 7-segment LED displays. Seven-segment codes for Now that you have an overview of the ports in this
the
the digits lobe disp'ayed are sent to a RAM in the 8279. system. see if you can find in the block diagram
decoder which selects an addressed port. You should
The 8279 then automatically sends out the code for one the center
digit and turns on that digit. After a millisecond or so. find the 3625 PROM labeled (A22) about in
of the block diagram. Later we discuss how this
device
the 8279 sends out the 7-segment code for the next digit

8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 179


2&

7 6 S 3

J6 J6
2ZC8 RESET OUT P1A036
RESET o
PIA1 40
(RD
6—
WR
1 2 2 P1A2 4
3

7ZD2 HIGH POATSEL 6 P1A344


A2 PA340 P1A4 0

9A0 I.. Al
f PtA5
39 P1A642
7Z02 LOW PORT SEL 637 13
P1A7
015 27 07 14
26 17
014 2806 0 15 P1C1 24
19
013 D5
1
1116
217
P1C2 22

21
04 pica
2ZB3 012 20 23
011 313 Pc 13 P1C4 28
25
010 32 12 PiGS
02 28 27
09 Dl P1C6 32
I 6 P1C7
29
08 34D0 31
07 18 l'0 16
33
D6 19 P191 12
05 1 20 P182 C
04 2 21 P183
22C3 PB 22 P194 6
28
03 41
02 23 RIBS 10
43
DI 8255A P166 14
A35 6 24 4
00 25 P187
+5 V

iS i5
RESET 4 P2AO

AS P2A1 28
3ZC2' A6 -0
113 P22 42
5
A7 8 P2A3
A8 PA1340 P2A4
A9 539 P2AS
AlO P2A640
13 B
All 27 07 1 62837 P2A7
3282
Al2 2806 14 P2CO 24
17
A13
A14
1
1 15
PIC1 2
19
P2C2 4
2 16 21
A15 31 03 J 17 P2C3 6
23
02 PC 13 P2C4 26
25
4ZB2 01 12 P2C5 28
27
34 P2C6
oa 29
Al2 I 6 10 P2C7 32
31
A13 18 P280
A14 0 19 P281 22
1 35
A15 20 P292
3ZB2 2 21 P283 14
A16 39
A17 PB 22 P284 16
41
A18 23 P285 20 A
43
A19 8255A 24 P286 12
A40 45
2ZA3 M/R 25 P287
7

4- OFF BOARD 2ZA8, 2Z08


74 LS 14
IIGURE 7-8 (continued) Sheet 5 ol 9.

180 CHAPTER SEVEN


4 S I 2
7 S I I I

3Zc2 Al
3ZA2 BUE
All
Al2
A13
A14
3Z02 A15
A16
A17
AIB
A19
C

Al
A2
A3
3Z2 A4
- A5
Al
Al

3ZB2 Al
All
AC
B 2ZA34
I_ u,ic

oil
Dl.
Dl
2Z13
014
013
012
07
Dl
Dl
04 2ZC3
A 03
02
DI
0S

FIGURE 7-8 (continued) Sheet 6 of 9.

8016 SYSTEM CONNECTIONS. TIMING, AND TROUBLESHOOTING . 181


C)

01 UI 4O0uJi&Q 0
-_.1 00000000 0000000 0

U >
- I__i, (I'
30300000

* -
61

'I

1!E

a,
0

=
C
0
U

-
U UI U U P C


N Q
I'-
C U
]

182
0 V I

ci

)
. *

0U

_3O0O0 ___________
U-
183
1]1 [
!
•-

I- -U
x ,c )C )C

L
ed - - -
)- ,- - >.
- .- =
- - (_)

:i+
__'

-4f-1i ____________

-ri

-44----

_1

4
V

.-
• m

_J C,

—o----
I o
-ow---- am.
p____

• I p.s,
- ,- Ca

C-

Ca
_______________________

184
produces the port select signals from a port address sent upper left corner of the component side of a board. There
out by the 8086. may be several 2716s on the board, but only one will be
The final parts of the SDK-86 block diagram to take a labeled A36.
look at are the buffers along the tight-hand edge. The Inadditlon to ICs. another type of device often found
purpose of these devices is to buffer the data and control on microprocessor boards is a resistor pack. You can
bus lines so that they can drive additional ROM, RAM. find an example in zone CS of schematic sheet 1. As you
or ports that you might add to the expansion area of the can see from the schematic, this device contains foui-
board. Note that the address lines are already buffered 2.2-kfl resistors. Resistor packs may physically be thin.
by the 74S373 address latches. vertical, rectangular wafers, or they may be in packages
simIlar to small ICs. The advantages of resistor packs
are that they take up less printed-clrct.it-board space
A First Look at the SDK-86 Schematics and that they are easier to install than individual
Now that you have seen an overview of the SDK-86. the resistors.
next step is to take a first look at Figure 7-8, which Some other symbols to look at in the schematics are
shows the actual schematics for the board. At first the the structures with labels such as J2 and P1. You can
many pages of schematics may seem overwhelming to find examples of these In zones C7 and B7 of schematic
you, but if you use the 5'mlnutefreak-out rule and then sheet 1. These symbols are used to indicate connectors.
approach the schematics one part at a time, you should The number in the rectangular box specifies the pin
have no trouble understanding them. The schematics number on the connector that a signal goes to. The
simply show greater detail for each of the parts of letter P stands for plug. A connector is consIdered a plug
the block diagram that we discussed in the preceding If it plugs into something else. In the case of the SDK.
sections of the chapter. 86, the connector labeled Pits the printed-circuit-board
At this point we want to make clear that it is not the edge connector. The letter J next to a connector stands
purpose of this chapter to make you an expert on the forjack. A connector is considered a jack if something
circuit connections of an SDK-86 board. We use parts of else plugs into it. On the SDK-86 board the jacksJl
these schematics to demonstrate some major concepts. through J6 are 50-pin connectors that you can plug
such as address decoding, and to show how the parts ribbon cable connectors into. These jacks allow the
are connected tog.ther to form a small but real system. address bus, data bus, control bus, and parallel ports
Even if you do not have an SDK-86 board, you can learn to be connected to additional clrcuitly.
a great deal from these schematics about how an 8086 One more point to notice on the SDK-86 schematics
system functions. Multlpage schematics such as these Is the capacitors on the power supply Inputs shown in
are typical for any microprocessor-based board or prod- zone B6 of sheet 1. A(it you can see there, the schematic
uct, so you need to get used to working with them. shows a large number of 0. 1-p.F capacitors in parallel
Before getting started on the next major concept, we with a 22-F capacitor. Most systems haveJlltering such
will discuss some of the symbols commonly used on as this on their power lines. You may wonder what is
microprocessor system schematics. First, take a look at the use of putting all these small capacitors In parallel
the numbers across the top and bottom of each sche- with one which is obviously many times larger. The
niatic and the letters along the sides of each. These are point of this is that the large capacitor filters out, or
ca1le zone coordinates, You use these coordinates to bypasses, low-frequency noise on the power lines, and
identi the location of a part or connection on the the small capacitors, spread around the board. bypas
schelPa. just as you might use similar coordinates on high-frequency noise on the power supply lines. Noise is
a ro,ur'ap to help you locate Bowers Avenue. For produced on the power supply lines by devices switching
exan. on sheet I of the schematics, find the lines from one logic state to another. If this noise is not
labelA I through A7 in the upper left corner. Next to filtered out with bypass capacitors, It may become great
the' .ines you should see 3ZC2. This indicates that enough to disturb system operation.
thc address lines come from zone C2 on sheet 3. To Glance through the SDK-86 schematics to get an idea
see what the lines actually connect to. first find sche- of where various parts are located and to see what
rustic sheet 3. Then move across the row of theschemat Ic additional information you can pick up from the notes
libeled C until you come to the column labeled 2. ThIs on them. In the next Section of this chapter. we discuss
zone is small enough that you should easily be able to how microcomputer systems address memory and ports.
find where these lines come from. The zone coordinates As part of the discussion, we cycle back to these schemat-
next to these lines on sheet 3 indicate the othesche- ics to see how the SDK-86 does it.
matle sheets and zones that these lines go to. For
practice. try finding where a few more lines connect Addressing Memo'y and Ports
from and to. in Microcomputer Systems
The next points to look at on the schematics are the
numbers on the ICs. in addition to a part number such
as 2716. each IC has a number of the form A36. This ADDRESS DECODER CONCEPT
second number is used to help locate the IC on the While discussing the block diagram of the SDK-86 board
printed circuit board. The number is commonly silk- earlier in this chapter, we mentioned that the 3625
screened on the board next to the corresponding IC, devices on the board serve as address decoders. One
Usually IC numbers are sequential and start from the function of an address decoder Is to produce a signal
8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 185
Al2
Do
*13
*14 DATA
BUS

Dl
A15

RD

+5 V
- 74LS138

FIGURE 7-9 Parallel ROMs with decoder.

which enables the ROM. RAM, or port device that you If the 74LS 138 is enabled by making its G2A and G2B
want enabled for a particular address. A second, related inputs low and its Gi input high, then only one output
function of an address decoder is to make sure that only of the device will be low at a time. The output that wlU
one device at a time is enabled to put data on the data be low Is detennijied by the 3-bit address applied to the
bus lines. C, B, and A select 'iputs. For exampfr, if CBA i 000.
It seems that every microcomputer system does ad- then the YO output will be low, and all the other outputs
dress decoding in a different way from every other will be high. This wlU assert the CS input of ROM 0. If
system. Therefore. instead of memorizing the method CBA is 001. the Yl output will be low and the ROM I
used In one particular system, it is important that you will be selected. If CBA is 1 11. then Y7 will be low, and
understand the concept of address decoding. You can only ROM 7 wIll be enabled. Now let's see what address
then figure out any system you have to work on. range these connections on the 74LS 138 wIll give each
of these ROMs in the system.
AN EXAMPLE ROM DECODER To determine the addresses of ROMs. RAMs, and ports
To start, look at Figure 7-9. This figure shows how eight in a system, a good approach in many cases is to use a
EPROMs can be connected in parallel on a common worksheet such as that in Figure 7-10. To make one of
address bus and common data bus. Just by looking at these worksheets, you start by writIng the address bits
the schematic you can see that these EPROMs output and the binary weight of each address bit across the top
bytes of data because each has eight outputs connected of the paper, as shown in the figure. To make it easier
to the system data bus. The number of address lines to convert binary addresses to hex, it helps if you mark
connected to each devie gives you an Indication of how off the address lines In groups of four, as shown. Next.
many bytes are stored ft it. Each EPROM has 12 address draw vertical lines which mark off the three address
lines lAO—Al I) connected to it. Therefore, the number lines that connect to the decoder select inputs (C. B.
of bytes stored In the device is 22 or 4096. If you have and A). For the decoder in Figure 7-9. address lines A14.
trouble with this, think of how many bits a Counter has Al.3. and Al2 are connected to the C, B. and A inputs
to have to Count the 4096 States from 0 to 4095 decimal, of the decoder, respectively. Then write under each
or 0000N to OFFFH. address bit the logic level that must be on that line to
Note that each 2732 in Figure 79 has a Chip Select. address the first location in the first EPROM.
CS. input. When this input Is asserted low, the addressed To address the first location in any of the EPROMs.
byte in a device will be output on the data bus. The the A0 through All address lines must all below, so put
74LS 138 in Figure 7-9 makes sure that the CS input of a 0 under each of these address bits on the worksheet. To
only one ROM device at a time is low. enable EPROM 0, the select inputs of the decoder must

186 CHAPTER SEVEN


HEX DIGIT HEX DIGIT HEX DIGIT :1 HEX DIGIT


HEX
2" 2" 2° 2" 2" 2" 2' 2' 2' 2' 2' 2' 2' ' 2' 2° EQUIVALENT
Al5 A14 A13 Al2 All AlO AS AS *7 *6 A5 *4 *3 *2 Al A0 ADDRESS
BLOCKISTART 0 0 ' 0 0 0 0 0 0 0 0 0 0 0 0 0000
1 lEND 0 0 - - 1 1 1 1 1 1 1 1 1 1 1 OFFF
BLOCKSTART 00 00 0 0 0 0 0 0 0 0 0 0 -1000
2END 0 0 - - -- 1 11 1 1 1 1 .1 11 1FFF -
BLOCK START 001 0 0 0 0 0 0 0 0 0 0 0 0 2
3 END 0 0 I 0 1 I 1 1 1 1 1 1 1 1 •2FFF
BLOCKJSTART 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 -3000
4 lEND 0 0 1 1 1 1 1 1 1 1 1 1 1 1 3FFF
BLOCKSTART 01 0 00 0 000 0 0 0 0 0 0 •4000
END 0 1 0 1 1 1 I 1 1 1 1 1 1 -4FFF
BLOCK START 0 1 1 00 0 0 000 0 0 0 0 0 -5000
8 END 0 1 1 1 1 1 1 1 1 1 1 •SFFF
BLOCKSTART 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 '6000
?END 0 1 0 1 1 11 1 1 1 1 1 1 1 -BFFF
BLOCK START 0 - Il 1 00 0 0 0 0 0 0 0 0 0 0 7000
8 END 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -7FFF

DECODER
ADO RESS
INPUTS

FIGURE 7-10 Address decoder worksheet showing address decoding for eight
2732s in Figure 7-9.

be all 0's. Since address lines A14, Al3. and Al2 are blocks of memory. If you think of the address lines as
connected to these select Inputs, they must then all be the outputs of a 16-bit Counter, you can see how this
0's to enable EPROM 0. WrIte a 0 under each of these works. The end address for each EPROM has all l's in
address bits on the worksheet. Since address line A 15 address bits A0—A1 1. When you increment the address
is connected to the G2A enable input of the decoder, it to access the next byte In memory, these bits all go to
must be asserted low in order for the decoder to work 0, and a 1 rolls over into bits A14, A13. and Al2. This
at all. Write a0under the A15 bit on your worksheet. increments the count in these 3 bits by 1 and enables
Note that the RD signal from the microprocessor control the next highest 4096-byte EPROM. The count In these
bus is connected to the 02B enable input of the decoder. bits goes from binary 000 to ill.
The decoder then will only be enabled during a read
operation. This Is done to make sure that data cannot AN EXAMPLE RAM DECODER
accidentally be written to ROM. The 01 enable input of The system in Figure 7-9 contains only ROM. In most
the decoder is permanently asserted by tying it to + 5 V systems, you want to have ROM. RAM, and ports. To
because we don't need it for anything else in this circuit, give you more practice with basic address decoding, we
You can now read the starting address of EPROM 0 will show you now how you can add a decoder for RAM
directly from the woyksheet as 0000H. The highest to the system.
address In EPROM O,is that address where A0—Al I are Suppose that you want to add eight 2K x 8 RAMs to
all l's. If you put a I under each of these bits as shown the system, and you want the first RAM to start at
on the worksheet, you can see that the ending address address 8000H. just above the EPROMs, which end at
for EPROM 0 is OFFFH. Remember that Al2—Al4 have address 7FFFH.
to be low to select EPROM 0. A 15 has to be low to enable To start, make a worksheet similar to the one in Figure
the decoder. The addres, range of EPROM 0 is said to 7-10. Addressing one of the 2048 bytes (2") in each
be 0000H to OFFFH. a 4-Kbyte .b4ock. RAM requires II address lines. A0 through AlO. These
Now let's use the worksheet 'to determine the address lines will be connected directly to the address inputs on
range for EPROM 1. EPROM 1 is enabled when Al5 is each RAM, so draw a vertical line on the worksheet to
0. Al4 is 0. Al3 Is 0, and Al2Ia I. For the first address indicate this.
in EPROM I, address lines A0 through Al Imust all be The three address lines All, Al2. and Al3 will be
low. Therefore, the starting address of EPROM 1 Is used to select one of the eight RAMS, so write a 3-bit
10001-I. Its ending address, when AO through All are binary count sequence under these three columns In
all l's. Is IFFFH. If you look at the worksheet In Figure your worksheet.
7-10. you should see that the address ranges for the We want the RAM to Start at address 8000H. For this
other six EPROMs In the system are 2000H to 2FFFH, address, Al5 isa I and Al4 isa 0, so mark these values
3000H to 3FFFH, 4000H to 4FTflI, 5000H to 5FFFH. in the appropriate columns in your worksheet. Your
6000H to 6FFFH. and 7C)0H to 7FFFH. In this system, completed worksheet should look like the one In Figure
then, we use address lines A14, A13, and Al2 to select 7-I Ia. p. 188. Now, let's see how you can implement
one of eight EPROMs in the overall address range of this truth table with hardware.
00001-I to 7FFFH. Some people like to think of address Since you want to select one of eight RAM devices, you
lines Al4. Al3. and Al2 as "counting off" 4096-byte can use another 74L.S 138 such as the one we used lot'

- 26 6086 SYSTEM CONNECTIONS. TIMING. AND TROL)BLESHOOTINC 187


HEX DIGIT - -- HEX DIGIT HEX DIGIT HEX DIGIT HEX START
EQUIVALENT OF
A15 A14 A13 Al2 All AlO A9 A8 Al A6 AS A4 A3 A2 Al A0 - ADDRESS BLOCK
1 0 0 0 C 00 0 0 0 0 0 0 0 0 8000H
1 0 0 0 1 0 0 0 0 C 0 0 0 0 0 0 B800H 2
1 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 =9000H 3
1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 =980011 4
1 0 1 0 0 0 0 0 0 0 0 j 0 0 0 0 "AOOOH 5
1 0 1 0 I 0 0 0 0 0 0 0 0 0 0 0 =ABOOH 6
1 0 I 1 0 0 0 0 0 0 0 0 0 0 C 0 BOOOH 7
I 0 I 1 1 0 D 0 0 0 0 0 0 0 0 0 B80OH B

DECODER
ADDRESS
INPUTS
(a)

Out the hexadecimal addresses for each of the other


seven RAMs. Vhen you finish, compare your results
with those in Figure 7-1 la. The eight RAMs occupy the
A15 G1
address space from 80001-I to BFFFH.
31:>-.-
26____.I ENABLE
I SIGNALS
A14 11j RAM
5I DEVICES
FOR
AN EXAMPLE PORT DECODER

6 Figure 7-1 2a shows how another 74LS 138 can be con-


j nected in a system to produce chip select signals br
some port devices. The truth table or address decoder
worksheet in Figure 7-12b shows the system address
which corresponds to each of the decoder outputs.
First, note that A15 and A14 must be hIgh to enable
A13 Al2 All
the decoder, so these bits are l's in the worksheet. Then
(b) notice that A13 and Al2 must be low to enable the
decoder, so these columns on the worksheet contain 0's.
FIGURE 7-11 Address decoder. (a) Worksheet for eight
Finally, address lines A3, A4, and A5 are connected to
2-Kbyte RAMS starting at address 8000H. (b) Schematic
the decoder select inputs, so we wrote a 3-bit binary
for 74LS138 connections.
count sequence in these columns in the worksheet.
Address lines A0, Al, and A2 will be connected directly
to the port devices to address individual ports and
the EPROMs. You want to select 2048-byte blocks of control registers in the devices. This is the same idea
memory, so address line All will be connected to the A as connecting the lower address lines directly to' ROM
input of the decoder, Al2 will be connected to the B so that we can address one of the bytes stored there.
input of the decoder, and A13 will be connected to the Address lines A6 through All are not connected to
C input of the decoder. the port devices or to the decoder, so they have no effect
You want the block of RAM selected by the outputs of on selecting a port. We don't care then whether these
this decoder to start at address 8000H. For this, address bits are l's or 0's. As you will see, these "don't care" bits
A15 is high and A14 is low. The 01 enable input of the mean that there are many addresses whIch will turn on
decoder Is active high. so yo connect it to the A15 one of the port devices, To give the simplest address for
address line. This input will then be asserted when A15 each device, however, we assume that each of these
is high. You connect the A14 address line to the G2A don't care bits is 0. Write 0's under each of these bits
input of the decoder so that this Input will be asserted on your worksheet. You should now see that the address
when A14 is low. Because you don't need to use it in C000H will cause the Y0 output of the decoder to be
this circuit, you can simply tie the G2B input of the asserted. The address COO8H will cause the Y 1 output
decoder to ground o that it will be asserted all the time. of the decoder to be asserted, Using address lines A3.
Figure 7-1 lb shows the connections for this decoder. A4, and A5 on the decoder select inputs, then, leaves
Note that you don't cnnect the 8086 RD signal to an eight address spaces for each port device.
enable input on a RAM decoder, because you want to To see that any one of several different addresses can
enable the RAMs for both read and write operations. select one of these port devices, replace the 0 you put
From the worksheet or truth table in Figure 7-I la. under A6 on the first line of your worksheet with a 1.
you can quickly determine the address range for each This represents a system address of CO4OH. A15 and
of the RAMs. The first RAM will Start at address 8000H. A14 are l's and A13, Al2, A5, A4, and A3 are Os for
The ending address for this RAM will be at the address this address. Therefore, this address will also cause the
where bits A0—Al0 are all l's. If you put l's under these Y0 output of the decoder to be asserted. You can try
bits on your worksheet, you should see that the ending other combinations of l's and Os on A6 through All if
address for the first EU\M is 87FFH. For practice, work you need to further convince yourself that these bits

188 CHAPTER SEVEN


74LS1 38 HEX
HEX HEX HEX HEX
74LS08 vo DIGIT DIGIT DIGIT DIGIT PORT DEVICE
A15 15A14A13Al2 A11AIO A A? A6 AS A4 A3 A2 Al AO ADDRESS
A14 OH N H H 88000 000 C 000
001 C 008
SIGNALS 010 C 010
FOR 01 1 C 018
A13 i PORT
DEVICES 100 C 020
101 CO 28
110 CO 30
Al 2 1 I 0 OlB B N N H H 111 CO 38

DtCODER
SELECT
A5 A4 A3 INPUTS
(i lot

FIGURE 7-12 Adding a port device decoder. (a) Schematic for 741.5138
connections. (b) Address decoder worksheet.

dont matter when addressing ports. Again, we usually stored byte. As you know from previous chapters. when
use 0's for these bits to give the simplest address. you write a word to memory with an instruction such
Using a decoder which translates memory addresses as MOV DS:WORI) rrRt43m11}.BX. the word is actually
to chip select signals for port devices Is called memorr4- written into two consecutive memory addresses. Asum-
mapped I/O. In this system a port will be written to or ing that DS contains 0000. the low byte of the word is
read from in the same way as any other memory location. written Into the specified memory address. 0437A}1, nd
In other words, If this were an 8088 system, you would the high byte of the word Is written Into the next-higher
use an instruction such as MOV AL.DS:BYTE PTR address. 0437BH. To make it possible to read or write
00000H to read a byte of data from the first port to the a word with one machine cycle, the memory for an 8086
AL register Instead of using the MOV DX.00000H and is set up as two "banks" of up to 524,288 bytes each.
IN AL.DX Instructions. The advantage of memory- Figure 713a, p. 190, shows this in diagram form.
mapped 1/0 Is that any Instruction which references One memory bank contains all the bytes which have
memory can be used to input data from or output data even addresses such as 00000, 00002. and 00004. The
to ports. In a system such as this, for example, the single data lines of this bank are connected to the lower eight
Instruction ADD AL,DS:I3YTE VtROCOOOHJ could be data lines. DO through D7. of the 8O8. The other
used to input a byte of data from the port at address memory bank Contains all the bytes which have odd
C000H and add the byte to the AL register. The disadvan- addresses such as 00001. 00003. and 00005. The data
tage of memory-mapped 110 is that some of the system lines of this bank are connected to the upper eight data
memory address space is used up for ports and is lines. D8 through Dl5, of the 8086. Address line AO Is
therefore not available for memory. used as part of the enabling for memory devices In the
You can use memory-mapped 1/0 with any micropro- lower bank. An addressed memory device In this bank
cessor. but some microprocessors, such as those of the will be enabled when address line AD Is low, as it will be
8086 family, allow you to setup separate address spaces for any even address. Address lines Al through A19 are
for input ports and for output ports. You access ports used to select the desired memory device in the bank
In these separat address spaces dircctTy with (he IN and to address the desired byte in that device.
and OUT instructions. Having separate address spaces Address lines Al through A19 are also used to select
[or input and output ports Is called direct I/O. The a desired memory device In the upper bank and to
advantage uf direct [/Ois that none of the system memory address the desired byte in that bank. An additional
space is used for ports. The disadvantage Is that Only part of the enabling for memory devices In the u_2p.r
the specialized IN and OUT Instructions can be used to bank is a separate signal called bus high enable. BHE.
Input or output data. BHE is multlpiexed out from the 8086 on a signal line
in a later section of this chapter. we show how direct at the same time as an address is sent out. An external
I/O is done with the 8086, but first we will discuss how latch. strobcd by ALE, grabs the BIlE signal and holds
the 8086 addresses memory. It stable for the rest of the machine cycle. Just as is done
with addresses. Figure 7-13b shows you the logic level
that will be on the BHE and AO lines for different types
8086 and 8088 Addressing of memory accesses.
and Address Decoding If you read a b y te [ronl or Write a byte to an even
address such as 00000Ff. AO will be low and BHE will
8086 MEMORY BANKS
be higF. The lower bank will be enabled, and the upper
The 8086 has a 2Oblt address bus, so it can address bank will be disabled. A byte will be transferred to or
2° or 1.048,576 addresses. Each address represents a from the addressed location in the low bank on DO-

8086 SYSTEM CONNECTIONS. TIMING, AND TROUBLESHOOTING '189


UPPER BANI- LOWER BANK-


ODD ADDRESSED EVEN ADDRESSED
8086A BYTES BYTES
FFFFEH

00002
00000H

I.)

DATA -
ADDRESS TYPE BUS DATA
______ CYCLES LINES USED
0000 BYTE 1 0 ONE 00-07
0000 WORD 0 0 ONE DO-015
0001 BYTE 0 1 ONE 07-015
0001 WORD 0 I FIRST 00-07
1 0 SECOND 07-015

Ib)
FIGURE 7-13 8086 memory banks. (a) Block diagram. (b) Signals (or byte and
word operations.

07. For an instruction such as MOV AH.DS:BYTE enabled. The byte will be transferred from memory
PTRI0000I. the 8086 will automatically transfer the byte address 0000IH in the high bank to the 8086 on lines
of data from the lower data bus lines to AH. the upper 08-0 15. The 8086 will automatIcally transfer the byte
byte of the AX register. You Just write the instruction of data from the higher eight data lines to AL. the low
and the 8086 takes care of getting the data in the right byte of the AX register. Note that address 0000IH Is
place. actually the first location in the upper bank.
Now. if the OS register contains 0000H and you use The final case in Figure 7-13b Is the one where you
an instruct ion such as MOV AX,DS:WORX) PTRI0000I want to read a word Irom or write a word to an
to read a word from memory into AX, both A0 and BHE odd address, The instruction MOV AX.DS:W0RD
will be asserted low. Therefore, both banks will be PTRI000IHI copies the low byte of a word from address
enabled. The low byte of the word will be transferred 00001 to AL and the high byte from address 00002H to
from address 00000H to the 8086 on 00-07. The high AN. In this case, the 8086 requires two machine cycles
byte of the word will be transferred from address 00001 H to copy the two bytes from memory. During the first
to the 8086 on 08-015. The 8086 memory, remember. machin , cle the 8086 will output address 0000lH,
is set up in banks so that words: which have their low assert RHE low, and assert A0 high. The byte from
byte at an even address, can be transferred to or from address 0000)H will be read into the 8086 on lines 08-
the 8086 in one bus cycie. When programming an 8086. Dl5 and put in AL. During the second machine cycle
then, It is important to start an array of words on an the 8086 will send out address 00002H. Since this is
even address for most efficient operation. If you are an even address, A0 will be low. However, Since we are
using an assembler, the EVEN directive is used to do accessing Only a byte. HHE will be high. The second byte
this. will be read into the 8086 on lines 00-07 and put in
When you use an Instruction such as MOV AL.DS AH. Note that the 8086 automatically takes care of
BYTE P1'RJOOOl Ito access Just a byte at an odd address. gettIng a byte to the correct register regardless of which
A0 will be high and BHE will be asserted low. Therefore. data lines the byte comes in on.
the low bank will be disabled, and the high bank will be The main reason that the A0 and BIlE signals function

190 CHAPTER SEVEN


the way they do is to prevent the writing of an unwanted In the system. you need to look next at the 3625 address
byte into an adjacent memory location when the 8086 decoder labeled A26 on sheet 1 of Figure 7-8.
writes a byte. To understand this, think what would A 3625 isa 1K x 4 bipolar PROM which functions as
happen if both memory banks were turned on for all ah address decoder, just as the 74LS 138 performs In
write operations and you wrote a byte to address 00002 Figures 7-9 and 7-11. Since a 3625 has open collector
with the instruction MOV DS:BYrE PTR!00021.AL. The outputs, a pull-up resistor to + 5 V is required on each
data from AL would be written to address 00002 as output. The dotted box around the four resistors on the
desired. However, if the upper bank were also enabled, schematic indicates the four are all contained In one
the random data on D8—D15 would be written into package, resistor pack 5 (RP5). The 3625 translates an
address 00003. Since the 8086 is designed so that BHE address to a signal which is used as part of the enabling
Is high during this byte write. theupper bank of memory of the desired device. Using a PROM as an address
is not enabled. This prevents the random data on D8— decoder, however, is for several reasons much more
D15 from being written to address 00003. powerful than using a simple decoder such as the
Now that you have an overview of address decoding 74LS 138. In the first place. the 3625 is programmable.
and of the 8086 memory banks, let's look at some which means that you can move the memory devices to
examples of how all this is put together in a small new addresses in memory by simply programming a new
system. PROM. Second. the large number of inputs on the PROM
allows you to select a specific area of memory without
using external gates. If. for example, you wanted the
ROM ADDRESS DECODING ON THE SDK-86 G2A input ofa 74LS138 to be asserted ifAl 1—A15 were
Sheet 1 of the SDK-86 schematics in Figure 7-8 shows all high. you would have to use an external NAND gate
the circuit connections for the EPROMs and EPROM to detect this condition. With a PROM, you can just
decoder. The 2716 EPROMs there are 2K x 8 devices. make this condition part of the truth table you use to
Two of the EPROMs have their eight data outputs burn the PROM.
connected in parallel to system data lines D0—D7. These Now, to analyze any address decoder circuit, first
two EPROMs then give 4 Kbytes of storage in the lower determine what signals are required to enable the de-
memory bank. The other two EPROMs have their data coder. The CS 1 enable input of the 3625 EPROM decoder
outputs connected in parallel to system data lines D8— is tied to ground. so it is permanently enabled. The CS2
D15 to give 4 Kbytes of storage in the upper bank of enable input is tied to the RD signal 1ron the 8086. so
ROM. that the decoder will only be enabled if the 8086 is doing
Eleven address lines arc needed to address the 2 a read operation. As explained previously, you don't
Kbytes in each device. Therefore, system address lines want to accidentally enable a ROM if you send out a
Al—All are connected to all the EPROMs in parallel. wrong address during a write operation.
Remember that A0 cannot be used to select a byte in The next step in analyzing a decoder circuit using a
the EPROMs because, as we described in the last section, PROM is to consult the manufacturer's manual for the
it is used to enable or disable the lower bank. system. You have to do this because, for a PROM, the
A 2716 has two enable inputs. CE and OE. In order relationship between the inputs and the outputs cannot
for the 2716 to output an addressed byte, both of these be determined directly from the schematic.
enable inputs must be asserted low. The CE inputs of Figure 7-14 shows the truth table for the PROM
the two devices In the lower bank are connected to from the SDK-86 manual. This truth table is just a
system address line A0, so the CE iflputs of these devices compressed form of writing an address decoder work-
will be asserted II A0 is low. The CE inputs of the two sheet such as those we used in the previous discussion
2716sin the upper bank are connected to the BE-IE line. of address decoding. From the truth table you can see
The CE irrni,is of these devices then will be asserted that in order for the 01 output of the 3625 to be asserted
whenever BHE is asserted low. To summarize, then, the low. M/I0 has to be high. This is reasonable, since this
two devices labeled A27 and A36 form the lower bank of decoder is enabling memory devices, not port devices.
EPROMs and the two devices labeled A30 and A37 form Also, address lines Al2 through A19 have to be high in
the , per bank of EPROMs in this system. To see how order for the 01 output of the PROM to be asserted low.
the OE enable input of each of these devices gets asserted Since the upper eight address bits must all be Fs for
and to determine the address that each device will have the 01 output lobe asserted, the lowest address which

PROM INPUTS
______________________ PROM
- OUTPUTS
I A14-A19 A13 I Al2
PROM ADDRESS
01 BLOCK SELECTED
M/IO 04 03 02
1 1 I 1 1 1 1 0 FFXIOH-FFFFFU
1 I 1 I o 1 1 0 I FEOU.FEFErH
1 I I I I 1 0 1 1 FDON-FDEFFH ICSXI
I 0 0 0 1 I I FCOH-FCFFFH ICSYI
ALLOTHEA STATES 1 1 1 I NONE

FIGURE 7-14 Truth table for an SDK . BE. ROM decoder PROM lATh).

808A SYSTEM CONNICTIONS. TIMING, AND TROUBLESHOOTING 191


will cause this is IT000H. If you refer to sheet I of the address inputs. AO—A9. indIcates that each one stores
SL'K-86 schematics in Figure 7-8, you will see that the 2' or 1024 of these 4-bit words. To store bytes, two
01 output of the decoder PROM connects to the OE 21 42s are enabled in parallel. Devices A38 and A4 1, for
enable puts of two of the 2716 EPROMs. A27 and A30. example. are enabled together to store bytes from the
These OE outputs then will be enabled whenever the lower .clght data lines, and devices A43 and A45 are
8086 sends Out an address In the range of FF000H to enabled together to store bytes from the upper ei,gt
FFFFFH. To fully enable these devices, however, their data lines. Note next that the control bus signals RD.
CE Inputs must also be asserted. WR. and M.'lO are connected to all the 2142s. RD is
The CE input of the A27 EPROM is connected to connected to the output disable. OD. pin on the 2l42s.
system address line A0, so this device will be enabled When the RD signal is high or when the device Is not
whenever the 8086 does a memory read from an even enabled, the output buffers will be disabled. During a
address lAO = Olin the range FF000H to FFFFEH. read operation the RD signal is asserted 'ow. Yf a 2142
The CE enable input of A30 is connected to the system is enabled and Its OD input is low, the output buffers
BHE line. As shown in Figure 7-13. BHE will be asserted will be turned on so that an addressed word is output
low whenever the 8086 accesses a byte at an odd address onto the data bus.
or a word at an even address. Therefore, the A30 EPROM WR from the 8086 is connected to the write enable.
will be enabled when the 8086 reads a byte from an odd WE. input of the 2142s. If a 2142 is enabled, data on
address in the range FF000H to FFFFFH. A30 will also the data bus will bcwritten into the addressed location
be enabled when the 8086 asserts both AO and BHE low in the RAM when the 8086 asserts WR low,
to read a word that starts on an even address in the The 2142s have two enable inputs, CS! and CS2.
range FF000H to FFFFFI-I. The M/lO signal from the 8086 is connected to the CS2
Note in Figure 7-14 and the first sheet of Figure 7-8 Input of all the 2142s. Since the CS2 Input Is active
that the 02 Output of the 3625 decoder PROM will be high, it will be asserted whenever the 8086 Is doing a
asserted for addresses in the range of FE000}-1 to memory operation. The CS 1 inputs of the 21 42s are
FEFFFH. This signal is used as part of the enabling for connected in pairs to the outputs of a 3625 PROM which
the A36 and A37 EPROMS. AO and BHE provide the rest functions as an address decoder.
of the enabling for these devices. Just as we described In order to assert any of its outputs and enable some
previously for A27 and A30 devices. For practice, trace RAM, the 3625 must itself be enabled. Since the CS2
these signals on the first sheet of Figure 7-8. enable input of the 3625 PROM is tied to ground, it is
Also note In the first sheet of Figure 7-8 that the 3625 permanently enabled. The CSI enable input will be
ROM decoder has two unused outputs which can be asserted when system address line A19 is . 10w. To
used as part of the enabling for EPROMs you add to the determine any more information about this PROM. you
prototyping section of the board. As shown In Figure 7- need to look at the truth table for the device. Before we
14, the address ranges for these two outputs are FD000H go on to that, however, note that AO and BHE are
to FDFFFH and FC000H to FCFFFH. connected to two of the address inputs on the 3625
The four SDK-86 EPROMs actually contain two moni- PROM. Knowing what you do about 8086 memory banks,
tor programs. One monitor, in devices A27 and A30. why do you think we want AO and BHE to be part of
allows you to use the hex keypad for entering and what determines the outputs for this decoder? If you
running programs. The other monitor, in devices A36 don't have the answer to this question, a look at the
and A37. allows you to use an external CR1 terminal to truth table for the device in Figure 7-15 should help
enter and run programs. The EPROMs are put at this you.
high address In memory on the SDK-86 board because. According to the third line of the truth tabl&address
after a RESET, the 8086 goes to address FFFFOH to get decoder worksheet in Figure 7-15, the 01 output of the
Its first instruction. Since we want the SDK-86 to execute PROM will be asserted low if At2 through A18 are low.
its monitor program after we press the RESET button. All is low, 8HE is high. and A0 is low. The 01 output
we locate the EPROM containing the monitor program then will be asserted for even system addresses starting
such that this address is In it. You can interchange the with 00000H. A low on the Dl output will enable the
actual EPROM devices so that either the keypad monitor A38 and A4 I RAMs, which are connected to the lower
or the serial monitor executes when you press the half of the data bus. These two devices are part of the
RESET button. lower bank of RAM.
Next, look at the second line of the PROM truth table
RAM ADDRESS DECODING ON THE SDK-86 in Figure 7-15. From this line you should see that the
To give you another example of memory address decod- 02 output of the PROM will be asserted low if Al2
ing in a real system, we now discuss the RAM decoding through Al8 are low, All Is low. BHE is low, and A0 is
of the SDK-86 board. Sheet 6 of the SDK-86 schematics high. The 02 output will then be asserted for odd system
in FIgure 7-8 shows the circuit for the system RAM and addresses starting with 000IH. A lox on the 02 output
RA.M decoder. Let's look at this schemattc to see what will enable the A43 and A4.5 RAIvls. which are connected
we can learn from it. on the upper half of the data bus. These two devices are
First, take a look at the input and output lines on the part of the upper hank of RAM.
2142 static RAM devices. From the fact that each device Now, suppose we want to write a 16-hit word to RAM
has four data 110 lines, you can conclude that the devices at an even address. To do this, we want both 01 and
store 4-bit words, 'the fact that each device has 10 02 to be asserted low so that both the lowcr-barik RAMs

192 CHAPTER SEVEN


PROM INPUTS PROM OUTPUTS


______ - - - - - - - BYTE(S) SELECTED
A0 04 01 (ADDRESS BLOCK)
Al2-A18 All 03 02
O 0 0 0 1 1 0 0 BOTH BYTES (OH-O7FFH)
o 0 0 1 1 0 1 HIGH BYTE (0I-4-OJFFH)
o 0 1 0 1 1 1 0 LOWBYTE(OH-O7FFNI
o l 0 0 0 0 I 1 BOTH BYTES 08H-OFFFH)
o 1 0 1 0 1 1 1 HIGH BYTE IO8HOFFFI.4)
o 1 0 1 0 1 I LOWBYTEIO800H-OFFFHI
ALLOTHERSTATES 1 1 I 1 NONE

FIGURE 7-15 Truth table for an SDK-86 RAM decoder PROM (A29).

and the upper-bank RAMs are enabled. According to the output operations, the 16-bit port address Is first loaded
first line of the PROM truth table In Figure 7-15, 01 and into the DX register with an instruction such as MOV
02 wIll both he asserted low if BHE and AO are both low. DX.OFFF8H. The Instruction IN AL,DX is then used to
Remember from Figure 7-13 that BHE and AO will both copy a byte from port FFF8H to the AL register. MOV
be low whenever you write a word to an even address or DX,0038H followed by IN AL.DX has the same effect as
read a word from an even address. This last case gives IN AL,38H.
the answer to the question we asked earlier about why Whenever the 8086 executes an IN or OUT instruction
A0 and BHE are connected to the address decoder PROM to access a port, none of the segment registers are
Inputs. The two Inputs are required to tell the PROM Involved in producing the physical address sent Out by
decoder to assert both 01 and 02 for a word read or the 8086. The port address Is sent out directly from the
write operation. 8086 on lines ADO—ADI5. and 0's are output on lines
The address range for the A38, A41, A43, and A45 A16-Al9.
RAMs is 000001-i to OO7FFH. Another look at the PROM In an 8086 system which uses direct I/O, the M/lO
truth table in Figure 7-15 should show you that RAMS signal Is used to enable a memory decoder or a port
A39, A42, A44. and A46 Contain 2 Kbvtes more In the decoder. Remember that the MJIO signal being high was
range 00800H to OOFFFH. Again, both banks of this one of the enabling conditions for the SDK-86 ROM and
additional RAM will be enabled If A0 and BHE are both RAM decoders we discussed in previous sections. As you
low, as they are for reading or writing a word to an even wIll see, a low on MJ1O Is used to enable a port decoder.
address, During the execution of an (N instruction, the RD
signal from the 8086 will be low, This signal can be
SDK-86 PORT ADDRESSING used to enable an addressed input port device. During
AND PORT DECODING execution of an OUT instruction the WR signal from the
In a previous section ol this chapter we described 8086 will be low. This signal can be used to enable an
memory-mapped inpuUoutput. In a system with memo- addressed output port device. Since the 8086 outputs
ry-mapped 110, port devices are addressed and selected up to a 16-bit address for direct 110 operations. It can
by decoders as If they were memory devices. The main address any one of 2' or 65.536 input ports and any
advantage of memory-mapped I/O Is that any Instruction one of 65.536 output ports.
which refers to memory can theoretically be used to read For an example of how direct I/O ports are addressed
from or write to a port. Thc single Instruction A1)D and sclectedin a real s ystem, we will again look at the
BH,DS BYTE PTRI437AIII could be used to read a byte SDK-86 schematics In Figure 7-8. sheet 7. Here another
from a memory-mapped port and add the byte read In 3625 PROM. A22, Is used to produce the chip select
to the BH register. The disadvantage of men.ary-rnapped signals for four I/O devices. The 01 output of the PROM
110 Is that the ports occupy part of the system memory Is used to enable the 8279 kevboardidisplay interface
space. This space Is then not available for storing data device, which we discuss in a section of Chapter 9. The
or instructions. 02 output of the PROM Is used to enable the 825 IA
To avoid having to use part of the system memory USART shown on sheet 9 of the schematics. The 825 IA
space for ports, 8086 family microprocessors have a allows communication with other systems in serial form.
separate address space for ports. Having a separate A Section in Chapter 14 discusses the operation of this
address space for ports is called direct I/O because this device. The 03 arid 04 outputs are connected to two
separate address space Is accessed directly with the IN 8255A parallel port des ices, shown on sheet 5 of the
and the OUI Instructions. schematics. These devices can be eoabled individually
Remember from previous chapters that the 8086 IN to Input or output bytes. The y can also be enabled
and OUT instructions each have two forms.Jtxed port together to input or output words A section iii Chapter
arid variable port. For fixed-port instructions, an 8-bit 9 shows you how to tell eac port in these devices
port address is written as part of the instruction. The whether you want it to be an in it or an output.
instruction IN AL,38H, for example, copies a byte from Take a look now .ii the i'25 . idcr PROM to deter-
port 38H to the AL register. For variable-port input or mine what conrtilion' cii ii shoub bud that

Sf186 SSsTEM CONNtCTIONS, T).',tl'-,C \[) -':')LP ',HOOTINi 193


PROM INPUTS PROM OUTPUTS __________ -


04 03 02 01
A11-A15 A5-A1O A4 A3 AO HIGH PORT SELECT LOW PORT SELECT USART SELECT KOSEL
1 1 0 1 0 0 1 1 1 0
1 1 0 1 1 0 1 1 1 0
1 1 1 0 0 0 1 1 0
1 I 1 0 I 0 1 1 0 I
1 I 1 1 0 0 0 0 1 I
1 I 1 1 0 1 0 1 1 1
1 1 1 10 1 0 1 1
ALLOTHER STATES I 1 1 1

fi

Ib

FIGURE 7-16 Truth table and map for SDK-06 port decoder. (a) Truth table. (b) Map.

the CS2 enable input of the PROM will be asserted when selects one Internal address. and Al high selects the
M/lO Is low, as it is during an input or put operation. other Internal address. Al low gives system address
Furthermore, you should see that the CS! input will be FFE8H. and Al high gives system address FFEAH. These
asserted when All to A15 are all high. Now, to see are then the two addresses for the 8279 in this system.
what addresses cause each of the PROM outputs to be According to the truth table in Figure 7-16a. the 02
asserted, refer to thc truth table for the PROM in Figure output ol the decoder PROM will be asserted low when
7!6a. From this figure you can see that to assert the A4 through A15 arc high and A3 and AO arc low. BIlE
01 output low. A5 through A15 have to be high. A4has can be either low or high. but, since only the lower eight
to below. A3 has to be high, and A0 has to be low. I3HE data lines are connected to the 825 IA USART, data must
can be either high or low. Note, however, that only the be sent to or read from the device as bytes at an even
lower eight data lines. DO—D7. are connected to the address. Again, system address line Al is used to select
8279. Therefore, data must be Sent to or read from one of two internal addresses in the 825 IA (Figure 7-8.
the 8279 at an even byte address. In other words, data sheet 9). Al low selects one internal address and Al
must be sent as a byte to an even address or as the lower high selects the other internal address. Therefore, the
byte of a word to an even address. two system addresses for this device arc FFFOU and
The system base address for this device then is FFE8H. FFF2I-f.
System address line Al is connected to the 8279 to select Now, before discussing the 03 and 04 outputs of the
one of two internal addresses in the device. Al low decodcr PROM. we will take a brief look at the two 8255

194 CHAPTER SEVEN


parallel port devices they enable. These devices are of the data bus at the same time. When the 8086 on an
shown on sheet 5 of the schematics In Figure 7-8. Each SDK-86 board execut,ts the instructIon sequence MOV
of these devices contains three 8-bit parallel ports and DX,FFF8H—lN AX.DX. both A0 and BHE will be low
a control register. System address lines Al and A2 are during the IN instruction. As shown by the fifth line in
used to address the desired port or register in the device. the truth table, this will cause both the 03 and the 04
Just as lower address lines are used to address the outputs of the port decoder to be low. These signals will
desired internal location In a memory device. Note that enable both the A40 and A35 port devices. The byte of
the lower eight data lines. DO—D7. are connected to the data on port 2A will be input to the 8086 on the lower
A40 device, and the upper eight data lines are connected half of the data bus, arid the byte of data on port LA will
to the A35 device. This is done so that you have several be input to the 8086 on the upper half of the data bus.
input or output possibilities. You can read a byte from Note in the truth table in Figure 7-16a that the 3625
or write a byte to an even-addressed port in device A40. PROM decoder will enable a port device only when the
You can read a byte from or write a byte to an odd- specific address assigned to that device is sent out by
addressed port in device A35. You can read a word from the 8086. This is sometimes called comp fete decoding
or write a word to a 16-bit port made up from an 8-bit because all the address lines play a part in selecting a
port from device A40 and an 8-bit port from device A35. device and one of its internal ports or registers. As we
To input or output a word, both devices have to be show In Chapter 8. adding another decoder to produce
enabled. Now let's look at the decoder truth table to enable signals for more port devices is very easy In a
determine what addresses enable the various ports in system which uses this complete decoding.
these devices.
The A40 device will be enabled by the 03 output of THE SDK-86 "OFF-BOARD" DECODER
the 3625 decoder PROM if address lines A3 through A 15 Take a look at the off-board clrcuitrlj in zone AS on sheet
are high and A0 Is low. Al and A2 are used to select 5 of the SDK-86 schematics. The purpose of this circuitry
internal ports of the 8255A. Let's assume that these two is to produce the signal OFF BOARD whenever the 8086
bits are 0 for the first address in the device. To select sends out a memory or port address which does not
the A port in the A40 8255A. address lines Al and A2 correspond to a device decoded on the board, The 'F
have to be low. The system address that will enable this I3OARD signal will be asserted low if pin 4 of the A3
device and select the A port within it is FFF8H. Other NAND gate is low or if pin 5 of the A3 NAND gate is low,
values of A2 and Al will select one of the other ports or According to the truth table for the Al2 PROM in Figure
the control register in this device. Figure 7-16b shows 7-17. the 01 output will be low if the 8086 is doing a
the system addresses for the ports and control register memory operation and the address sent Out is not in
in this 8255. Note that the ports in this device (A40) are one of the ranges decoded for the onboard RAM or ROM.
identified as port 2A, port 2B. and port 2C. These all In order for pin 4 of the A3 NAND gate to be low, both
have even addresses because AO must be low for this pin 9 and pin 10 of the A3 NAND gate must be high.
device to be selected. Pin 10 will be high if the 8086 is doing an Input or
The A35 8255A, which contains port IA. port lB. and output operation llO/M from the 8286 inverting buffer
port IC, will be enabled by the 04 output of the decoder equals I). Pin 9 of the A3 NAND gate will be high if any
PROM if A3 through A15 are high and the BHE line is one of the A19 NAND gate inputs is low. Since system
low. If this 8255A is being enabled for a byte read or address lines A5 through A15 are connected to the
write, then the A0 Line will also be high. A2 and Al are Inputs of the 74LS 133 NAND gate. the signal to pin 9
again used to address one of the ports or the control of A3 will be high for any address less than FFEOH. in
register within the 8255A. A2 0 and Al = I will select other words, pin 4 of the A3 NAND gate will be asserted
port IA in this 8255A. As shown in Figure 7-I6b. then. low for any i/O operation in an address range not selected
the system address for port IA is FFF9H. Port lB will by the A22 port decoder.
be accessed with asystem address of FFFBH. port IC The OFF BOARD signal produced by the previously
will be accessed with a system address of FFFIDH. and discussed PROM and logic gates Is connected to an input
the internal control register will be accessed with a of a NANE) gate labeled A2 on sheet2of the schematics.
system address of FFFFH. If OFF BOARD is asserted low, or INTA Is asserted low.
As we said before. (he 8086 can input a 16-bit value or 1-ILIJA is asserted low, the output of this gate will be
in one operation by enabling a port device on the lower high. For now, all we are Interested in is the fact that If
hail of the data bus and a port device on the upper half OFF BOARD Is asserted low, a high will be applied to

PROM INPUTS PROM OUTPUT CORRESPONDING


(01) ADDRESS BLOCK
M/iO I A19 AlS I 417! A161 415! A14 I A13 1412
1 I i I Io o 0 0 I 0 1 (INACTIVE) ON-OFFFH ON-BOARD RAM)
I I
1 IiIiI I 1 1 1 I 1 (INACTIVE) FE000H-FEFFFH (ON-BOARD PROM)
1 1 1 I 1 1 1 I 1 I (INACTIVE) FF000H-FFFFFH ON-BOARD PROM)
ALL OTHER STATES 0 (ACTIVE) O1000H-FDFFFH (OFF-BOARD)

FIGURE 7-17 SDX-86 oU . board decoder PROM truth table.

- 27 80& SYSTEM CONNECTIONS. TIMING. AND TROUBLESHOOTING 195


pin 1 of the A3 NAND gate in zone A4 of the schematic. the RDYI lnp't will be asserted low if all three inputs
if the DEN signal from the 8086 is also asserted low the of the Al .5 NAND gate shown In zone D5o1 the schematic
signal labeled BUFFER ON will be as,serted low. The DEN are high. Pin 10 of this device Is tied to +5 V. so it is
signal from the 8086 will be asserted whenever the 8086 permanently high. Pin 11 of Al5 will be high if any of
reads in data from a memory location or a port or when the inputs of the NAND gate in zone D7 are asserted
it writes data to a memory location or a port. The low. Pin I of gate AIS will be low whenever the 8086
BUFFER ON signal produced here is used to enable the does an input or output operation. Pin 2 of gate AI5
8286 data bus buffers (A6 and A7) shown on sheet 4 of will be low whenever the 8086 accesses a port or memory
the schematics. Now here's the point of all this. location which is not decoded on the board. In other
In the next chapter we show you how to add another words, with these connections, the selected number of
I/O decoder and some other devices to the prototyping WAIT states will be inserted In each machine cycle when
area of an SDK-86 board. To drive these additional the 8086 does a read from or a write to an on-board 110
devices, the address, data, and control buses must all device or when the 8086 does a read from or a write to
be buffered. The address bus on the SDK-86 board is any device not decoded on the board. If jumper W39 is
buffered by the 74S373 address latches shown on sheet installed on pin 13 of AlS, pin II of A15 will always be
3 of the schematics. Data bus and control bus buffers high. The number of WAIT states selected by the W27—
are not needed to drive the ROM, RAM, and port devices W34 jumpers will be inserted for all read and write
that come with the SDK-86 board. To read data from or operations.
write data to external devices, however, the data bus Is The desired number of WAIT states to be inserted is
buffered by two 8286s. shown as A7 and A6 on sheet 4 selected by putting a jumper between two pins in the
of the SDK-86 schematics, These two buffers are turned W27—W34 matrix shown In zone D3 (sheet 2) of the
on when the BUFFER ON signal, described in the schematic. If ajumper is Installed in the W27 position.
preceding paragraph, is asserted low. The 8286 buffers for example, no WAIT states will be inserted. If a jumper
are bidirectional. When these buffers are enabled, the is installed in the W28 position, one WAIT state will be
Data Transmit/Receive signal, DT/R. from the 8086 will inserted. The pattern continues to Jumper W34, which
determine in which direction the buffers are pointed. If will cause seven WAIT states to be inserted in each
IYF/R Is high, the buffers will be enabled to write data machine cycle. Here's how the WAIT-state generator
to some external device. II DT/R is low, the buffers will itself works.
be enabled to read data In from some external device. The 74LS164 WAIT-state generator is an 8-bit shift
The control bus signals are buffered by an 8286 labeled register. At the start of a machine Cycle, the RI). WR.
All and a 74LS244 labeled AS on sheet 4 of the SDK- and INTA signals from the 8086 are all high. These three
86 schematics. These buffers are permanently enabled signals being high will cause the A2 NAND gate in zone
to send Out the control bus signals except during a C4 to assert the clear input, CLR. of the shift register.
HOLD state, which we will explain later. The outputs of the shift register will then all below. One
of these lows will be coupled through a jumper and an
THE SDK-86 WAIT-STATE GENERATOR CIRCUITRY inverter to pin 9 of the A15 NAND gate we discussed
Now that you know how the OFF BOARD signal is previously. This high on pin 9. together with a high on
produced on the SDK-86 board, we can explain the pin 11, will cause the RDYI input of the 8284 to be
operation of the WAIT-stale generator circuitry shown pulled low. However, WAIT states will not be inserted
on sheet 2 of the schematics. unless RDYI remains low long enough. Now. whenR.D.
In a previous section of the chapter we showed you WR. or INTA goes low In the machine cycle, the CLR
that if the RDY input of the 8086 is asserted low, the input of the 74LS 164 shift register will go high, and the
8086 will Insert one or more WAIT States in the machine shift register will lunction normally. The highs on the
cycle it is currently executing. Figure 7-lb shows how a INA and INB inputs will be loaded Onto the QA output
WAIT state is inserted in an 8086 machine cycle. During on the next positive edge of the clock. If th WAIT-state
a WAIT state, the information on the buses is held jumper Is in the W27 position, then this high on the QA
constant. The stgnal levels on the buses at the start of output will, through the inverter and NAND gate, cause
the WAIT State remain there throughout the WAIT state. the RDYI input of the 8284 to go high again. For thIs
The main purpose of Inserting one or more WAIT states case, the RDYI input goes high soon enough that no
in a machine cycle is to give an addressed memory device WAIT states are inserted.
or 1,0 device more time to accept or output data. In the The high loaded into the 74LS164 shift register is
next major sectionf the chapter, we show you how to shifted one stage to the right by each successive clock
determine whether a WAIT s t ate is needed for a given pulse. When the high reaches the juniper connected to
device with a given 8086 clock frequency. For now. the A25 inverter, it will cause the RDYI Input of the
however, lets just see how the circuitry on the SDK-86 8284 to go high. The 8086 will then exit from a WAIT
board causes the 8086 to insert a selected number of state on the next clock pulse. The number of WAIT States
WAIT states. inserted in a machine cycle is determined by how many
WAIT states are inserted by pulling the RDYI Input of stages the high has to be shifted before it reaches the
the 8284 clock generator IC low (Figure 7-8. sheet 2. installed jumper.
zone D51. The 8284 internally synchronizes the RDY1 To summarize all this, the 8086 will insert the selected
input signal with the clock signal and sends the resultant number of WAIT states in any machine cycle which
signal to the ROY input of the 8086. For the SDK-86. accesses any device not addressed on the board or any

196 CHAPTER S€V[N


I/O device on the board. If jumper W39 is Inserted, the facturers' data books give detailed timing waveforms
selected number of WAIT states Will be inserted for any and lists of timing pa.-ameters for each microprocessor.
onboard or off-board access. The purpose of inserting Complete timing information for the 8086 is contained
WAIT states is to give (he addressed devIce more time in the data sheet in Appendix A. Figure 7-19. pp. 198-9,
to accept or output data. shows some timing waveforms and parameters for an
8086 minimum-mode read machine cycle.
As you look at Figure 7-19a, remember the 5-minute
How the 8088 MicroprOcessor freak-out rule. Most of the time there are only a very few
Accesses Memory and Ports of these parameters that you need to wony about. In
most systems. for example. you don't need to worry
Now that we have shown in detail how the 8086 accesses
about the clock signal parameters. because an 8284
memory and port devices, we can show you how the
clock generator and a crystal will be used to produce the
8088 does it. clock signal. The frequency of the clock signal from an
In Chapter 2 we mentioned that the 8088 is the CPU
8284 is always one-third the resonant frequency of
used in the original IBM PC and the IEIM PC/XT. The
the crystal connected to it. The 8284 is designed to
instruction set of the 8088 is identical to that of the
guarantee the correct clock period, clock time low, clock
8086. and the registers of the two are the same, but
time high. etc. - as long as the correct suffix number part
there are two major differences between the two devices.
is used. The 8284A, for example, can be used in an
First, the 8088 Instruction byte queue Is only 4 bytes
8-MHz system. but a faster part. the 8284A-1, must be
long instead of 6. Second, and more important. the 8088
used for a system where a 10-MHz clock is desired.
memory is not divided into two banks as the 8086
The edges of the clock signal cause operations in the
memory is: it consists of a single bank of up to 1.048.576
8086 to occur: therefore, as you can see in Figure
bytes, as shown in Figure 7-18.
7-19a. the clock waveform Is used as a reference for
As you can see, the 8088 has only an 8-bit data bus.
other times, The timing values for when the 8086
DO—D7. All the memory devices and ports in an 8088
puts out MJlO. addresses, ALE, and control signals, for
system are connected onto these eight lines. Addrcsa
example, are all specified with reference to an appro-
lines A0 through AI are used with some decoders to
priate clock edge.
select a desired byte in memory. The 8088 does not
As we mentioned earlier, o of the main things you
produce the BHE signal because it is not needed, This
use these diagrams and parameters for is to find out
single bank structure means that an 8088 can read or
whether a particular memory or port device is fast
write Only a byte at a time. Therefore, art 8088 must
enough to work in a system with a gIven clock frequency.
always do two machine cycles to read or write a word.
Here's an example of how you do this.
The 8088 was designed with an 8-bit data bus so that
If you look in zone C5 of sheet 2 of the SDK-86
it would interface more easily with 8-bit memory devices
hematics. you will see that if Jumper W4 1 is installed.
and i/O devices.
the 8086 will receive a 4,9-MHz clock signal from the
8284. If jumper W40 is installed, the 8086 will receive
8086 Timing Parameters the 2.45-MHz PCLK signal from the 8284. Now, suppose
that you want to determine whether the 2716 EPROMs
In previous sections of this chapter. we used generalized on the SDK-86 board will rk correctly with no WAIT
timing waveforms such as that in Figure 7-lb. These states If you install jumper W4 1 to run the 8086 with
diagrams are sufficient to show the sequence of activities the 4.9-MHz clock.
on the 8086 buses. However, they are not detailed First, you look up the access times for the 2716
enough to determine, for example, whether a memory EPROM in the appropriate data book. According to an
device is fast enough to work In a given 8086 system Intel data book, the 2716 has a maximum address to
To allow you to make precise timing calculations, man output access time, t, of 450 ns. This means that if
the 2716 Is already enabled and its output buffers are
turned on. it will put valid data on its outputs no more
ADDRESS
than 450 ns after an address is applied to the address

Li
FFFFFH inputs. The 2716 data sheet also gives a chip enable to
output access time, t, of 450 ns. This means that If
an address is already present on the address inputs of
the 2716 and the output buffers are already enabled.
the 2716 will put valid data on its outputs no later than
450 ns after the CE input is asserted low. A third
00003 H
parameter given for the 2716 in the data book Is an
00002 H
output enable to output time, t 0 . of 120 ns maximum.
00001 H
This means that if the device already has an address on
C0000H ItS address inputs, and its CE input is already asserted.
valid data will appear on the output pins at most 120
ns after the OE pin is asserted low.
Now that you have these three parameters for the
FIGURE 7-18 8088 memory structure. 2716. the next step is to check whether each one of

&18 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 197


M(NIMUM MODE

CLX (8264A OUTPUT(

M/IO

j /s7 AJS-A/S

ALE

ROY (8284A INPUT(


SEE NOTE 4

READY (8086 INPUT) {

I AD-AD0

AD
READ CYCLE
(NOTE II
(WR,INTAV0 ,I -
DT/R

DEN

FIGURE 7-19 8086 minimum-mode timing waveforms and parameters. (a) Read
waveforms. (See also next page.)

these times is short enough for the device to work with Now took further to the right on the ADI5-ADO lines,
a 4.9-MHz 8086. In other words, does the 2716 put Out You should see that valid data must arrive at the 8086
valid data soon enough after it is addressed and enabled from memory a time TDVCL before the failing edge of
to satisfy the requirements of the 8086? To determine the clock at the end of T 3 . TDVCL stands for time data
this, you need to look at both the 8086 timing parameters must be valid before clock goes low. The data sheet
and how the 2716 is addressed and enabled on the SDK- gives a value of 30 ns for this parameter.
86 board. The time between the end of the TCLAV interval and
To make it easier for you to find the important the start of the TDVCL interval is the time available for
parameters for these calculations, we show in Figure getting the address to the memory and for the tM of
7l9b a simplified version of the timing diagram in the memory device. You can determine this time by
Figure 7-19a. You should try to do this simplification subtracting TCLAV and TDVCL from the time for three
mentally whenever you are faced with a timing diagram. clock cycles. With a 4.9-MHz clock, each clock cycle
As shown by the timing ,, agram in Figure 7-19b. the will be 204 ns. Three clock cycles then total 612 os.
8086 sends Out MIlO. BI-IE. and an address during T Subtracting a TCLAV of 110 ns and a TDVCL of 30 ns
of the machine cycle. Note on the AD 15—ADO lines of the leaves 472 ns available for getting the address to the
timing diagram that the 8086 outputs this information 2716 and for its t- To help you visualize these times.
within a time labeled TCLAV after the failing edge ol the Figure 7-20a. p. 200, shows this operation in simplified
clock at the start of T TCLAV stands for ttme from diagram form.
clock low to address valid. According to the 8086 If you look at sheets I and3of the SDK-86 schematics,
column of the data sheet shown in Figure 7l9c. the you should see that the BHE signal and the A0—Al I
maximum value of this time is 110 ns. address information go from the 8086 through the

198 CHAPTER SEVEN


CLK )8284A OUTPUT)

M.'IO

A19S6-A16/53

ALE

AD 1 5—ADO

RD

DT/ R

DEN

(b)

MINIMUM COMPLEXITY SYSTEM TIMING REQUIREMENTS


8086 8086-1 )PreIinjnary) 8086-2
SYMBOL PARAMETER UNITS
MN. MA*, MIN. MAX. MIN. MAX.
TCLCL CLK Cycle Period 200 500 100 500 125 500 n
TOVCL Dt in SetUP Time 30 5 20
TCLAV Addrex VImd DeIy 10 110 10 50 10 60 nx
TCLRL Active DoIy 10 165 10 70 10 100 ox
NOTE: Complete tinting infomnmation itt Appendix
(C)

FIGURE 7-1 (continued) (b) Simplified read waveforms. (c) Timing


parameters. (Intel Corporation)

74S373 latches to get to the 2716s. The propagation ECE of the 2716 is 450 ns, you know that this parameter
delay of the 74S373s then must be subtracted from the is also acceptable for an SDK-86 operating with a 4.9-
472 ns to determine how much time is actually available MHz clock.
for the t of the 2716. The maximum delay of a 74S373 The final parameter to check Is t 0 of the 2716.
is 12 ns. As shown in Figure 7-20a. subtracting this According to sheet 1 of the SDK-86 schematics, the OE
from the 472 ns leaves 460 ns for the t of the 2716. signals for the 2716s are produced by the 3625 decoder.
Now, as we told you in a previous paragraph, the 2716 The signals comg to this decoder are Al2 through
has a maximum t . qf 450 ns. Since 450 ns is less than A19, MIlO. and RD. Look at the 8086 timing diagram
the 460 ns available, you know that the t of the 2716 in Figure 7-19b to see if you can determine which of
is acceptable for the SDK86 operating with a 4.9-MHz these signals arrives last at the 3625. You should find
clock. You still, however. must check if the values of tc that addresses and MJlO are sent out during T,. but RD
and t 0 for the 2716 are acceptable. is not sent >ut until T.As indicated by the arrow from
If you look at sheet I of the SDK-86 schematics, you the falling edge of the RD signal, RD going low causes
should see that the CE inputs of the 27 16s are connected the address decoder to send an OE signal to the 2716
either to AU or to L3HE. The timing for these signals is EPROMs. Since RD Is sent out so much later than
the same as that for the addresses in the preceding addresses, it will be the limiting factor for timing. RD
section. As shown in Figure 7-20a. the time available going low and the EPROM returning valid data must
for ke of the 2716 will be 460 ns. Since the maximum occur within the time of states T 2 and T Now, according

8086 SYSTEM CONNECTIONS, TI'.IINC, AND TROUBLESHOOTING 199


to the timing diagram. RD is sent out from the 8086
within a time TCLRL after the falling edge of the (lock
at the start of T 2 . From the data sheet, the maximin1
value of TCLRL is 165 Os. As we discussed before, the
L.2.L' LL±i
8086 requires that valid data arrive on ADO through ICLAV ItO,,I 1P0141J') 2.,. rDVcL
AD 15 from memory a time TDVCL before the falling edge TIME AVAILABLE FOP 2116
*006605 ACCESS TIMF -
of the clock at the end of T. The minimum value of Pr?,, - lS2, 4jJ
TDVCL from the data sheet is 30 ns. The time between
1
the end of the TCLRL interval and the start of the TDVCL
Interval is the time available for the OE signal to be
produced and for the OF signal to turn on the memory.
To determine the actual time available for these opera-
tions, first compute the time for states T 2 and T. For a
4.9-MHz clock, each clock cycle or state will be 204 rts,
so the two together total 408 ns. Then subtract the ICLAL = ISA,, 1P031525 30,, , TDVCL - 30,9

TCLRL of 165 ns and the TDVCL of 30 Cs. As shown by TIME AVAILABLE 106 2716
22•_ 03,9
the simple diagram in Figure 72Ob, this leaves 213 ns
(Al
available for the decoder delay and the tOE of the 2716.
Checking a data sheet for the 3625 would show you that fIGURE 7-20 Calculations of maximum allowable access
It has a maximum CS2 to output delay of 30 ns. Subtract times for 4.9-MHz 8086. (a) Time for tACO and 1611 . ( b)
this from the available 213 ns to see how much time is Time for t112;.
left for the t, of the 2716. The result of this subtraction
Is 183 ns.
As we Indicated in a previous paragraph, the 2716
has a maximum t 0 of 120 ns. Since this time is enough time to compensate for the buffer delay, so the
considerably less than the 183 ns available, the 2716 added 2716s will work correctiy.
has an acceptable t<IE value for operating on he SDK-86
board with a 4.9-MHz clock.
All three times for the 2716 are less than those
required by the 8086 for 5-MHz operation, so you know TROUBLESHOOTING A SIMPLE 8086-
that the devices will work correctly at 4.9 MHz without BASED MICROCOMPUTER
Inserting a WAIT state. You could use a logic analyzer
Now that you have some knowledge of the software and
as we described earlier in the chapter to verify the timing
the hardware of a microcomputer system, we can start
on an actual SDK-86 board. teaching you how to troubleshoot a simple microcom-
Here's a final point about calculating the time available
puter system such as an SDK-86 board. For this section
for tACC, t, and t of some device in a system. Suppose
assume that the microcomputer or microprocessor-
that you want to add another pair of 2716 EPROMs in
based instrument previously worked. Later sections of
the prototyping area of the SDK-86 board, and you want
this book will describe how the prototype of a micropro.
to enable the outputs of these added devices with the
cessor-based instrument is developed.
03 output of the 3625 ROM decoder on sheet I of the
The following sections describe a series of steps that
schematics. The timing for these added devices wU be
we have found effective In troubleshooting various mi-
the same as for the previously discussed 27l6s, except
crocomputer systems. The first point to impress on your
that the data from the added devices must come back
mind about troubleshooting a microcomputer is that a
through the 8286 buffers shown on sheet 4 of the SDK-
systematic approach is almost always more effecilve
86 schematics. According to an 8286 data sheet, these
than random poking, probing, and hoping. You don't,
buffers have a maximum delay of 30 ns. This 30 ns
for example, want to spend 2 hours troubleshooting a
must be subtracted from the times available for t, t,
system and finall y find that the only problem is that the
and tOE' If you look back at our calculations of the tIme
power supply is putting out only 3 V instead of 5 V. lJse
available for t in Figure 7-20a. for example, you will
the following list of steps or a list of your own each time
see that we ended up with 460 ns available for t.
you have to troubleshoot a microcomputer: (1) identify
Subtracting the 30 ns of buffer delay from this leaves
the sy mptoms. (2) make a careful visual and tactile
only 430 ns, which Is considerably less than the n6axi-
inspection. (31 check the power supply. (4) do a "signal
mum t M of 450 ns for the 2716. This tells you that,
roll call," (5) s ystematically substitute socketed (Cs, and
because of the buffer delay, the added 271 6s are not fast
(6) troubleshoot soldered-in ICs. The following para-
enough to operate on an SDK-86 board with a 4.9-MHz
graphs describe each step.
clock and no WAIT states. To take care of this problem,
the SDK-86 is designed so that any access to a memory
or t'O device "off board" will cause the selected number Identify the Symptoms
of WAIT atates to he inserted In the machine cycle. For
our example here, selecting one WAIT state with jumper Make a list of the symptoms that you find or those that
W28 on sheet 2 will give another 20' ns for the data to a customer describes to you. Find out, for example,
get from the 2716s to the 8086. This is more than whether the symplom Is present Immediately when the

200 CHAPTER SEVEN


power is turned on or whether the system must operate condition by the failure of some TTL devices. To check
for a while before the symptom shows up. If someone this out, use the manual to help you predict what logic
else describes the symptoms to you, check them yourself. level should be on each of the CPU input control signals
or have that person demonstratC the symptoms to you. for normal operation. The RDY input of the 8086, for
This allows you to check If the problem Is with the example, should be high for normal operation. If an
machine or with how the person is attempting to use external logic gate falls and holds RDY low, the 8086
the machine. will go on inserting WAIT states forever, and the buses
will be held constant, If the 8086 HOLD input is stuck
high or the RST input is held high. the 8086 address/
Make a Careful Visual and Tactile Inspection data bus will be floating. Connecting a scope probe to
This step is good for preventive maintenance as well for these lines will pull them to ground. so you will see them
finding a current problem. Check for components that as constant lows,
have been or are excessively hot. When touching compo- If there is activity on the buses. use an oscilloscope to
ncnts to see if any are too hot, do it gently, because a see if the CPU is putting out control signals such as RD
bad IC can get hot enough to give a nasty burn if you and WR. Also, check with your oscilloscope to see if
keep your finger on it too long. select signals are being generated on the outputs of the
Check to see that all ICs are firmly seated in their ROM. RAM. and port decoders as the system attempts
sockets and that the lCs have no bent pins. Vibration to run Its monitor or basic program. If no select signals
can cause lCs to work loose in their sockets. A bent pin are being produced, then the address decoder may be
may make contact for a while, but after heating. cooling, bad or the CPU may not be sending out the correct
and vibration, it may no longer make contact, Also. addresses,
inexpensive IC sockets may oxidize with age and no After a little practice, you should be able to work
longer make good contact. through the previously described steps quite quickly. If
Check for broken wires and loose connectors. A thin you have not located the problem at this point, the
film of dust. etc.. may form on printed . circuit-board edge next step for . system with its ICs in sockets is to
connectors and prevent them from making dependable systematically substitute known good lCs for those in
contact. The film can be removed by gently rubbing the the nonworking system.
edge connector fingers with a cleaning pad available for
this purpose. If the microcomputer has ribbon cables. Systematically Substitute Socketed ICs
check to see if they have been moved around or stressed.
Ribbon cables have small Wires that are easily broken. The easiest case of substitution is that where you have
II you suspect a broken conductor in a ribbon cable, two Identical microcomputers, one that works and one
you can later make an ohmmeter check to verify your that doesn't, and the iCs of both units are in sockets,
suspicions. For this case you can use the working system to test the
lCs from the noriworking system. The trick here is to
do this in such a way that you don't end up with two
Check the Power Supply systems that do not work! Here's how you do it.
First of all, do not remove or insert any ICs with the
From the manual for the microcomputer, determine power on! With the power off, remove the CPU from the
the power supply voltages. Check the supply voltage(s) good system and put it in a piece of conductive foam.
directly on the appropriate pins of some ICs to make Plug the CPU from the bad system into the now empty
sure the voltage is actually getting there. Check with a socket on the good board and turn on the power. If the
scope to make sure the power supplies do not have good system still works, then the CPU is probably good.
excessive noise or ripple. One microcomputer that we Turn off the power and put the CPU back in the bad
were called on to troubleshoot had very strange symp- system. If the good system does not work with the CPU
toms caused by 2-V peak-to-peak ripple on the 5-V from the bad s ystem, then the CPU is probably bad.
supply. Remove It from the good system and bend the pins so
that you know it is bad. If the CPU seems bad. you can
Do a Signal Roll Call try replacing it with the CPU you removed from the good
system. If you do this, however. it Is important that you
The next step is to make a quick check of some key keep track of which IC came from which system. To do
signals around the CPU of the microcomputer. If the this, we like to mark each IC from the good system with
problem is a bad IC, this can help point you toward the a w!de-tip, water-soluble marking pen. We can then
one that is bad. First, check it the clock signal is present rebuild the good system by simply putting back all the
and at the right frequency. If not, perhaps the clock marked lCs. The marks on the ICs can easily be removed
generator IC is bad. If the microcomputer has a clock but with a damp cloth.
doesn't seem to be doing anything, use an oscilloscope to The procedure from here on is to keep testing ICs
check ii the CPU Is putting out control signals such as from the bad system until you find all the bad ICs. Make
RD. WP. and ALE. Also, check the least significant data sure you turn the power off before you remove or insert
bus line to see if there is any activity on the buses. If any ICs. Be aware that more than one IC may be bad. It
there is no activity on these lines, a comrncn cause is Is not unusual, for example, for an AC power line surge
that the CPU is stuck in a wait, hold, halt, or reset to wipe Out several devices in a s y stem. We usually work

5(186 SYST(M CONN[CFIONS, TIMING. AND TROU8LESHOOT I " "01


our way Out from the CPU to address latches, buffers, "slorper. Modern multliayer printed-circuit boards are
decoders, and memory devices, Often the specific symp- quite fragile, and these tools can slip and knock a trace
toms point you to the problem group of ICs without your right off the board. Instead, use cutters with narrow
having to test every IC in the system. If, for example. tips to Cut all the leads of the IC next to the body. Since
the system accesses ROM but doesn't access RAM, you are going to throw it out anyway. you don't care if
suspect the RAM decoder. If a system uses buffers on you destroy the IC. With the body of the IC out of the
the buses, suspect these devices. Buffers are high- way, you can then gently heat each pin individually and
current devices, and they often fail. use needle-nose pliers to remove it from the PC board.
If the hole fills with solder, heat it gently and insert a
small wooden toothpick until the solder cools. After you
Troubleshoot Soldered-in ICs replace each IC. power up the system and see if it now
The approach described in the preceding paragraphs works.
To remove "surface-mount" ICs, use a tool such as
works well if the system ICs are all In sockets and you
that shown in Figure 7-21. This tool sends out a directed
have two identical systems. However, since sockets add
blast of hot air which heats all the pins at the same time,
to the cost and unreliability of a system, many small
and allows the IC to be easily removed. To replace the
systems put only the CPU and ROMs in sockets. This
IC, you put some solder paste on the PC board pads for
makes your troubleshooting work harder but not Impos.
the IC. place the IC carefully in position, and heat the
slble.
pins with another blast of hot air.
Again, if you have two ldentica systems, one that
The techniques described iii the preceding sections
works and one that doesn't work, you can attempt to
will enable you to troubleshoot many microcomputer
run the monitor or basic system program on each and
systems with a minimum of test equipment. However,
compare signals on the two. A missing or wrong signal
specialized test equipment Is available to speed up the
may point you to the bad IC or ICs.
process and help find complex problems. The following
If the system works enough to read some instructions
sections describe two of these instruments.
from ROM and execute them, you can replace the
monitor or basic system ROM with one that contains
diagnostic programs which test RAM and I/O devices. A Equipment for Troubleshooting Microcomputers
RAM test routine, for example, might attempt to write
all l's to each RAM location and then read each memory LOGIC ANALYZER
location to see if the data was written correctly to A logic analyzer can be a powerful tool for debugging
that location, If the data read back is not correct, the difficult problems, but it is important [or you 10 have a
diagnostic program can stop and In some way tndicate perspective on when to use an analyzer in troubleshoot-
the address that it could not write to. If a write of all l's ing simple systems that previously worked. Generally
Is successful, then the test routine will try to write all you can use the techniques described in previous see-
0's to each memory location. A port test routine might
Initialize a port for output and then write alternating
l's and 0's to the port over and over again. With an
oscilloscope you .ean see if the port device is getting
enabled and if the data Is getting to the output of the
port device. Another port test routine might try to read
a byte of data in from a port over and over so that you
can again see if the device is getting enabled and if the
data Is getting through the device to the system data
bus. The technique of using program routines to test
hardware is a very Important one that you will use
many times when you are working with microcomputer
systems..
Now, suppose that you have localized the problem to
a few ICs that are soldered in. If the problem is one that
occurs when the unit gets hot, you might try spraying
some cold spray on the ICs, one at a time, to see if you
can determine which one has a problem. If this does not
find the bad IC or the problem is not heat-related, what
you do next is replace these ICs one at a time until the
system works correctly. The point we want to stress here
is that the Cost of these few ICs is probably much less
than the cost of the time it would take you to determine -,
Just which IC is bad, if you do not have specialized test FIGURE 7-21 Leister-Labor S hot'air contactless
equipment. desoldering and soldering tool for removing and
If you do not have special tools available to remove a replacing leaded and surface mount components on PC
"through-hole mounted" IC from a printed-circuit board, boards. (Courtesy Brian R. White Co. Inc., Uk,ah,
do not attempt to desolder pins with a hand-held solder California.)

202 CI-4APTtR SEVEN


tions to find and fix a problem in less time than it would technician and have to repair several different types of
take you to connect the logic analyzer. figure out what microcomputer systems with poor documentation to
.you should see in a trace, and determine If (he trace is work from, most analyzers are not too useful. To make
correct. your life easier in this case, "smart' Instruments such
One of the main problems is that in a repair setting as the Fluke 9010A Microsystem troubleshooter have
you often don't have good documentation on an instru- been created.
ment, so it is difficult to determine what the correct An you can see from the picture of the 90 bA in Figure
trace should be. Anaiyzers such as the Tektronix 1230 7-22, it has a keyboard. a display. and an "umbilical"
allow you to store a trace from a functioning Instrument cable with an IC plug on the end. The unit also contains
in a reference memory. This trace can then be compared a rninicassette tape recorder, For troubleshooting, the
with a trace from a nonfunctioning instrument. We have 901 OA is used as follows.
found this feature very helpful In pointing to the source The microprocessor In a fully functioning unit is
of a problem. removed, and the plug at the end of the cable is inserted
The disassembly feature found in some analyzers is in its place. The learn function of the 9010A is then
also useful, because it allows you to determine if a executed. This function finds and maps ROM. RAM. and
microcomputer-based Instrument is correctly fetching I/O registers that can be written into and read from. It
and executing its basic control program. also computes signatures (checksums) for blocks of
Despite the minor difficulties, don't hesitate to use an ROM. All these parameters are stored in the 9010A's
analyzer when the simple techniques don't seem to be RAM and/or on a minicassette tape. The microprocessor
getting you anywhere. on a malfunctioning unit is then removed and the plug
at the end of the umbilical cable inserted in its place.
An automatic test function is then executed. In this
mode, the 9010A tests the buses, RAM. ROM. ports.
OTHER MICROCOMPUTER power supply, and clock on the malfunctioning system.
TROUBLESHOOTING EQUIPMENT Any problem found, such as stuck nodes or adJaccnt
A logic analyzer is a very powerful troubleshooting trace short circuits. is Indicated on the display. The
tool, but to use it effectively, you need some detailed results of this test give some good hints as to the source
knowledge and a program listing for the system that you of the problem. Because of its built-in intelligence, the
are trying to troubleshoot. If you are working as a repair 9010A can be programmed to do other tests as well.

.1

FIGURE 7 . 22 Fluke 9010A microsystem troubleshooter. (John Fluke ffg. Co.,


lfl(
8Oô SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 2C
- 28
The point of an instrument such as the 9010A is that State. instruction cycle, machine cycle, WAIT state, RDY
with It you do not have to be intimately familiar with signal
the programming language and hardware detailq
of a simple microcomputer system In order to trouble- Bus activities during read/write
shoot it.
Logic analyzer use: external clock, internal clock, word
recognizer. trigger, trace
Bidirectional buffer
General functions: 8284, 8255A, 8251A, 8279, 2716.
2142
CHECKLIST OF IMPORTANT TERMS AND
CONCEPTS IN THIS CHAPTER SDK-86 schematic: zones, plugs, Jacks. resistor
packs
If you do not remember any of the terms or concepts in Address decoding: ROM decoding. RAM decoding. port
the fouowtng list, use the Index to find them in the decoding
chapter.
Memoiymapped and direct 110
Pin functions of 8086: 8086 memory banks
RD. WR, CLK. ALE, M/lO, LOCK. MN/MX, RESET,
NMI, INTR, BHE, DEN, DT'R Timing parameters: t. tç. tOE. t. TCLAV, TCLRL.
TDVCL
8086 RESET response
8086 typical clock frequencies
4aximum and minimum mode of 8086
Troubleshooting steps for a simple 8086-based micro-
8086 timing diagram interpretation computer

REVIEW QUESTIONS AND PROBLEMS


I. From what point on the waveIonn is thc st:-rt e. How many WAIT states can be inserted in a
of an 8086 State measuj machine cycle?
-
-. Why are latches requiret 'U,: e . !. .) ADI5 bu ii' j Why would you want the 8086 to insert a WAIT
an 8086 system? state
3. What is the purpose of the ALE sIgnal in an 8086 10. What are the functions of the 8086 DT/R and DEN
system? signals?
4. Descrl be the sequence of events on the 8086 11. What does an arrow going from a transition on
data/address bus, the ALE line, th .s M./iO line, one signal waveform to a transition on another tell
and the RI) line as the 8086 fetches an Instruction you?
word.
12. Draw a block diagram of a simple logic analyzer
S. What, logic levels will be on the 8086 RD. WR. and and briefly describe how it operates. Include in your
M/lO lines when the 8086 is doing a write to a answer the function of the clock and the function
memory location? A read from a port? of the trigger.
6. What is the major difference between an 8086 13. What do you use for a logic anaiyzer clock
operating in minimum mode and an 8086 operatIng when you want to make detailed timing measure-
in maximum mode? ments?
7. Describe the response an 8086 will make when its
14. On what signal and what edge of that signal would
RESET (RST) input is asserted high. you clock a logic analyzer, and on what word would
8. Why are buffers often needed on the address, data. you trigger to see each of the following in an 8086
and control buses in a microcomputer system? system?
a. The sequence of addresses output after a
9. a. How is an 8086 entered into a WAIT state? RESET.
b. At what point In a machine cycle does an 8086 b. The sequence of instructions read in after a
enter a WAIT state?
RESET. (Assume that the first instruction word
c. What Information Is on the buses during a is 9CEAH.I
WAIT state? c. Both the addresses sent out and the words
ci. How long isa WAIT state? read in.

204 CHAPTER SEVEN


d. What clock qualifier would you use to see a


31. Why is some ROM put at the top of the address
trace of oniy data read in from ports? space in an 8086 system?
IS. How Is it possible for a logic analyzer to display 32. a. Show the truth table you would use for a 3625
data that occurred before the trigger? PROM decoder to produce CSI signals for
4K x 8 RAMs In an 8086 system. Assume the
16. How are wire-wrap Jumpers indicated on a sche-
first RAM starts at address 00000H. Don't
matic?
forget A0 and BHE.
17. What is the meaning of 18 on a signal line in a b. Draw the circuit connections for the 3625
schematic? decoder PROM and for two of the 4K x 8 RAMs.
18. Describe the two purposes of address decoders In 33. Use sheets 5 and 7 of the SDK-86 schematics to
microcomputer systems. help you determine for the SDK-86 what lqg levels
will be on BHE. AO to Al 9. M/lO. RD. and WR when
19. A memory device has 15 address lines connected
a word is read from ports FFFSH and FFF9H.
to it and 8 data outputs. What Size words and how Are these ports memory-mapped or direct? What
many words does the device store?
instruction(s) would you use to do this read oper-
20. Briefly describe the function of the 8255. 8251A. ation?
and 8279 devices in the SDK-86 microcomputer 34. a. How Is the OFF BOARD signal produced on the
system.
SDK-86 board?
21. A group of signal lines In a schematic has the b. Describe the purpose of the OFF BOARD signal.
label 2ZB3 next to it. What Is the meaning of
35. Describe how the 8088 memory is configured. Why
this label?
doesn't the 8088 need a BHE signal?
22. What is the difference between a connector identi-
36. By referrtng to the 8086 timing diagrams in Figure
fled with a J and a connector identified with a P? 7-19a and parameters in Appendix A. determine
23. Describe the purpose of the many small capacitors for the 8086-2:
connected between and ground on microcom- a. The maximum clock frequency.
puter printed-circuit boards. b. The time between CLOCK going low and RD
going low.
24. A 74LS 138 decoder has Its three SELECT inputs c. The time for which memory must hold data on
connected to Al2, A13, and A14 of the system the data bus after CLOCK goes low at the start
address bus. it has G2A connected to A15, G2B of T4.
connected to RD. and GI connected to +5 V. Use d. The time that the lower 16•address bits remain
an address decoder worksheet to determine what on the data bus after ALE goes low.
eight ROM address blocks the decoder outputs will
select. Why is RD used as one of the enables on a 37. The 27128-25 is a 16K x 8 EPROM with a tAec of
ROM decoder? 250 ns maximum, a t of 250 ns maximum, and
a t of 100 ns maximum. Will this device work
25. Show a memory map for the ROMs in Problem 24.
correctly without WAIT states in an 8-MHz 8086-2
26. Use an address decoder worksheet to help you draw system with circuit connections such as those
a Circuit to show how another 74LS 138 can be in the SDK-86 schematics? Assume the address
Connected to select one of eight I-Kbyte RAMs latches have a propagation delay of 12 ns and the
starting at address 800011. decoder has a delay 0130 ns.
27. Why are there actually many addresses that will List the major steps you would take to trouble-
select one of the port devices connected to the port shoot a microcomputer system such as the SDK-
decoder in Figure 7-12a? 86 which previously worked. Assume all ICs are in
sockets.
28. Describe memory-mapped I/O and direct ['0.
Give the main advantage and main disadvantage 39. Why is it important to check power supplies with
of each. an oscilloscope?

29. a. Why is the 8086 memory set up as 2-byte-wide 40. Describe how you can keep from mixing up ICs
banks? from a good system with those from a bad system
b. What logic levels would you find on BIlE and when substituting.
A0 when an 8086 is writing a byte to address 41. Write an 8086 rOutine to test the system RAM in
0427411? When ii is writing a word to 04274H addresses 0020011 through O7FFFH.
c Describe the 8086 bus operations required to
write a word to address 04373Ff. 42. Write a test routine to output alternating is and
Os to port FFFAH over and over. With this routine
30. how does the circuitry on the SDK-86 make sure running, you could check with an oscilloscope to
that von cannot accidentally write a byte or word see if the port device is getting enabled and is
to ROM? outputting data.

84)86 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTiNG 205


43. Describe the symptoms that an SDK-86 would show c. None of the outputs of A29 in zone D7 of
for each of the following problems. schematic sheet 6 ever goes low.
a. Pin 8 of Al 5 in zone D5 of schematic sheet 2 d. Pin 6 of A3 in zone A5 of schematic sheet 5 is
Is stuck low, stuck low.
b. The reset key is stuck on.

206 CHAPTER SEVEN


8086 Interrupts and
Interrupt Applications

Most microprocessors allow normal program execution The third source of an interrupt is some error condi-
to be interrupted by some external signal or by a special tion produced in the 8086 by the execution of an
instruction in the program. In response to an interrupt. instruction. An example of this is the divide-by-zero
the microprocessor stops executing its current program interrupt. If you attempt to divide an operand by zero,
and calls a procedure which "services" the interrupt. An the 8086 will automatically interrupt the currently exe-
IRET Instruction at the end of the interrupt-service cuting program.
procedure returns execution to the interrupted program. At the end of each instruction cycle, the 8086 checks
This chapter introduces you to the 8086 interrupt types. to see if any interrupts have been requested. If an
shows you how the microprocessors in the 8086 family interrupt has been requested, the 8086 responds to the
respond to interrupts, teaches you how 10 write inter- interrupt by stepping through the following serie€ of
rupt-service procedures, and describes how interrupts major actions.
are used in a variety of applications.
I. It decrements the stack pointer by 2 and pushes the
flag register on the stack.

OBJECTIVES 2. It disables the 8086 INTR Interrupt input by clearing


the interrupt flag (IF) In the flag register.
At the conclusion of this chapter, you should be able to;
3. It resets the trap flag (TF) in the flag register.
I. Describe the interrupt response of an 8086 family
4. It decrements the stack pointer by 2 and pushes the
processor. current code segment register contents on the stack.
2. Initialize an 8086 interrupt vector (pointer) table.
5. It decrements the stack pointer again by 2 and
3. Write interrupt-service procedures. pushes the current instruction pointer contents on
the stack.
4. Describe the operation of an 8254 programmabic
counter/timer and write the instructions necessary 6. It does an IndIrect far jump to the start of the
to initialize an 8254 for a specified application. procedure you wrote to respond to the interrupt.

5. Describe the operation of an 8259A priority interrupt Figure 8-1, p. 208. summarizes these steps in diagram
controller and write the instructions needed to ini- form. As you can see, the 8086 pushes t he flag register
tialize an 8259A for a specified application. on the stack. dfsable& the INTR input and the single-
step function, and does essentially an indirect far call
6. Call a BIOS procedure using a software interrupt. to the interrupt service procedure. An IRET Instruction
at the end of the interrupt service procedure returns
execution to the main program. Now let's see how the
8086 INTERRUPTS AND 8086 actually gets to the interrupt procedure.
INTERRUPT RESPONSES Remember from Chapter 5 that when the 8086 does
a far call to a procedure. it puts a new value in the code
Overview segmeni register and a new value in the instruction
An 8086 interrupt can come from any one of three pointer. For an indirect far call, the 8086 gets the new
sources. One source is an external signal applied to values for CS and IP from four memory addresses.
the norrrnaskable interrupt INMII input pin or to the Likewise, when the 8086 responds to an Interrupt. It
Interrupt (INTR) input pin. An Interrupt caused by a goes to four memon' locations to get the CS and IP
signal applied to one of these Inputs Is referred to as a values for the Start of the interrupt-service procedure.
hardware Interrupt. In an 8086 s y stem. the first 1 Kbyte of memor . from
A second source of an interrupt is execution of the 00000H to 003FFH. is set aside as a table for storing
Interrupt Instruction. tNT. This is referred to as a the starting addresses of interrupt service procedures.
software interrupt. Since 4 b y tes are required to store the CS and IP values

207

MAINLINE
PROGRAM INTERRUPT for use In more complex microprocessors, such as the
SERVICE 80288, 80386, and 80486. In a later chapter we dlscus.c
PUSH FLAGS EDURE
CLEAR IF PUSH REGISTERS some of these Interrupt types. The upper 224 Interrupt
CLEAR IF types, from 32 to 255. are available for you to use for
PUSH CS hardware or software interrupts.
PUSH IF
FETCH ISR ADDRESS As you can see in Figure 8-2. the vector for each
interrupt type requires four memory locations. There.
POPIP fore, when the 8086 responds to a particular type
I
II Interrupt, it automatically multiplies the type by 4 to
PoPCS
POP REGISTERS produce the desired address In the vector table. It then
RET
goes to that address In the (able to get the starting
FIGURE -1 8086 interrupt response. address of the interrupt service procedure. We will show
you later how you use instructions at the start of your
program to load the starting address of a procedure into
for each Interrupt service procedure, the table can the vector table.
hold the starting addresses for u.i to 256 Interrupt Now that you have an overview of how the 8086
procedures. The starting address of an Interrupt service responds to interrupts, we will discuss one type of
procedure Is often called the interrupt vector or the interrupt in detail and showyou how to write a procedure
interrupt pointer, so the table is referred to as the to service that interrupt.
interrupt-vector table or the interrupt -pointer table.
Figure 8-2 shows how the 256 Interrupt vectors are
arranged In the table In memory. Note that the instruc- An 8086 Interrupt Response Example—Type 0
tlon pointer value is put In as the low word of the vector. Probably the easiest 8086 interrupt to understand It
and the code segment regIster Is put In as the high the divide-by-zero Interrupt, identified as type 0 Ic
word of the vector. Each doubleword Interrupt vector is FIgure 8-2. Before we get into the details of the type C
identified by a number from 0 to 255. Intel calls this interrupt response, let's refresh your memory about how
number the type of the interrupt. the 8086 DIV arid IDlY Instructions work.
The lowest five types are dedicated to specIfic Inter- The 8086 DIV instruction allows you to divide a 16-
rupts, such as the divide-by-zero interrupt, the single- bit unsigned binary number in AX by an 8-bit unsigned
step interrupt, and the nonmaskable interrupt. Later In number from a specified register or memory location.
this chapter we explain the operation of these Interrupts The 8-bit result (quotient) from this division will be left
in detail. Interrupt types 5 to 31 are reserved by Intel in the AL register. The 8-bit remainder will be left in the
Al-I register. The DIV Instruction also allowsyou to divide
a 32-bit unsigned binary number In DX and AX by a 16-
3FFI-4 bit number in a specified register or memory location.
TYPE 255 POINTER: The 16-bit quotient from this division Is left in the AX
3FCH (AVAILABLE)
register, and the 16-bit remainder is left In the DX

J register. In the same manner, the 8086 IDlY instruction

4
AVAILABLE INTERRUPT
POINTERS (224) allows you to divIde a 16-bit signed number in AX by an
TYPE 33 POINTER 8-bit signed number In a specified register or a 32-bit
(AVAILABLE) signed number in DX and AX by a 16-bit signed number
TYPE 32 POINTER. from a specified register or memory location.
080H IAVAJ LABLE)
O7FH
lithe quotient from dividing a 16-btt number is too
TYPE31POINTER large to fit in AL or the quotient from dividing a 32-bit
(RESERVED)
number is too large to fit In AX. the result of the division
RESERVED INTERRUPT
POINTERS )27( will be meaningless. A special case of this Is where an
attempt Is made to divide a 32-bit number or a 16-bit
I TYPESPOINTER number by zero. The result of dividing by zero is Infinity
01414 (RESERVED)
(actually undefined), which Is somewhat too large to fit
TYPE 4 POINTER: In AX or AL. Whenever the quotient from a DIV or IDly
010H OVERFLOW operation IS too large to fit in the result register. the
TYPE 3 POINTER. 8086 will automatically do a type 0 interrupl. In response
1-BYTE INT INSTRUCTION
DEDICATED INTERRUPT
to this Interrupt the 8086 proceeds as follows.
TYPE 2 POINTER The 8086 first decrements the stack pointer by 2 and
POINTERS (5) . NON-MASKABLE
008H
copies the flag register to the stack. It then clears IF and
I TYPE 1 POINTER TF. Next, It saves the return address on the stack. To
____________________ 004H SINGLE-STEP
CS BASE ADDRESS1I do this, the 8086 decrements the stack pointer by 2.
TYPE OPOINTER
IPOFFSET '1 j, DIVIDE ERROR pushes the CS value of the return address on the stack.
0001-4 I decrements the stark pointer by 2 again, and pushes
I- 16 BITS the lP value of tile return address on the stack, The
8086 then gets the starting address of the interrupt-
FIGURE 8-2 8086 Interrupt-pointer table.
service procedure from the type 0 locatIons In the
208 CHAPTER FIGHT
interrupt-vector table. As you can see in Figure 8-2. It INITIALIZATION LIST
gets the new value for Cs from addresses 00002H and
00003H and the new value for IP from addresses 00000H REPEAT
Get INPUT VALUE
and 00001 H. After the starting address of the procedure Divide by scale factor
is loaded Into CS and IP. the 8086 then fetches and If result valid THEN
executes the first Instruction of the procedure. store result as scaled value
At the end of the interrupt-service procedure, an IRET ELSE store zero
UNTIL all values scaled
instruction Is used to return execution to the interrupted
program. (a)

• The IRET instruction pops the stored value of IP off Save registers
the stack and increments the stack pointer by 2. It then Set error flag
pops the stored value of CS off the stack and increments Restore registers
Return to mainline
the stack pointer again by 2. Finally, it restores the flags
by popping off the stack the values stored during the Is
Interrupt response and increments the stack pointer by
FIGURE 8-3 Algorithm for divide'by-zero program
2. Remember from the previous paragraph that during example. (a) Mainline program. (b) Interrupt.ser-vice
Its Interrupt response, the 8086 disables the INTR and procedure.
single-step interrupts by clearing IF and TF. If the INTR
Input and/or the trap Interrupt were enabled before the
interrupt, they will be enabled upon return to the program. The flag in this case Is not one of the flags in
interrupted program. The reason for this is that flags the 8086 flag register. The flag here is a bit In a mem-
from the interrupted program were pushed on the stack ory loiation we set aside for this purpose. In the
before IF and TF were cleared by the 8086 in tts interrupt actual program, we give this memory locatIon the name
response, To summarize, then. IRET returns execution BAD..DIV_FLAG. At the end of the interrupt-service
to the Interrupted program and restores IF and TF to procedure, execution is returned to the interrupted
the state they were in before the Interrupt. Now that we mainline program.
have described the type 0 response, we can show you After the divide operatIon in the mainline program.
how to write a program to handle this interrupt. we check the value of the BAD_DIV_FLAG to determine
If the result of the division is valid, If the result of the
An 8086 Interrupt Program Example division was too large. then the 8086 wIll have done a
type 0 Interrupt, and the interrupt . servtce procedure
DEFINING THE PROBLEM AND will have set the BAD_DIV_FLAG to a 1. If the result of
WRITING THE ALGORITHM the division is valid, then the 8086 will not have done
In the last chapter we were working mostly with hard- the type 0 interrupt, and the HAD_DIV_FLAG will be 0.
ware, so Instead of jumping directly into the program, This sequence of operations is repeated until all the
let's use this example to review how you go about writing values have been scaled.
any program.
For the example program here, assume we have four
WRITING THE INITIALIZATION LIST
word-sized hexadecimal values stored in memory. We After you have worked out the data structure and the
want to divide each of these values by a byte-type scale algorithm for a program. the next step is to make an
factor to give a byte-type scaled value. If the result of the initialization list such as the one shown in Chapter 3.
division is valid, we want to put the scaled value in an Here is a list for this program.
array in memory. If the result of the division is invalid
(too large to fit in the 8-bit result register), we want to I. Initialize the Interrupt-vector table. In other words,
put 0 in the array for that scaled value. Figure 8-3 shows the starting address of our type 0 interrupt service
the algorithm for this program in pseudocode. routine must be put in locations 00000FI and
00002H.
As shown in Figure 8-3a. the mainline part of this
program gets each (6-bit value from memory in turn 2. Set up the data segment where the values to be
and divides that value by the 8hii scale factor. If scaled, the scale factor, the scaled values, and the
the result of the division is valid, it is stored in the BAD_DIV_FLAG will be put.
appropriate memory location: else a 0 is stored in the
memory location. Not indicated in the algorithm is how 3. Initialize the' data segment register to point to tile
we determine whether the quotient is valid or not. base addrcss of the data segment containing the
With 8086 family microprocessors, a t ype 0 interrupt values to he scaled.
procedure is a handy way to do this. 4. Set up a stack to store the 11a and return address.
Remember from the preceding discussion that If the
result of the division is too large to fit in the quotient 5. Initialize the stack segment and stack pointer reg-
register. AL. then the 8086 will do a t ype 0 Interrupt isters.
Im mediately aftcr the divide instruction finishes. Figure
6. Initialize a pointer to the start of the data to he
8-3b shows the algorithm for a procedure to service this scaled, a counter to keep track of how many values
type 0 interrupt. The main function of this procedure
is to set ajiag which will be checked by the mainline have been scaled, and a pointer to the Start of the
array where the scaled values are to be written.

80& INTERRUPTS AND INTERRUPT APPLIcATIONS 209


;8086 MAINLINE PROGRAM F8-04A.ASM
2 ;A8STRACT Program scales data values using division.
3 ;PORTS : None used
4 ;REGISTERS Uses CS,DS,ES,SS,SP,Sl.AX,BX.CS
5 ;PROCEDURES : Uses BAD_DIV. a type 0 interrupt service procedure
6 Link mailine FB-04A.OBJ with procedure F8-04B.OSJ
7
8 0000 DATA SEGMENT WORD PUBLIC
9 0000 0035 085S 2011 1359 INPUT_VALUES DW 003514, 08554, 20114, 1359H
10 0008 04(00) SCALED_VALUES 08 4 OUP(0) Answers 05,ED,CO300
11 000C 09 SCALE_FACTOR 08 09
12 0000 00 BAD DIV_FLAG 09 0
¶3 000K DATA ENDS
14
15 0000 STACK_SEG SEGMENT STACK
¶6 0000 64(0000) DV 100 DUP (0) Set up stack of 100 words
17 TOP STACK LABEL WORD Pointer to top of stack
18 0008 STACK_SEG ENDS
19
20 PUBI.IC BAD_DIV_FLAG Make flag available to other modules
21
22 0000 BET_PROC SEGMENT WORD PUBLIC
23 EXTRN BAD DIV:FAR Let asseetter know procedure BAD DIV
24 0000 INT_PROC ENDS is in another asseetty module
25
26 0000 C00E SEGMENT WORD PUBLIC
27 ASSIJ4E CS:C00E, DS:DATA, SS:STACK_SEG
28 0000 88 0000s START: NOV AX, STACK_SEG initialize stack Segment
29 0003 8€ 00 NOV SS, AX register
30 0005 BC OOCBr NOV SP, OFFSET TOP_STACK Initialize stack pointer
31 0008 88 0000s NOV AX, DATA Initialize data segment
32 000B BE 08 NOV OS, AX register
33 ;Store the address for the BAD_DIV routine at address 0000:0000
31. ;Address 00000-00003 is where type 0 interrupt gets interrupt
35 ;service procedure address. CS at 00002 & 00003, IP at 00000 & 00001
36 0000 88 0000 NOV AX, 0000
37 0010 8E CO NOV ES, AX
38 0012 26: C7 06 0002 0000s NOV WORD PTR ES:0002, SEG BAD_DIV
39 0019 26: C7 06 0000 0000e NOV WORD PTR ES:0000, OFFSET BAD_DIV
40 0020 BE 0000r NOV SI, OFFSET INPUT_VALUES ; Initialize pointer for input values
41 0023 88 0008r NOV BX, OFFSET SCALED_VALUES Point BX at start of result array
42 0026 89 0004 NOV CX, 0004 Initialize data value counter
43 0029 8804 NEXT: NOV AX, (Si) Bring a value to AX for divide
44 0029 F6 36 000Cr DIV SCALE_FACTOR Divide by scale factor
45 002F 80 3E 0000r 01 CMP BAD_DIV_FLAG, 01 If divide produced valid result
46 0034 7506 JWE OK then go save scaled value
47 0036 Co 07 00 NOV BYTE PTR IBNI, 00 eLse load icaled value
48 0039 KB 03 90 JMP SKIP
49 003C 88 07 OK: NOV IBX), AL Save scaled value
50 003E CO 06 0000r 00 SKIP: NOV BAD_DIV_FLAG. 0 Reset BAD_DIV_FLAG
51 0043 83 CO 02 ADD SI, 02 Point at next input value location
52 0046 43 INC BX Point at location for next result
53 0047 (2 EU L00P NEXT Repeat untiL all values done
54 0049 90 STOP: NOP
55 004A C00E ENDS
56 END START
Ia I

FIGURE 8-4 8086 assembly language program for divide-by-zero example. (a) Mainline.
(See also next page.)

Once you have the algorithm and the initialization list when y ou write your own interrupt programs. Also, to
for a program. the ni-st step is to start writing the help refresh your memory of the PUBLIC and EXTRN
instructions for the program. so flow lets look at the directives, we have written the mainline program and
assembl y language program for this problem. I lie interrupt service procedure as two separate assembly
modules.
At the start of the mainline program in Figure 8-4a,
ASSIMBI.Y 1.ANC;UAGE PROGRAM we declare a segme lit named I )ATA for the data that
AND INTERRUP1 PROCEDURE the program will he working with. The WOR[) in this
Figure 84 shows our 8086 assembl y lartguage program statement tells the Iltiker. locator to locate this segment
for I lie mainline arid for the t ype 0 interrupt service on the lirst available even address. The PUBLIC in this
procedure. You can use man y parts from these examples statement tells the linker that this segment can bejoined

210 CHAPTER EIGHT


;8086 PROCEDURE F8-04B.ASI4 catted by the program F8-04A.ASM
2 ;ABSTRACT: PROCEDURE BAD DIV
3 Services divide-by-zero interrupt (TYPE 0).
4 Sets the LSB of a memery location catted BAD_DIV_FLAG,
5 enables INIR, and returns execution to the interri.çted program
6 ;DESTROYS: Nothing
7
8 0000 DATA SEGMENT D PUBLIC
9 EXIRN BAD_DIV_FLAG:BYTE ; Let asseithter know BAD_DIV_FLAG
10 0000 DATA ENDS is in another asseithty module
11
12 PUBLIC BAD_DIV ; Make procedure BAD_DIV available
13 to other assethty modules
14 0000 lilT_PROC SEGMENT bARD PUBLIC Segment for interrupt service procedure
15 0000 BAD_DIV PROC FAR Procedure for type 0 interrupt
16 ASS*14E CS:INT_PROC, OS:DATA
17 0000 50 PUSH AX Save AX of interrupted program
18 0001 1E PUSH OS Save OS of interrupted program
19 0002 B8 0000s NOV AX, DATA Load Data Segnt register value
20 0005 SE 08 NOV DS, AX needed here
21 0007 C6 06 0000e 01 NOV BAD_DIV_FLAG, 01 Set LSB of BAD_DIV_FLAG byte
22 000C 11 POP OS ; Restore OS of interrupted program
23 0000 58 POP AX Restore AX of interrupted program
24 000E CF IRET Return to next instruction in interrupted
25 000F BAD_DIV ENDP ; program
26 000F INT_PROC ENDS
27 £110
(b)

FIGURE 8-4 (continued) ( b) Interrupt-service procedure.

together (concatenated) with segments of the same name as public. This means that when the object module for
from other assembly modules. The Input values are this program is linked with some other object module
words, so we use a DW directive to declare these four that declares BAD_DIV_FLAG as EXTRN, the linker will
values. The scaled values will be bytes. so we use a DB be allowed to make the connection. Some programmers
directive to set aside four locations for them. Remember say that the PUBLIC directive "exports" a name or label.
that the DUP(0) In the statement initializes the 4-byte The other end of this export operation is to "import"
locations to all Os. As the program executes, the results labels or names that are defined in other assembly
will be written Into these locations. SCALE_FACTOR modules. For example, the statement EXTRN BAD_
DB 09H Sets aside a byte location for tl'ie number by DIV:FAR in our example program tells the assembler
which we are going to be dividing the input values. The that BAD_DIV is a label of type far and that BAD_DIV ts
advantage of using aDB rather than an EQU directive defined in some other assembly module. The INT_PROC
to declare the scale factor is that with a DB the value of SEGMENT WORD PUBLIC and INT_PROC ENDS state-
the scale factor can be held in RAM, where ii can be ments tell the assembler that BAD_DIV is defined in a
changed dynamically in the program as needed. If you segment named INT_PROC. When the assembler reads
use a statement such as SCALE_FACTOR EQU 09H to these statements. It will make an entry in its symbol
Set a value, you have to reassemble the program to table for BAD_DIV and identify It as external. When the
change the value. object module for this program is linked with the object
Part of the 8086 interrupt response Is essentially a far module for, the program where BAD_DIV Is defincI. the
call to the Interrupt service procedure. In any psogram linker will fill in the proper values for the CS and IP of
that calls a procedure, we have to Set up a stack to Store BAD_DIV.
the return address and parameters passed to and from For the actual instructions of our mainline program.
the procedure. The next section of the program declares we declare a 'ode segment with the statement CODE
a stack segment called STACK_SEG. It also establishes SEGMENT WORD PUBLIC.
a pointer to the next location above the stack with the As usual, at the start of the code segment we use an
statement TOP_STACK LABEL WORD. Remember from ASSUME statement to tell the assembler what logical
the examples in Chapter 5 that this label is used to segments to use for code, data, and stack. After this
initialize the stack pointer to the next location after the come the familiar Instructions for initializing the stack
(op of the stack. segment register. the stack pointer register. and the
The next two parts of the program are necessary data segmcrit register.
because we wrote the mainline program and (he inter- The next tour instructions load the address of the
rupt service procedure as two separate assembly mod- BAD_DIV interrupt-service procedure in the type 0
ules. When the assembler reads through a source pro- locations the interrupt-vector table. We load ES with
gram, It makes a symbol table which contains the 0000 so tiat we can use it as an Imaginary segmc"t
segment and offset of each of the names and labels used absolute ,ddres 00000H. Then we use the staternn
In the program. Thestatement PUBLIC_BAD_DIV_FLAG MOV WC'i ii) PTR ES:0000 OFFSET BAD_DIV to Ioa
tells the assembler to Identify the name BAD_DIV_FLAG the offst )f the interrupt-service procedure in memory
29 8086 INTl KRUPTS ANI) INT'KK'Jrl ArtLILAIIUF4) LI
at 00000FI and 00(X) I H. The statement MOV WORD PTR that It does not load the DS register with a value for the
ES:0000 SEG BAD_DIV is used to load the segment start of that segment. The instructions MOV AX,DATA
base address of BAD_DIV into memory at 00002H and and MOV DS.AX do this In our procedure.
00003H. It is necessary to load the interrupt procedure Finally, we get to the whole point of this procedure
addresses in this way if you are using an SDK-86 bosrd with the MOV BAD_DIV_FLAG,01 instruction. This
or using the MASM and Link programs on an IBM PC- instruction simply sets the least significant bit of the
type machine. memory location we set aside with a DB directive at the
Next, we initialize SI as a pointer to the first input start of the mainline program. Note that in order to
value and initialize BX as a pointer to the first of the access this variable by name, you have to let the assem-
locations we set aside for the 8-bit scaled results. CX is bler know that it Is external, and you have to make sure
initialized as a counter to keep track of how many values that the DS register contains the segment base for the
have been scaled. segment in which BAD_DIV_FLAG Es located.
Finally, after everything is initialized, we get to the To complete the procedure, we pop the saved registers
operations weset out to do. The statement MOVAX.ISII off the stack and return to the interrupted program.
copies an input value from memory to the AX register, The IRET instruction, remember, is different from the
where It has to be for the divide operation. The DIV regular RET instruction in that it pops the flag register
SCALE_FAC'FOR instruction divides the number in AX and the return address off the stack. Note in the program
by 09H, the value we assigned to SCALE...YACTOR in Figure 8-4b that the procedure must be "closed" with
previously with a DB directive. The 8-bit quotient from an ENDP directive, and the segment must as usual be
this division will be put in AL, and the S-bit remainder closed with an ENDS directive.
will be put in AH. If the quotient Is too large to fit in AL. Now let's look back in the mainline to see what it does
then the 8086 wIll automatIcally do a type 0 Interrupt. with this BAD_DIV_FLAG. Immediately after the DIV
For our program here, the 8086 will push the flags on instruction, the mainline checks to see if the BAD_
the stack, reset IF and TF, and push the return address DIV_FLAG is set by comparing it with 01. If the BAD_
on the stack. It will then go to addresses 0000H and DIV_FLAG was not set by the type 0 interrupt-servIce
0002H to get the IP and CS values for the start of procedure, then a Jump is made to the MOV IBXLAL
BAD_DIV. the procedure we wrote to service a type 0 instruction. This instruction copies the result of the
interrupt. It will then execute the HAD_DIV procedure. division in AL to the memory location in SCALED_VAL-
Now let's look at the procedure in Figure 8-4b and see UES pointed to by BX. If BAD_DIV_FLAG was set by a
how it works, type 0 interrupt, then 0 is put in the memory location
The BAD_DIV procc. iure starts h ietflng the assem- In SCALED_VALUES and a Jump will be made to the
bler know that the nanc' BAD_DI\,., t"LAG represents a MOV BAD_DIV_FLAG,00 instruction, which resets the
variable of type byte nd that this variable Is thtined in BAD_DIV_FLAG. Since this Jump passes over the MOV
a segment called DA"A In -a . me other tEXTRr4 assembly ( T3XJ.AL Instruction, the invalid result of the division
module. We also tell the se. 'r that the label BAD_ will not be copied into one of the locations in
DIV should be made available l& ther assembly modules SCALED_VALUES.
(PUBLIC). After putting the scaled value or 0 in the array and
Next, we declare a logical seg'et.0 called INT_PR')(. resetting the flag. we get ready to operate on the next
We could have put this procedure in the segment CODE input value. The ADD Sl.02 instruction increments SI
with the maInline program. Howeer, in system pro- by 2 so that it points to the next 16-bit value in
grams where there are many interrupt-service procc. INPUT_VALUES. The INC BX Instruction points BX at
dures, a separate segment is usually set aside for them. the next 8-bit location in SCALED_VALUES. The LOOP
The statement BAD_DIV PROC FAR identifies the actual instruction after these automatically decrements the CX
start of the procedure and tells the assembler that both register by 1 and, if CX is not then 0, causes the 8086
the CS and IP values for this procedure must be saved. to Jump to the specified label. NEXT.
Now, an Important operation to do at the start of any The preceding section has shown you how to set U
Interrupt-service procedure Is to push on the stack any an interrupt-pointer table, how to write an Interrupt-
registers that are used in the procedure. You can then service procedure, and how the 8086 responds to a type
restore these registers by popping them off the stack 0 interrupt. Now we can discuss some of the other types
just before returning to the Interrupted program. The of 8086 Interrupts.
interrupted program will then resume with its registers
as they were before the interrupt. In the procedure in 8086 Interrupt Types
Figure 8-4b, we saved AX and DS. Since we use the
same data segment, DATA, In the mainline and in the The preceding sections used the type 0 Interrupt as an
procedure, you may wonder why we saved DS. The point example of how the 8086 interrupts function. In this
is that an interrupt-service procedure should be written section we discuss In detail the different ways an 8086
so that it can be used at any point In a program. By can be Interrupted and how the 8086 responds to each
saving the DS value for the Interrupted program. this ol these Interrupts. We discuss these in order. starting
interrupt-service procedure can be used in a program with type 0, so that you can easily find a particular
section (hat does not use DATA as Its data segment. discussion when you need to refer back to it. However,
The ASSUME statement tells the assembler the name as you read through this section. you should not attempt
of the segment to use as a data segment. but remember to learn all the details of all the interrupt types at once.

212 CHAPTER EIGHT


Read through all the types to get an overview, and are: Set the trap flag. write an interrupt-service proce-
then focus on the details of the hardware-caused NMI dure which saves all registers on the stack, where they
interrupt, the software interrupts produced by the INT can later be examined or perhaps displayed on the CRT.
Instruction, and the hardware interrupt produced by and load the starting address of the type 1 interrupt-
applying a signal to the INTR input pin. service procedure into addresses 00004H and 00006F1,
The actual single-step procedure will depend very much
DIVIDE-BY-ZERO INTERRUPT-TYPE 0 on the system on which it Is to be implemented. We do
As we described in the preceding section, the 8086 will not have space here to show you the different ways to
automatically do a type 0 Interrupt if the result of a DIV do this. We will. houever. show you how the trap flag Is
operation or an IIDIV operation is too large to fit in the set or reset, because this is somewhat unusual,
destination register. For a type 0 interrupt, the 8086 The 8086 has no instructions to directly set or reset
pushes the flag register on the stack, resets IF and TF. the trap flag. These operations are done by pushing the
and pushes the return address (CS and IP) on the stack. flag register on the stack, changing the trap flag bit to
It then gets the CS value for the start of the interrupt- what you want it to be, and then popping the flag
service procedure from address 00002H in the Interrupt. register back off the stack. Here Is the instruction
pointer table and the IP value for the start of the sequence to set the trap flag.
procedure from address 00000H in the interrupt pointer-
table. PUSHF Push flags on stack
Since the 8086 type 0 response is automatic and MOV BP,SP Copy SP to BE' for use as index
cannot be disabled In any way, you have to account for OR WORD PTRIBP+0J,O100H
it in any program where you use the DIV or IDly Set TF bit
instruction. One way is to in some way make sure the POPF Restore flag register
result will never be too large for the result register. We
showed one way to do this in the example program in To reset the trap flag. simply replace the OR instruction
Figure 5-27b. In that example, you may remember, we in the preceding sequence with the instruction 4ND
first make sure the divisor is not zero, and then we do WORD PTR{BP+Ol. OFEFFI-I.
the divisioji In several steps so that the result of the
division will never be too large. NOTE: We have to use tBP + 0) because BR cannot
be used as a pointer without a displacement. See
Another way to account for the 8086 type 0 response
Figure 3-8.
is to simply write an interrupt-service procedure which
takes the desired action when an invalid division occurs.
The trap flag is reset when the 8086 does a type I
The advantage of this approach is that you don't have
interrupt, so the single-step mode will be disabled during
the overhead of a more complex division routine in your
the interrupt-service procedure.
mainline program. The 8086 automatically does the
checking and does the interrupt procedure only if there NONMASK4 BLE INTERRUPT—TYPE 2
is a problem.
The 8086 will automatically do a type 2 interrupt
SINGLE-STEP INTERRUPT—TYPE 1 response when it receives a low-to-high transition on its
NMI input pin. When it does a type 2 interrupt, the 8086
In a section of Chapter 3 on debugging assembly lan- will push the flags on the stack, reset TF and IF.
guage programs, we discussed the use of the single-step and push the CS value and the IP value for the next
feature found in some monitor programs and debugger instruction on the stack, It will then get the CS value
programs. When you tell a system to single-step. it will for the Start of the type 2 interrupt-service procedure
execute one instruction and stop. You can then examine from address 0000A}l and the IP value for the start of
the contents of registers and memory locations, If they the procedure from address 00008H.
are correct, you can tell the system to goon and execute The name nonmaskable given to this input pin on
the next instruction. In other words, when in single. the 8086 means that the type 2 interrupt response
step mode, a system will stop after it executes each cannot be disabled (masked) by any program instruc-
instruction and wait for further direction from you. The tions. Bccause this input cannot be intentionally or
8086 trap flag and type I interrupt response make it accidentally disabled, we use it to signal the 8086 that
quite easy to Implement a single-step feature In an 8086- some condition in an external system must be taken
based system. care of. We could, for example, have a pressure sensor
If the 8086 trap flag Is Set, the 8086 will automatically on a large steam boiler connected to the NMI input. If
do a type I Interrupt after each instruction executes. the pressure goes above some preset limit, the sensor
When the 8086 does a type I interrupt. it pushes the will send an interrupt signal to the 8086. The type 2
flag register on the stack, resets TF and IF. and pushes interrupt-service procedure for this case might turn off
the CS and IP values for the next instruction on the the fuel to the boiler, open a pressure-relief valve, and
slack. It then gets the CS value for the start of the type sound an alarm.
I interrupt-service procedure from address 0000611 and Another common use of the type 2 interrupt is to save
it gets the IP value for the start of the procedure from program data in case of a sjstem power failure. Some
address 00004H. external circuitry detects when the ac power to the
The tasks Involved In implementing single stepping system fads and sends an interrupt signal to the NM!

808k INTERRUPTS AND INTERRUPT APPLICATIONS 213


Input. Because of the large filter capacitors In most overflow error in a program. One way is to put the
power supplies, the dc system power will remain for Jump II Overflow instruchon, JO. immediately after the
perhaps 50 ms after the ac power is gone. This is arithmetic instruction. If the overflow (lag is set as a
more than enough time for a type 2 interrupt-service result of the arithmetic operation. execution will Jump
procedure to copy program data to some RAM which has to the address specified in the JO instruction. At this
a battery backup power supply. When the ac power address you can put an error routine which responds
returhs. program data can be restored from the battery- to the overflow in the way you want.
back'd RAM, and the program can resume execution The second way of detecting and responding to an
where it left off. A practice problem at the end of the overflow error is to put the Interrupt on OvefJlow instruc-
chapter gives you a chance to write a simple procedure tion. INTO, immediately after the arithmetic instruction
for this task. in the program. lithe overflow flag Is riot set when the
8086 executes the INTO Instruction, the Instruction will
simply function as an NOP. However, if the overflow flag
B:AKpOINT INTERRUPT-TYPE 3 is set, indicating an overflow error, the 8086 will do a
The type 3 interrupt is produced by execution of the type 4 Interrupt after It executes the INTO instruction.
tNT 3 instruction. The main use of the type 3 interrupt When the 8086 does a type 4 interrupt. It pushes the
Is to Implement a breakpoint (unction in a system. flag register on the stack, resets TF and IF, and pushes
the CS and IP values for the next Instruction on the
In Chapter 4 we described the use of breakpoints in
debugging assembly language programs. We hope that stack. It then gets the CS value for the start of the
you have been using them in debugging your programs. interrupt-service procedure from address 00012H and
the IP value for the procedure from address 0001OH.
When you insert a breakpoint, the system executes the
instructions up to the breakpoint and then goes to the Instructions in the interrupt-service procedure then
breah procedure. Unlike the single-step feature, perform the desired response to the error condition. The
which stops execution after each instruction, the procedure might, for example set a "flag" in a memory
breakpoint feature executes all the Instructions up to location as we did in the BAD_DIV procedure in Figure
the inserted breakpoint and then stops execution. 8-4b. The advantage of using the INTO and type 4
When you tell most 8086 systems to Insert a breakpoint Interrupt approach is that the error routine is easily
at some point in your program, they actually do it accessible from any program.
by temporarily replacing the Instruction byte at that
address with CCH, the 8086 code for the INT 3 instruc-
SOFTWARE INTERRUPTS-TYPES 0 THROUGH 255
tion. When the 8086 executes this INT 3 instruction. It
pu:hes the flag register on the stack, resets TF and IF, The 8086 INT instruction can be used to cause the 8086
pushes the CS and IP values for the next mainline to do any one of the 256 possible interrupt types.
..truction on the stack. The 8086 then gets the CS The desired interrupt type is specified as part of the
',alue of the startof the type 3 interrupt-service procedure instruction. The instruction INT 32, for example, will
from address 0000EH and the IP value for the procedure cause the 8086 to do a type 32 interrupt response. The
from address 0000CU. A breakpoint interrupt-service 8086 will push the flag register on the stack. reset TF
procedure usually saves all the register contents on the and IF. and push the CS and IP values of the next
stack. Depending on the system. it may then send instruction on the stack. It will then get the CS and IP
the register contents to the CRT display and wait for the values for the start of the interrupt-service procedure
next command from the user, or in a simple system It from the interrupt-pointer table In memory. The IP value
may just return control to the user. In this case an for any interrupt type Is always at an address of 4 times
Examine Register command can be used to check if the the interrupt type, and the CS value is at a location two
register contents are correct at that point In the program. addresses higher. For a type 32 interrupt, then, the IP
value will be put at 4 x 32 or 128 decimal (SOH). and
the CS value will be put at address 82H in the interrupt-
OVERFLOW INTERRUPT-TYPE 4 vector table.
The 8086 overflow flag (OF) will be set if the signed Software interrupts produced by the INT instruction
result of an arithmetIc operation on two signed numbers have many uses. In a previous section we discussed the
is too large to be represented In the destination register use of the INT 3 instruction to insert breakpoints
or memory location. For example, if you add the 8-bit in programs for debugging. Another use of software
signed number 01101 100 (108 decimal) and the 8-bit interrupts is to test various interrupt-service proce-
signed number 01010001 (81 decimal), the result will dures. You could, for example. use an INTO instruction
be 10111101 (189 decimal). This would be the correct to send execution to a divide-by-zero Interrupt-service
result if we were adding unsigned binary numbers, but procedure without having to run the actual division
it is not the correct signed result. For signed operations. program. As another example, you could use an INT 2
the I in the most significant bit of the result indicates instruction to send execution to an NM! interrupt-
that he result is negative and in 2's complement form. service procedure. This allows you to test the NMI
The result. 10111101. then actually represents –67 procedure without needing to apply an external signal
decimal, which Is obviously not the correct result for to (he NMI input of the 8086. In a later section of the
adding + 108 and ^89. chapter. we show an example of another important
There are two major ways to detect and respond to an application of software interrupts.

214 CHAPTER EIGHT


INTERRUPT AND
TYPE TO 8088
ADO DO lAO

INTERRUPT
IN PUTS


AOl 07 IR7
INTA tNT
INTA
IN TA

FIGURE 8-5 Block diagram showing an 8259 connected to an 8086.

procedure is to make sure that a signal on the INTR input


INTR INTERRUPTS—TYPES 0 THROUGH 255
does not cause the 8086 to interrupt itself continuously.
The 8086 INTR input allows some external signal to The INTR input is activated by a high level. In other
interrupt execution of a program. Unlike the NM! input, words, whenever the INTR input is high and INTR is
however, INTR can be masked (disabled) so that it enabled, the 8086 will be interrupted. If INTR were not
cannot cause an interrupt. If the interrupt flag (IF) is disabled during the first response, the 8086 would be
cleared, then the !N'FR Input is disabled. IF can be continuously interrupted and would never get to the
cleared at any time with the Clear Interrupt instruction, actual interrupt-service procedure.
CLI. If the interrupt flag is set, the INTRinput will be The IRET instruction at the end of an interrupt-service
enabled. IF can be set at any time with the Set Interrupt procedure restores the flags to the condition they 'were
in befort the procedure by popping the flag register off
instruction, STI.
When the 8086 is reset, the interrupt flag is automati- thestack. This will reenable the INTR Input. If a high.
cally cleared. Before the 8086 can respond to an Interrupt level signal is still present on the INTR input, It will
signal on its INTR input. you have to set IF with an STI cause the 8086 to be interrupted again. If you do not
Instruction. The 8086 was designed this way so that want the 8086 to be interrupted again by the same input
ports, timers, registers. etc., can be initialized before signal. you have to use external hardware to make sure
the INTR input Is enabled. In other words, this allows that the signal is made low again before you reenable
you to get the 8086 ready to handle interrupts before INTR with the STI instruction or before the IRET from
letting an interrupt in. just as you might want to get the INTR service procedure.
yourself ready in the morning with a cup of coffee before When the 8086 responds to an INTR interrupt signal.
turning on the telephone and having to cope with the Its response is somewhat different from its response to
other interrupts. The main difference is that for an INTR
interruptions it produces.
Remember that the Interrupt flag (IF) is also automati- interrupt the interrupt type is sent to the 8086 from
cally cleared as part of the response of an 8086 to an an external hardware device such as the 8259A priority
Interrupt. This is done for two reasons. First, it prevents Interrupt controller, as shown in Figure 8-5. We discuss
a signal on the INTR input from interrupting a higher. the 8259A in detail later in the chapter. but here's an
priority interrupt-service procedure in progress. How- introduction.
ever, if you want another INTR input signal to be able When an 8259A receives an interrupt signal on one of
to interrupt an interrupt procedure in progress. you can its IR inputs, it sends an interrupt request signal to the
reenable the INTR input with an STI Instruction at any INTR input of the 8086. If the INTR Input of the 8086
has been enabled with an STI instruction, the 8086 will
time.
The second reason for automatically disabling the respond as shown by the waveforms in Figure 8-6.
INTR input at the start of an INTR interrupt-service The 8086 first does two interrupt-acknowledge ma-

T T T T ITI T, j T3 1'

ALE _,[\
FROM 8086

INTA
F ROM 9086 TO\-_________.__' t_______f -
AO0-AD15 D.OAT

FIGURE 8-6 8086 interrupt-acknowledge machine cycles.

8086 INTERRUPTS AND INTERRUPT APPLICATIONS 215


chine cycles, as shown in Figure 8-6. The purpose of interru response is to clear IF. This disables the INTR
these two machine cycles is to get the interrupt type from input and prevents the INTR signal from interrupting
the external device. At the start of the first infrrrupt- the higher. priority type 0 interrupt-servIce procedure.
acknowledge machine cycle, the 8086 floats the data An IRET instruction at the end of the type 0 procedure
bus lines, AtO—ADl5, and sends out an interrupt- will restore the flags to what they were before the type
acknowledge pulse on its INTA output pin. This pulse 0 response. This will reenable the INTR input, and the
essentially tells the 8259A to "get ready." During the
8086 will do an INTR interrupt response. A similar
second interrupt-acknowledge machine cycle, the 8086
sequence of operations will occur if the 8086 Is executing
sends out another pulse on Its INTA output pin. In an INT or INTO instruction and an interrupt signal
response to this second INTA pulse, the 8259A puts the arrives at the INTR input.
interrupt type (number) on the lower eight lines of the As a second example of how this priority works.
data bus, where it is read by the 8086.
suppose that a rising-edge signal arrives at the NMI
Once the 8086 receives the interrupt type, it pushes input while the 8086 is executing a DIV instruction,
the flag register on the stack, clears TF and IF. and and that the division operation produces a divide error.
pushes the CS and IP values of the next instruction on Since the 8086 checks for internal interrupts before It
the stack. It then uses the type it read in from the checks for an NM! interrupt, the 8086 will push the
external device to get the CS and IP values for the flags on the stack, clear TF and IF, push the return
interrupt-service procedure from the interrupt-pointer
address on the stack, and go to the start of the divide
table In memory. The IP value for the procedure will be error (type 0) service procedure. However, because the
put at an address equal to 4 tImes the type number, and NM! Interrupt request is not disabled, the 8086 will then
the CS value will be put at an address equal to 4 times
do an NMI (type 2) interrupt response. In other words.
the type number pIus 2, Just as is done for the other
interrupts. the 8086 will push the flags on the stack, clear TF and
IF, push the return address on the stack. and go execute
The advantage of having an external device insert the
the NM! interrupt-service procedure. When the 8086
desired interrupt type is that the external device can fInishes the NMI procedure, it will return to the divide
"funnel" interrupt signals from many sources into the
error procedure, finish executing that procedure, and
lNTRpt pin on the 8086. When the 8086 responds then return to the mainline program.
with INTA pulses, the external device can send to the
To finish our discussion of 8086 interrupt priorities,
8086 the interrupt type that corresponds to the source let's see how the single-step (trap. or type 1) interrupt
of the Interrupt signal. As you will see later, the external fits in, If the trap flag is set, the 8086 will do a type I
device can also prevent an argument if two or more
interrupt response after every mainline instruction.
sources send interrupt signals at the same time.
When the 8086 responds to any Interrupt, however, part
of its response is to clear the trap flag. This disables the
PRIORITY OF 8086 INTERRUPTS
single-step function, so the 8086 will not normally
As you read through the preceding discussions of the single-step through the instructions of the interrupt-
different interrupt types, the question that may have service procedure. The trap flag can be set again in the
occurred to you is, What happens if two or more inter- single-step procedure if single-stepping is desired in the
rupts occur at the same time? The answer to this interrupt-service procedure.
question is that the highest-priority interrupt will be Now that we have shown you the different types of
serviced first, and then the next-highest-priority inter- 8086 Interrupts and how the 8086 responds to each, we
rupt will be serviced. Figure 8-7 shows the priorities of will show you a few examples of how the 8086 hardware
the 8086 interrupts as shown In the Intel data book. interrupts are used. Other applications of interrupts
Some examples will show you what these priorities will be shown throughout the rest of the book.
actually mean.
As a first example, suppose that the INTR Input
is enabled, the 8086 receives an INTR signal during
execution of a Divide instruction, and the divide opera- HARDWARE INTERRUPT APPLICATIONS
tion produces a divide-by-zero interrupt. Since the inter-
nal interrupts__such as divide error, INT, and lN'FO - Simple Interrupt Data Input
have higher priority than INTR, the 8086 will do a divide
One of the most common uses of interrupts Is to relieve
error (type 0) interrupt response first. Part of the type 0
a CPU of the burden of polling. To refresh your memory,
polling works as follows.
The strobe or data ready signal from some external
INTERRUPT PRIOR77 device is connected to an input port line on the micro-
DIVIDE ERROR INT n, INTO HIGHEST computer. The microcomputer uses a program loop to
NMI read and test this port line over and over until the data
INTR ready signal Is found lobe asserted. The microcompuier
[LE-STEP LOWEST then exits the polling loop and reads in the data from
the external device. Data can also be output on a polled
basis.
FIGURE 8-7 Priority of 8086 interrupts. (Intel
Corpora(,on) The disadvantage ol polled input or output is that
while the microcomputer is polling the strobe or data
216 CHAPTER EiGHT
ready signal, it cannot easily be doing other tasks. In Now let's look at the software considerations for this
systems where the microcomputer must be doing many interrupt example.
tasks, polling Is a waste of time, so interrupt input and The software considerations are very similar to those
output is used. In this case the data ready or strobe for the divide-by-zero example in a previous section. As
signal is connected to an interrupt input on the micro- shown in Figure 8-9a, p. 218, the mainline program for
computer. The microcomputer then goes about doing this example consists mostly of a walk through an
its other tasks until it is interrupted by a data ready initialization list. First, assuming that you are going to
signal from the external device. An interrupt-service read in the ASCII characters from the keyboard and put
procedure can read in or send out the desired data in a them in an array in memory, you need to set up a data
few microseconds and return execution to the inter- segment for the array, set up the array, and declare any
rupted program. The input or output operation then other variables you are going to use in the program. The
uses only a small percentage of the microprocessor's statement ASCII_POINTER OW OFFSET ASCILSTRING
time. in the data segment In Figure 8-9a sets aside a word
For our example here, we will connect the key-pressed location in memory and Initializes that location with
strobe to the NMI interrupt input of the 8086 on an SDK- the offset of the start of the array we declared to put the
86. The NMI Input is usually reserved for responding to ASCII characters in. In the procedure we get this pointer,
a power failure or some other catastrophic condition. use it to store a character, and Increment it to point to
However, since we are not expecting any catastrophic the next location in the array. Since this pointer is
conditions to befall our DK-86, we choose to use this stored in a named memory location, it can be accessed
input because it does not require an external hardware easily by the procedure, no matter when the interrupt
device to insert the interrupt type as does the INTR occurs in the mainline program. KEYDONE is a flag
input. which will be set by the interrupt procedure when 100
Sheet 2 of the SDK-86 schematics In Figure 7-8 shows characters have been read in and stored,
the circuitry normally connected to the NMI input. This Any interrupt response uses the stack, so next you
circuitry is designed so that you can produce an NM! need to set up a stack. Note that the PUBLIC and EXTRN
interrupt by pressing a key labeled INTR on the hex directives are used so that the mainline program and
keypad. When this key is pressed, the input of the the interrupt procedure can be in separate assembly
74LS 14 inverter will be made low, and the output of the modules.
inverter will go high. The low-to-high transition on In the code section of the mainline you need to
the NMI input causes the 8086 to automatically do an initialize the stack segment register, the stack pointer
NMI (type 2) interrupt response. register. and the data segment register. Finally, you
Figure 8-8 shows how we modified the circuitry for need to Initialize the Interrupt-vector table by loading
our example here. We removed R22, a 110-fl resistor, address 00008H with the IP value for the start of the
and C33. a 1-1iF capacitor, so that the keypad switch type 2 procedure, and address 0000AH with the CS
can no longer cause an interrupt. We then connected value for the start of the procedure.
an active low strobe line from an ASCII-encoded keyboard The HERE:JMP HERE instruction at the end of the
directly to the Input ofA2l, the 74LS14 inverter. When mainline program stimulates a complex mainline pro.
a key on the ASCII keyboard is pressed, the keyboard gram that the 8086 might be executing. The 8086 will
circuitry will send out te ASCII code for the pressed execute this instruction over and over until an interrupt
key on its eight parallel data lines and it will assert the occurs. When an interrupt occurs, the 8086 will service
key-pressed strobe line low. The key-pressed strobe going the interrupt and then return to execute the HERE:JMP
low will cause the NMI input of the 8086 to be asserted HERE instruction over and over again until the next
high. This will cause the 8086 to do a type 2 interrupt. interrupt. Now let's consider the interrupt procedure.
The algorithm for the interrupt procedure can be
simply stated as

ASCII PORT
KEYBOARD FFF8H 8086 IF 100 characters not read THEN
Read character from port
I ool Ioo I IADO
Mask parity bit
8255 Put character irs array
P2A ________ Increment array pointer
Decrement character count
07 A07
Return
KP ELSE Return

Note that we used an IFTHENELSE structure rather


than a WHILE not 100 characters DO structure, because
S2
we want Only one character to be read in for each call of
-I- the procedure.
rO —
.1. INTR Figure 8-9b, p. 219, shows the assembly language
program for the Interrupt . servlce procedure. After saving
FIGURE 8-8 Circuit modifications for SDK-86 N'1I input. AX, 9X. CX. and DX on the stack, we check to see if all

8086 INTERRUPTS AND INTERRUPT APPLICATIONS 217


;8086 PROGRAM F8-09A.AS14
2 ;ABSTRACT .: Mainline of program to read characters frs a keyboard
3 The maintine of this program initializes the interrupt
4 table with th, address of the procedure that reads
5 characters fra a keyboard oc an interrupt basis.
6 ;PORTS : Uses none in mainline. Uses FFF8H in procedure
7 ;REGISIERS : Uses CS,DS,SS,(S,SP,AX
8 ;PROCEDURES: Uses KEYBOARD
9 Link mainline F8-0A.O8J with procedure F8'098.OSJ
10
11 0000 DATA SEGMENT WORD PUBLIC
12 0000 64(00) ASCIISTRIMG 09 100 DUP(0) Store for characters
13 0064 0000r ASCII_POINTER OW OFFSET ASCII_STRING Pointer to ASCII_STRING
14 0066 64 CNARCNT OB 100 Read 100 characters
15 0067 00 KEYDOWE OB 0 =1 if characters alt read
16 0068 DATA ENDS
17
18 0000 STACK_SEC SEGMENT
19 0000 64*< 0000) OW 100 DUP (0) ;'Set up stack of 100 words
20 TOP_STACK LABEL WORD Pointer to top of stack
21 0008 STACK_SEC ENDS
22
23 PUBLIC ASCII POINTER, CHARCNT, KEYDOME Make available to other modules
24 EXTRN KEYBOARD:FAR Procedure in another asseity module
25
26 0000 C00E SEGMENT WORD PUBLIC
27 ASSUME CS:C00E, DS:DATA, SS:STACK_SEG
28 0000 58 0000s
START: NOV AX, STACK_SEC Initialize stack segment register
29 0003 8€ DO NOV SS, AX

30 0005 BC OOC8r NOV SP, OFFSET TOP_STACK ; Initialize stack pointer
31 0008 B8 0000s NOV AX, DATA Initialize data segment register
32 0008 8€ 08 NOV DS, AX
33 ;Store the address for the KEYBOARD routine at address 0000:0008
34 ;Address 00008-00005 is wflCre type 2 interrupt gets interrupt
35 ;service procedure address. CS at 0000A & 0000B, IP at 00008 & 00009
36 0000 B8 0000 NOV AX, 0000
37 0010 8€ CO NOV ES, AX
38 0012 26: C7 06 000A 0000s NOV WORD PTR ES:000AH, SEC KEYBOARD
39 0019 26: C7 06 0008 0000e NOV WORD PTR ES:0008H, OFFSET KEYBOARD
40 ;Siim.ilate larger program
41 0020 ES FE HERE: JNP HERE
42 0022 CXE ENDS
43 END
(a)

FIGURE 8-9 Reading characters from an ASCII keyboard on interrupt back.


(a) Initialization and mainline. (See also next page.)

.
characters ha,Ye been read, If CHARCNT Is 0, then Using Interrupts for Counting and Timing
we Just pop the regIsters and return to the mainline
program. If CHARCNT Is not 0, we copy the array pointer
COUNTING APPLICATIONS
from Its named memory location, ASCII_POINTER, to
BX. We then read In the ASCII character from the port As a simple example of the use of an interrupt Input for
that the keyboard Is connected to and mask the parity counting, suppose that we are using an 8086 to control
bit of the ASCII character. The MOV {BXI,AL Instruction a printed . clrcult-board . maklng machine In our comput.
next copies the ASCII character to the memory location erized electronics factory. Further suppose that we want
pointed to by BX. To get the poInter ready for the read to detect each finished board as It comes Out ol the
and store operation, we Increment the stored pointer machine and to keep a count of finished boards so that
with the INC ASCII_POINTER Instruction. Finally, we we can compare this count with the number of boards
restore DX, CX. BX, and AX, and return to the mainline fed in. This way we can determine if any boards were
program. lost In the machine.
Sitting In a HEREJMP HERE loop waiting for an To do this count on an interrupt basis. all we have to
Interrupt signal may not seem like much of an Improve. do is detect when a board passes out of the machine
mcnt over polling the key . pressed strobe. However, in a and send an interrupt signal to an interrupt Input on
more realistic program, the 8086 would be doing many the 8086. The interrupt-service procedure [or that Input
other tasks between keyboard interrupts. With polling. can simply increment the board count stored in a named
the 8086 would not easily be able to do this. memory location.

218 CHAPTER EIGHT


;8086 PROCEDURE F8-098.ASM catted by program F8-09A.ASM
2 ;ABSTRACT : 1'!OCEDURE KEYBOARD
3 This procedure reads in ASCII! characters frii an
4 encoded keyboard on an interrupt basis and stores them
5 in a buffer in meery.
6 ;DESTROYS : Nothing
7 ;PORTS : Uses input port FFF8H for the keyboard input.
8
9 0000 DATA SEGMENT RD PUBLIC
10 EXTRN ASCII_POINTER:WORD, CHARCNT:BYTE. KEYDOIIE:BYTE
11 0000 DATA ENDS
12
13 PUBLIC KEYBOARD
14
15 0000 C00E SEGMENT PURL IC
16 0000 KEYBOARD PR FAR
17 ASSIJ4E CSCE, DS:DATA
18 0000 FR STI Enable 8086 IIITR so higher priority
19 interrupts can be recognized
20 0001 50 PUSH AX Save registers used
21 0002 53 • PUSH BX
22 0003 51 .PUSH CX
23 0004 52 PUSH OX
24 0005 80 3E 0000e 00 CMP CHARCNT, 00 See if alt characters read in
25 000A 74 23 JZ EXIT Leave procedure if att done
26 000C 88 1E 0000e NOV BX. ASCII_POINTER Get pointer to buffer
27 0010 BA FFF8 NOV DX, OFFF8H Point at keyboard port
28 0013 EC IN Al, DX Read in ASCIF code
29 0014 24 7F AND AL, 7FH Mask parity bit
30 0C16 88 07 NOV EBXI, AL Write character to buffer
31 0018 FE 06 0000e INC ASCII_POINTER Point to next buffer Location
32 OO1C FE OE 0000e DEC CHARCNT Reduce character co4x%t
33 0020 7508 JNZ NOTDOWE If 100 chars mt read, cLear carry
34 0022 Co oo 00000 01 NOV KEYDONE, 01 etse Set fag to indicate done
35 0027 ER 06 90 .JMP EXIT
36 002A CO 06 0000e 00 NOTOONE: NOV KEYDONE, 00 More characters to read so zer flag
37 OO2F 5A EXIT: POP OX Restore registers
38 0030 59 POP CX
39 0031 5B POP BX
40 0032 58 POP AX
41 0033 CF IRET Return to interrupted program
42 0036 KEYBOARD ENOP
43 0034 C00E ENDS
44 END

(b)
FIGURE 8-9 (continued) (b) Interrupt-service procedure.

To detect a board coming out of the machine, we use an response. As we mentioned before, all the type 2 inter-
infrared LED, a phototransistor. and two conditioning rupt-servIce procedure has to do in this case Is incremel:t
gates. as shown In Figure 8-10, p. 220. The LED is the board count in a named memory location and return
positioned over the track where the boards come Out, to running the machine. This same technique can be
and the phototransistor Is positioned below the track. used to count people going into a stadium, cows coming
When no board Is between the LED and the phototransis. in from the pasture, or Just. about anything else you
tor, the light from the LED will strike the phototransistor might want to• count.
and turn it on. The collector of the phototransistor will
then be low, as will the NMI input on the 8086. When a
TIMING APPLICATIONS
board passes between the.LED and the phototransistor.
the light will not reach the phototranststor. and it will In Chapter 4 we showed how a delay loop could be used
turn off. Its collector will go high, and so will the signal to set the time between microcomputer operations. In
to the NMI input of the 8086. The 74LS14 Schmitt the example there, we used a delay loop to take in data
trigger inverters are necessary to turn the slow-risetime samples at 1-ms Intervals. The obvious disadvantage of
signal from the phototransistor collector into a signal a delay loop Is that while the microcomputer is stuck in
which meets the risetine requirements of the NMI input the delay loop, it cannot easily be doing other useful
on the 8086. work, in many cases a delay loop would be a waste
When the 8086 receives the low-to-high signal on Its of the microcomputers valuable time. so We USC an
NMI input. it will automatically do a type 2 interrupt interrupt approach.

- 30 8086 INTERRUPTS AND INTERRUPT APPlICATIONS 219


+5 V I r- t a I. i
Interrupt Punter Table
•5V
Stack and Stack seyserrt Pointer
1kU Data Segment
Seconds count to 240 decimal
620 Wait br Irsterrutst
?4LS14 74LS14
Ii)

INFRARED Save Registers


LED Decrement Seconds Count
IF Secondt Count 0 THEN
Relc++rd Seconds count itb 240 decinal
Call pH read procedure
BOARD PHOTOTRANSISTOR Restore registers
Ret'..n to Mainline
FIGURE 8-10 Circuit br optcaIly detecting presence of ELu Restore registers
Return to Mainline
an object.
lb I

FIGURE 8-2 Algorithm for p1-1 read at 4-mm intervals.


Suppose, for example, that in o'.r 8086-controlled
(a) Initialization and mainline. (b) Interrupt.service
printed-circuit-board-making machine we need to check
procedure.
the pH ol a solution approximately every 4 mm, If we
t.sed a delay loop to count off the 4 mm, either the 8086
wouldn't be able to do much else or we would have some for the NMt interrupt. In this procedure we dccrement
difficult calculations to figure out at what points in. the the seconds count in the named memory location and
program to go check the pH. test to see if the count is down to zero yet. If the count
To solve this problem all we have to do Is connect a is zero. we know that 4 mm have elapsed, so we reload
s.mple 1 -Hz pulse source to an interrupt input, as shown the seconds count memory location with 240 and call
in Figure 8-Il. ThIs 555 timer cIrcuit is not very the procedure whici reads the pH of the solution and
+ccurate, hut it is Inexpensive, and It is good enough tal'es appropriate action if the pH is not correct. If the
tar this application. The 555 (liner will send an interrupt seconds count is not zcro, execution simply returns to
signal to the 8086 NM! input approximately once every the mainline program until the next interrupt from the
second. An Interrupt procedure Is used to keep a count or froru some other source occurs. The advantage
of how many NM! interrupts have occurred. This count of Itt's interrupt approach is that the niterrupt-service
s qual to the number of seconds that have passed. pmncedure takes only a few microsecm,nds of the 8086's
'o help you visuahze how this works Figure 8-12 tmi'e once ever/ second. The rest of the time the 8086
chews the algorithm for this rnai&ine and procedure. is hce lu run tue mainline program.
In the mainline we set up stack aad 7ata segments. In
the data segment, we et a.dde a rneino!y location for USING AN INTERRUPT TO PRODuCE
the seconds count and initialize that location to the A rEAL-TlM CLOCK
number of seconds that we want to count off. In this Another application using a 1-liz interrupt input might
case we want 4 mm, which is 240 decimal or FOH be to generate a real-time clock of seconds, minutes,
seconds. Then we InitIalize the data segment register. and hours, The time from this clock can then be
stack segment register, and stLch pointer register as displayed and/or printed out on tlmecards. etc. To
before.
generate the clock, a I-Hz signal is applied to an Inter-
Each time the 8086 recei.es art. interrupt from the rupt input. A seconds count, a minutes count, and
55 timer, It executes the Interru f-service procedure art hours count are kept irs three successive memory
locations. When an interrupt occurs, the seconds count
is incremented by 1. If the seconds count is not equal
+5 V
to 60, then execution is simply returned to the mainline
pi-ograul. If the seconds count is equal to 60. then the
100 kS 8086
seconds count is reset to 0 and the minutes count is
Incremented by 1. lIthe minutes count is not 60. then
execution is simply returned to the mainline. If the
470 kO minutes count is 60. then the minutes count is reset to
NMI 0 and the hours count is Incremented by 1. If the hours
count is not 13. then execution is simply returned to
the mainline. If the hours count is equal to 13, then it
is reset to I and execution is returned to the mainline,
A problem at the end of the chapter asks you to write
the algorithm and program for this real-time clock.
The interrupt-service nsutine for the real-time clock
FIGURE 8-11 inexpensive 1-Hz pulse source for interrupt can easily be modified to also keep track of other time
timing. measurements such as the 4-mm timer shown in the

220 CHAPTER EIGHT


preceding example. In other words, the single interrupt- Basic 8253 and 8254 Operation
service routine can be used to keep track of several
The Intel 8253 and 8254 each contain three 16-bit
different time intervals- By counting a different number
counters which can be programmed to operate in several
of interrupts or applying a different frequency signal to
different modes. The 8253 and 8254 devices are pin-for-
the interrupt input, this technique can be used to time
pin compatible, and they are nearly identical in function.
many dlifr-rent tasks in a microcomputer system.
The major differences are as follows:

GENERATING AN ACCuRATE TIME BASE 1. The maximum Input clock frequency for the 6253
FUR TIMING INTERRUPTS is 2.6 MHz: the maximum clock frequency for the
The 555 timer that we used for the 4-miri timer tust 8254 ts 8MHz (10 MHz for the 8254-2).
described was accurate enougn for that application, but
2. The 8254 has a read-bock feature which allows you
for many applications--such as a real-time clock-'it is
to latch the count in all the counters and the status
not. For more precise timing, we uauallv use a signal
of the counter at arty point. The 8253 does not have
derived from a crystal-controlled oscillator. The proces.
this read-back feature.
sor clock signal is generated by a crystal-controlled
oscillator. so ft is stable. bu'. thIs signal is onsiously too
To simplify reading of this section. we will refer only to
high in lr . 'qucncy to drive a processor interrupt input the 8254. However, you can assume that the discussion
directly. The solution is to divide the clock signal down
also applies to the 8253 except where we specifically
with an eternal counter device lottie desed frequency
state otherwise.
for the interrupt input. Most microcomputer manu 1ac- As shown by the block diagram of the 8254 In Figure
turers have a compatible device hich can be pro- 8-13. the device contains three 16-bit counters. in some
gramrncd with instructionS o dIvide air Input frequency
ways these counters are similar to the TTL presettable
by any desired number. Besides acting as programmable
counters we reviewed in Chapter 1. The big advantage
frequency dividers, these devices have many lrrportant
of these counters, however, is that you can load a count
uses in microcomputer systems. Thereflire. the next
in them, start them, and stop them with instructions
section describes how art Intel 8251 Programmable
In your program. Such a device is said to be software-
Counter operates. how an 8254 can easil y be added to programmable. To program the device, you send count
an SDK-86 board, arid how an 8254 is used in a variety
bytes and control bytes to the device just as you would
of Interrupt applications. Also in the next section. we
send data to a port device.
use the 8254 discussion to show y ou the general proce- If you look along the left side of the block diagram in
dure [or initializing any of the progi ammable peripheral
Figure 8-13. you will see the signal lines used to Interface
devices we discuss in later chapters.
the, device to the system buses. A little later we show
how these are actually connected in a real system. The
main points for you to note about the 8254 at the
moment are that it has an 8-bit in'terface to the data
8254 SOFTWARE-PROGRAMMABLE bus, it has a CS input which will be asserted by an
TIMER/COUNTER
hecause of the many tasks that they can be used tar in
microcomputer systems. prograinniabte timer/counters
I.—CLKO
are very important for you to learn about. As you read DATA
through the following sections, pay particular attention
to the applications of this device in systems and the
general procedure for initializing a programmable device
BUS
BUFFER
I I
0
I-
COUNTERI.._.GATEO
OUT 0

such a.s the 8254. Read lightly through the discussions


of the different Counter modes to become aware oi the
types of problems that the device can solve for you. Later.
when y ou have a specite problem to solve, you can dig
into the details of these discussions.
READ/ I cOUNTER
ER
CLK I
GATE I
LOGIC OUT1
Another important point to make to you here ithat
the discussions of various devices throughout the rest of
this book are not Intended to replace the manufacturers
data sheets for the devices. Many of the programmable
I'.-'- CUt 2
peripheral devices we discuss are so versatile that each CONTROL H I
reoutres aknost a small book to describe all the details WORD COUNTERLGATE2
of it operations The discussions here are intended to REGISTER r'i
I-.. OUT 2
introduce you to the devices, show you what they can
be used for, and show you enough details about them
that you can do some real jobs with them. After you
become familiar with the use of a device In some simple
applications, you can read the data sheets to learn FIGURE 8-13 8254 internal block diagram. (Intel
further 'bells and whistles" that the devices have. Corporation)

8086 INTERRUPTS AND INTERRUPT APPLICATIONS 221


r NUMBER
JACKNUMBEII +5 +5V 4-5V

A15 1
3433 vc SP/EN V GND
3233 P14 2 15 1 1
A13 3 80
230.J3 7 AO Vt
j1 74LS30 I 181 19

26J3 TT_2P
j.___ 8 I
HY21
12
11
10
DO
01
182
183
20
21
11
02 184 22
22)3 A9 10 8 23
03 185
20J3 V6 04
2433;74Ls2: 186 24
M,10 6 25
V7 D5 IA)
44J3
06 12
74 IS 138 CASO 13
18J3 Al D7
3 CASt 15
1 6J3 IIII - Th__!J G 1 I
6 2 - CAS2
I 4J3 --___-cf'
6 - 17 +5V
Afl 321 INTA INT
433
1233 -
A4 8259A#1 1 28

-- Ill
CS lAB
6J3 27 19
PB IR1
231
00 182 20
431 10
183 21
8J1-- 9 22
02 1R4
831
8 03 IRS 23
10J1
04 186 24
1W 6 25
05 1R7
1431 5 II
06
tail CASO 12
D7
CASt13
4&13- 2 -- CAS2 15
WA
26
I NT INT 17
3831 - 8259A$t2
A2
8J3 - SP/ENGN0
+5 V
24 J6J,4
2:11- Vcc I
— 1WA I
22,— 19
—lAD CIKOI-
3231 - _!J GATEOLJJ +5 V
3Wt2i 21 lic
-f 06 OUTOI-
2BJ12! I
-D5
26J1 41 ItS
—104 CLK1I-
2431 -JD3 GATE1L!i +5 V
2231 !1 02 0UTlL!
2031 7, I
—101 I
tail 81 118
H D0 CLK2I-
19. 116
—fAD GATE2I- +5 V
1 Ii?
•— CS OUT2
201 8254
741S30 AND 74LS27 1A1
V PIN 14 GND
GND = PIN I 112

FIGURE 8-14 Circuit showing how to add an 8254 and 8259A(s) to an SDK-86 board.

address decoder when the device is addressed, and it The right side of the 8254 block diagram in Figure
has two address Inputs, AO and Al. to allow you to 8-13 shows the counter inputs and outputs. You can
address one of the three counters or the Control word apply a signal of any frequency from dc to 8MHz to each
register in the device, of the counter clock inputs, labeled CLK in the diagram.
222 CHAPTER EIGHT
The GATE input on each counter allows you to start or 8-15 shows the system base addresses that will enable
stop that Counter with an external hardMre signal. If each of the 74LS 138 Y outputs. As you will see a little
the GATE input of a counter is high (1), then that later, system address lines Al and A2 are used to select
Counter is enabled for counting. If the GATE input is internal parts of the 8254 and 8259A.
low, the Counter is disabled. The output signal from We connected AO to the C input so that half of the Y
each Counter appears on its OUT pin. Now let's see how outpits will be selected by even addresses and half of
a programmable peripheral device such as the 8254 is the Y outputs will be selected by odd addresses. We did
connected in a system. this so that loading on the two halves of the data bus
will be equal as we add peripheral devices such as the
8254 and 8259A. To see how this works, note that the
System Copnedions for an 8254 Timer/Counter peripheral devices have only eight data lines. For an
8254 is a very useful device to have in a microcom- odd-addressed device we connect these data Lines to the
puter system, but, in order to keep the cost down, the upper eight system data lines, and for an even-addressed
SDK-86 was not designed with one on the board. Figure device, we connect these to the lower eight system data
8-14 shows the circuit connections for adding an 8254 lines. By alternating between odd- and even-selected
Counter and an 8259A Priority interrupt Controlier to outputs as we add peripheral devices, we equalize load-
an SDK-86 board. We discuss the 8259A in a later ing on the bus,
section of this chapter. As shown by the truth table in Figure 8-15. the
If you use wire-wrap headers for connectors Ji and system base address of the added 8254 is FFOIH. Other
J3 on an SDK-86 board, the circuitry shown can easily connections to the 8254 are the system RD and WR lines
be wire-wrapped on the prototyping area of the board. used to enable the 8254 for reading or writing: eight
Install th" WALT-state jumper to insert one WAIT state. data lines, used to send control bytes. status bytes, and
As explained in Chapter 7, a WALT state is needed count values between the CPU and the 8254: and system
because of the added delay of the decoders and buffers. address lines Al and A2, used to select the control
The 74LS 138 in Figure 8-14 is used to produce chip register or one of the three counters In the 8254 , Now
select (CS) signals for the 8254, the 8259A. and any that you see how an 8254 is connected in a system, we
ether L'O devices you might want to add. Let's look first will show you how to initialize an 8254 to do some useful
at the cIrcuitry around this device to determine the work for you.
system base address which selects each device.
In order for any of the oups of the 74LS 138 to be
asserted, the Gi, G2A, and G2B enable inputs must all Initializing an 8254 Programmable
be asserted The G1 Input will be asserted (high) if Peripheral Device
em address lines A5, A6, and A7 are all low. The
G2A input will he asserted (low) if System address lines When the power is first turned on. programmable periph-
A8 through Al5 are all high. As shown by the truth eral devices such as the 8254 are usually in undefined
table in Figure 8-15, these two inputs therefore will be states. Before you can use them for anything, you have
to initialize them in the mode you need for your specific
asserted for a system base address of FFOOH. The G2B
input of the 74LS138 will be asserted (low) if the M/lO application. initializing these devices is not usually
line is low, as It will be for a port read or write operation. difficult, but it is very easy to make errors if you do
Now, remember from Chapter 7 that only one of the not do it in a very systematic way. To initialize any
Y outputs of the 74LS 138 will ever be asserted at a time. programmable peripheral device, you should always
The output asserted is determined by the 3-bit binary work your way through the following series of steps.
code applied to the A. B, and C select inputs. Ii the
circuit in Figure 8-14. we connected system address line I. Determine the system base address for the device.
AO to the C input, address line A4 to the B Input, and You do this from the address decoder circuitry or
address line A3 to the A input. The truth table in Figure the address decoder truth table. From the truth table

Y OUTPUT SYSTEM BASE


A8-A15 A5-A7 A4 A3 A Al AO M/IO SELECTED ADDRESS DEVICE
1 0 0 0 X X 0 0 0 F F O 0 8259A#1
1 0 0 1 X X 0 0 F F 0 8 8259A #2
1 0 1 0 X X 0 0 2 F F 1 0
1 0 1 1 X X 0 0 3 F F 1 8
1 0 0 0 X X I 0 4 F F 0 1 8254
1 0 0 1 X X 1 0 5 F •F 09
1 0 1 0 X X I 0 6 F F 1 1
1 0 1 1 X X I 0 7 F F 1 9
ALL OTHER STATES NONE

FIGURE 8-15 Truth table for 741S138 address decoder in Figure 8-14.

8086 INTERRUPTS AND INTERRUPT APPLICATIONS 223


07 06 D5 04 03 02 Dl 00
Al AD SELECTS MO BCD
Sd SCO Awl AWO M2 Ml J
o 0 COUNTER 0
o I COUNTER 1
SC _SELECTCOUNfERI
I 0 COUNTER 2 Sd 5CC
I 1 CONI AOL WORD REGISTER
O 0 SELECTCOUNTERO
(t O 1 SELECT COUNTER I -

1 0 SELECTCOUNTER2 -
SYStEM ADDRESS 2254 PART 1 READ-BACK COMMAND SEE READ OPERATIONSi
1
F F 0 1 COUNTERO
F F 0 3 COUNTER1 RW .- READ/WRITE.
F F 0 5 COUNTER2 AWl RWO
F F 0 7 CONTROL RED COUNTER LATCH COMMAND (SEE READ
0 0 OPERATIONS)
(b)
O I READ/WAITE LEAST SIGNIFICANT BYTE ONLY.
FIGURE 8-16 8254 addresses. (a> Internal. (b) System 1 0 READ/WRITE MOST SIGNIFICANT BYTE ONLY.
- READ/WAITE LEAST SIGNIFICANT BYTE FIRST
I 1 THEN MOST SIGNIFICANT BYTE.
in Figure 8-15. the system base address of the 8254
In our example here Is FF011-I. M - MODE
M2 Ml MO
2. Use the device data sheet to determine the internal 0 MODE 0-' INTERRUPT ON TERMINAL. COUNT
O 0
addresses for each of the control registers, ports.
0 0 I MODE 1 - HARDWARE ONE-SHOT
timers, status registers. etc., in the device. Figure
8-l6a shows the internal addresses for the three X 1 0 MODE2-PuLSEGENERATOR
counters and the control word register for the 8254. X 1 1 MODE 3- SQUARE WAVE GENERATOR
AO in this table represents the AD input of the device. 1 0 0 MODE 4-SOFTWARE TRIGGERED STROBE
and Al represents the Al input of the device. Note 1 0 1 MODES-HAFIDWARETRIGGEREDSTROBE
in (he schematic in Figure 8-14 that system address
line Al Is connected to the AD input of the 8254, OCO:
and system address line A2 is connected to the Al
0[iINARY COUNTER 16-BITS
input. We could not use system address line AO as
BINARY CODED DECIMAL (BCD) COUNTER (4 DECADESt
oae of these because, as described before, we used
system address line AO as one of the inputs to the
NOTE: DON'T CARE BITS (Xl SHOULD BE 0 TO INSURE
address decoder. COMPATIBILITY WITH FUTURE INTEL PRODUCTS.
3, Add each, of the internal addresses to the system
base address to determine the system address of FIGURE 8-7 8254 control word formal. (Intel
Corporation)
each of the parts of the device. You need to do this
so that you know the actual addresses where you
have to send control words, timer values, etc. Figure each resulting half in two, and finally divide each
8-16b shows the system addresses for the three resulting quarter in two.) To help keep track of the
timers and the control register of the 8254 we added
meaning of each bit of a control word, write under
to the SDK-86 board. Note that the addresses all each bit the meaning of that bit. A little later we
have to be odd because the device is connected on show you how to do this br an 8254 control word.
the upper half of the data bus. Documentation of ih(s sort is very valuable when
4. Look in the data sheet for the device for the format you are trying to debug a program or modify an old
of the control word(s) that you have to send to program for sonic new applicalion.
the device to initialize it. For different devices.
6. Finally. send the control words) you have made up
incidentally, the control word(s) may he referred to to the control register address for the device. III (lie
as command words or mode words. To initialize the case of the 8254, you also have to sertd the starting
8254, you send a control word to the control register
count to each of the counter regislers.
for each counter that you want to use. Figure 8-17
shows the format for the 8254 control word.
Now that you have ati overview oi' the initialization
5. Construct the control word required tc initialize the process, let's take a closer look at how y ou do the lasI
device for your specific application. You copstruct two steps for an 8254.
this control word on a bit-by-hit basis. We have A separate control word must be sent for each counter
found it helpful to actually draw the eight little boxes that you want to use in the device. however, according
shown at the top of Figure 8-17 so that we don't to Figure 8-16a. the 8254 has onl y one control register
miss any bits, iAn easc way to draw Ihe eight boxes add less. The trick here is tha I tile COIl I ml words for all
is to draw a long rectangle. divide It ifl hail. divide Ihrcc counters arc .senl to the same address In the

224 CHAPTEk EIGHT


device. As shown in Figure 8-17. you use the upper 2 byte of the count ta the counter address. 'In a latet
bits of a control word to tell the 8254 which counter you paragraph we show an example of the instruction se-
want that control word to initialize. For example, if you quence to do this. In cases where you only want to load
are making up a control word for counter 0 in the 8254. a new value in the low byte of a counter, you can send
you make the SC! bit of the control word a 0 and the a control word with 01 in the RW bits and then send
SCO bit a 0. Later we will explain the meaning of the the new low byte to the counter. Likewise, if you want
read-back command, specified by a 1 in each of these to load Only a new high byte value in the counter, you
bits. can send a control word with 10 in the RW bits, and
The 16-bit counters In the 8254 are down counters. then send only the new high byte to the counter.
This means that the number in a counter will be You can read the number in one of the counters at
decremented by each clock pulse. You can program the any time. The usual way to do this is to first latch the
8.54 to Count down a loaded number in BCD (decimal) current count In some internal latches by sending a
or in binary. If you make the DO bit of the control word control word with 00 In the RW bits. Send another
a 0, then the counter will treat the loaded number as a control word with 01, 10. or 11 in the RW bits to specify
pure binary number. In this case the largest number how you want to read Out the bytes of the latched count.
that you can load in Is FFFFH. If you make the DO bit Then read the count from the counter address.
of thc contxol word a 1. then the largest number you As a specific example of initializing an 8254. suppose
can load in the countel is 99991-I, and the counter will that we want to use counter 0 of the 8254 in Figure
count a loaded number down in decimal (BCD). Actually, 8-14 to produce a stable 78.6-kHz square-wave signal
because of the way the 8254 counts, the "largest" for a UART clock by dividing down the 2.45'MHz PCLK
number you can load In foi both cases is 0000. but signal available on the SDK-86 board. To do this, we
thinking of FFFFH and 9999H makes it easier to remem- first connect the SDK-86 PCLK signal to the CLK input
ber the difference between the two modes. of counter 0 and tie the GATE input of the counter hIgh
Now let's take a brief look at the mode bits (M2, Ml-, to enable it for counting. 'l'o produce 78.6 kHz from 2.45
and MO) in the control word format in Figure 8-17. The MHz. we have to divide by 32 decimal, so this is the
binary number you put In these bits specifies the effect i'alue that we will eventually load Into counter 0. First.
that the gate Input will have on counting and the however, we have to determine the system addresses for
waveform that wIll be produced on th OUT pin. For the device, make up the control word for counter 0. and
example, if you specify mode 3 for a counter by putting send the control word.
Oil in these 3 bits, the Counter will be put in a square- As shown in Figure 8-16b, the system address for the
wave mode. In this mode, the output will be high for the control register of this 8254 is FFO7H. This Is where we
first half of the loaded Count and low for the second half will send the control word. For our control word we want
of the loaded count. When the count reaches 0, the to select counter 0, so we make the SC! and SCO bits
original count is automatically reloaded and the count- both 0's. We want the counter to operate in square-wave
down repeated. The waveform on the OUT pin In this mode. This is mode 3, so we make the mode bits of the
mode will then be a ?quare wave with a frequency equal control word 01 l.Since we want to divide by 32 decImal.
to the input clock frequency divided by the count you we tell the counter to count down in decimal by making
wrote to the counter. A little later we will discuss and the BCD bit of the control word a I. This makes our life
show applications for some of the six different modes. easier. because we don't have to convert the 32 to binary
First, let's finish looking at the control word bits and or hex. Finally, we have to decide how we want to load
see how you send the control word and a Count to the the count into the counter. Since the count that we
device, need to load in is less than 99. we only have to load the
The RWI and RWO bIts of the control word are used lower byte of the counter. According to FIgure 8-17. the
to specify how you want to write a count to a counter or RW! bit should be a 0 and the RWO bit a I for a write
to read the count from a counter. If you want to load a to only the lower bye (LSB). The complete control word
16-bit number into a counter, you put l's In both these then is 00010111 In binary. Here are the Instructions
bits in the control word you send for that counter, After to send the control word and count to counter 0 of the
you send the control word, you send the low byte of the 8254 in Figure 8-14. Note how the bits of the control
count to the counter address and then send the high word are documented.

MOV AL,000101 1113 Control word for counter 0


Readlwrlte LSB only. mode 3. I3CD countdown
:0001 011 1
BCD countdown
Mode 3
WLSB only
Select counter 0
MOV DX.OFFO7FI Point at 8254 contr.l register
OU1' DX.AL : Send control word
MOV AL.3211 . Load lower byte of count
MO' DX.OFFOIH : Point to counter 0 count register
OUT DX.AI. : Send count to count register

80&S INTERRUPTS AND INTERRUPT APPLICATIONS 225


Note that since we set the RW bits of the control word cw 10 LSB 4
for reaWwrtte 'SB only, we do not have to include
instructions to load the MSB of the counter. Pro-
grammed in this way, the 8254 will automatically load
Os in the upper byte of the counter.
If you need to load a count that is larger than I byte.
JSJJ1JL1LJW
GATE
make the RW bits In the control word both l's. Send the
lower byte of the count as shown above. Then send the OUT
high byte of the count to the Count register by adding N 0 0 0 0 0 EF FF
the instructions N N N 4 2 1 0 FF FE
3
MOV AL,HIGI-L..BYTE_OFCOUNT Load MSB of count
CW 10 LSB = 3
OUT DX,AL Send MSB to
count register
Note that the high byte of the count is sent to the same
CL K
address that the low byte of the count was sent.
For each counter that you want to use in an 8254,
you repeat the preceding series of six or eight instruc-
tions with the control word and count for the mode that
GATE I I
you want. Before going on with this chapter. review the our
six Initialization steps shown at the Start of this section
to make sure these are firmly fixed In your mind. In the N I NNN
0 I 0 I 0 I 0 I 0 I 0 1FF I
31 21 2 I 2 I 1 101 FF1
next Section we discuss and show some applications of
the different modes In which an 8254 counter can he CW=10 LSB = 3 LSB2
operated, but we do not have space there to show all the
steps for each of the modes.
C LK
8254 Counter Modes and Applications GATE
As we mentioned previously, an 8254 counter can be OUT I
programmed to operte in anyone of six different modes.
01 0 01 01 01 01FF
The Intel data book uses timing diagrams such as those NNNINIaI2Il2IljoIFF
in Figure 8-18 to show how a counter functions in each
of these modes. Since these waveforms may not be totally NOTE THE FOLLOWING CONVENTIONS APPLY TO ALL MODE
obvious to you at first glance. we will work our way TIMNG DIAGRAMS.
through some of them to show you how to interpret 1. COIJNTERS ARE PROGRAMMED FOR BINARY NOT BCDI
COUNTING AND FOR READING/WRITING LEAST
them. We will also show some uses of the different SIGNIFICANT BYTE (LSBI ONLY. -.
counter mods. As you read through this scetion, don't 2. THE COUNTER IS ALWAYS SELECTED (CS ALWAYS LOW).
try to absorb all the details of the different modes. 3. CWSTANDSFOR"C0NTR0LWORD";CW10MEANS
CONTROL WORD OF 10 HC ISVIRITTEN TO THE COUNTER.
Concentrate on learning to interpret the timing wave- 4. LSB STANDS FOR 'LA ""ICANT BYTE' OF COLNT.
forms and on the different types of output signals you 5. NUMBERS BELOW DIAGRAMS AFIE COUNT VALUES.
THE LOWER NUMBtR IS THE LEAST SIGNIFICANT BYTE.
can produce with an 8254. THE-UPPER NUMBER IS THE MOST SIGNIFICANT SYTE.
SINCE THE COUNTER IS PROGRAMMED TO READ/WRITE
MODE 0—INTERRUPT ON TERMINAL COUNT LSB ONLY. THE MOST SIGNIFICANT BYTE CANNOT BE READ.
N STANDS FOR AN UNDEFINED COUNT.
First read the Intel notes at the bottom of Figure 8-18; VERTICAL LINES SHOW TRANSITIONS BETWEEN
then take a look at the top set of waveforms in the figure. COUNT VALUES.
For this first example, the GA'rE input is held high so
that the counter is always enabled for counting. The MOOED
first dip in the waveform labeled WR represents the FIGURE 8-18 8254 MODE 0 example timuig diagrams.
control word for the counter being written to the 8254. (Intel CorporatIon)
CW - 10 over this dip Indicates that the control word
written is lOt-I. According to the control word format in
Figure 8-17, this means that counter 0 is being initial- the timing diagram. you should see that the count of 4
ized for binary counting, mode 0. and a readlwrite of is transferred into the counter by the next clock pulse
only the LSB. After the control word Is written to the after WR goes high. Each clock pulse after this will
control register. the output pin of counter 0 will go low. decrement the count by I. When the count is clecre-
The next dip in the WR waveform represents a count of mented to 0, the OUT pin will go high. If you write a
4 being written to the count register of counter 0. Before count N to a counter in mode 0. the OUT pin will go
this count can be counted down, it must be transferred high after N + I clock pulses have occurred. Note that
from the count register to the actual counter, llyou look the counter decrements from 0000 to FFFFH on the next
at the count values shown under the ou'r waveform in clock pulse unless you load sonic new count into the

226 CHAPTER EIGHT


lot, you can use an optical sensor such as the one shown
CW12 LSB3
in Figure 8-10. Each time a car passes through, this
Lfl_fl circuit will produce a pulse. You could connect the signal
from this sensor directly to an interrupt input and we
CLK ..f1J1J1J1JJ1J1J'lJlJlJlJ the processor count interrupts, as we dtd for the printed-.
circuit-board-making machine in a previous example.
GATE - - 111_______ However, the less you burden the processor with trivial
tasks such as this, the more time tt has available to do
complex work for you. Therefore, you let a counter In
OUT
an 8254 count cars and Interrupt the 8086 only when
0000FFOO it has counted 1000 Cars.
INININININI3I2I1I0IFFI3I2I
You connect the output from the optical sensor circuit
to the CLK input of. say, counter 1 of an 8254. You tte
CW12 LSB3 the GATE input of Counter Ito + S V so it will be enabled
for counting and connect the OUT pin of counter 1 to
an interrupt input on an 8259A or the NMI input on the
C LK .....flJlJlJ •'lJlJ• lJ'lJ'lJ.l.flJ.lJ---
8086.
In the mainline program, you initialize counter I for
GATE mode 0, BCD counting, and readiwrlte LSB then MSB
with a control word of 01110001 binary. You want the
OUT
_J I0IOIOl0IOlOI0I
counter to produce an interrupt after 1000 pulses from
the sensor, so you will send a count of 999 decimal to
the counter. The reason that you want to send 999
I N I N I N I NN 1312 1131211101 Instead of 1000 is that, as shown in FIgure 8-18. the
OUT pin will go high N + I clock pulses after the count
CW12 LS82 LS84 value is written to the counter. Since you Initialized the
counter for read/write LSB then MSB. you send 99H and
then 09H to the address of counter I. By Initializing the
CL K ....j1J1J1J1J1JlJ1.flJl.jl.J.1,.f' counter for BCD counting. you can just send the Count
value as a BCD number instead of havtng.to convert it
to hex.
GATE ---_____
The service procedure for this interrupt will contain
instructions which turn on the parking-lot-full sign.
OUT close off the main entrance, and return to the mainline
0 0 0 FF FF 0 0 program. For this example you dort't have to worry that
N N N N N 2 I 0 F FE 4 3 the Counter decrements from 0000 to FFFFH. because
after you shut the gate, the counter will not receive any
MODE 1 more interrupts.
FIGURE 8-19 8254 MODE 1 example timing diagrams.
(Intel Corporation) MODE 1—HARDWARE-RETRIGGERABIE
ONE-SHOT
counter. If the OUT pin is connected to an 8259A IR The basic principle of a one-shot is that when a siga
Input or the NMI interrupt Input of aj 8086. then the is applied to the trigger input of the device, its outpt'
processor will be interrupted when the counter reaches will be asserted. After a fixed amount of time the outpe.
0 Iterminat count). will automatically return to its unasserted state. For
The second set of waveforms in Figure 8-18 shows TFL one-shot such as the 74LS122. the time that t
that lithe GATE input is made low, the counter value output is asserted is determined by the time constao
will be held. When the GATE input is made high again. of a resistor and a capacitor connected to the devhe
the Counter continues to decrement by I for each Clock For an 8254 counter in one-shot mode, the time that
pulse. the output is asserted low Is determined by the frequency
The third set of waveforms in Figure 8-18 shows that of an applied clock and by a count loaded into the
If a new count is written to a counter, the new Count counter. The advantage of the 8254 approach Is that
will be loaded into the Counter on the next clock pulse. the output pulse width can be changed under program
Following clock pulses will decrement the new count control and, if a crystal-controlled clock is used, the
until it reaches 0. output pulse width can be very accurately specified.
As an example 01 what you can use this mode for. Figure 8-19 shows some example timing waveforms
suppose that as one of its jobs you want to use an 8086 for an 8254 counter In mode I. Lets take a look at th,
to control some parking lot signs around an electronics top set of waveforms. Again, the Ilrst dip in the WR
factory. The main parking lot can hold 1000 cars. When waveform represents the control word of 12i1 being s'
it gets full, you want to turn on a sign which directs to the 8254. Use Figure 8-17 to help you determine h'
people to another lot. To detect when a car enters the this control word initializes the device. 'i'au shoulu fl

- 31 8086 INTERRUPTS AND INTERRUPT APPLICATIONS 2.


that a control word of 1 2H programs counter 0 for binary quency. The 74L.S14 inverters sharpen the edges of
count, mode 1. read/write LSB only. When the control these pulses so that they can be applied to the GATE/
word is written to the 8254. the OUT pin goes high. trigger input of an 8254. For a 60-Hz line frequency, a
The second dip in the WR waveform represents writing pulse will be produced every 16.66 ins. Now what we
a Count to the counter. Note that, because the GATE want to do here is to load the countia with a value such
input is low, the counter does not 8tart counting down that the counter will always be retriggered by the power
Immediately when the count is written, as it does In line pulses before the countdown is completed. As shown
mode 0. For mode I, the GATE input functions as a by the second set of waveforms in Figure 8-19. the OUT
trigger input. When the GATE/trigger input is made pin will then stay low and not send an interrupt signal
high, the count will be transferred from the count to the NMI input of the 8086. If the ac power fails, no
register to the actual counter on the next clock pulse. more pulses come in to the 8254 trigger input. The
Each followIng clock pulse will decrement the counter trigger input will be left high. and the countdown will
by I. When the counter reaches 0. the OUT pin will go be completed. The 8254 OUT pin will then go high and
high again. In other words, if you load a value of N in intemipt the 8086.
the counter and trigger the device by making the GATE To determine the counter value for this application.
input high, the OUT pin will go low for a time equal to you just calculate the number of input clock pulses
N clock cycles. The output pulse width is then N times required to produce a countdown time longer than 16.66
the period of the signal applied to the CLK input. ms—for example. 20 ms. If you use the 2.4576-MHz
Incidentally, the dashed sections of the GATE waveforms PCLK signal on an SDK-86 board, 20 ms requires 49.152
in Figure 8-19 mean that the GATE/trigger input signal cycles of PCLK. so this Is the number you would load in
can go low again any time during that time interval. the 8254 counter. Since this number is too large to load
The second set of waveforms in Figure 8-19 demon- in as a BCD count, you put a 0 in the BCD bit of the
strates what is meant by the term retrtggerable. If control word to tell the 8254 to count the number down
another trigger pulse comes before the previously loaded in binary . Then you send the count value of C000}-I to
count has been counted down to 0. the original count the count register.
will be reloaded on the next clock pulse. The countdown
will then start over and continue until another trigger MODE 2-TIMED INTERRUPT GENERATOR
occurs or until the count reaches 0. If trigger pulses In a previous sect ion we described how a real-time clock
continue to come before the count is decremented to 0. of seconds. minutes. and hours could be kept in three
the OUT pin will rcmail low. memory locations by counting interrupts from a I-Hz
The bottom set of waveforms in i1gur - 19 shows pulse source. We also described how the 1-Hz interrupts
that if you write a new coui,t to a rou eg.ster whtle could be used to measure off other time intervals. The
the OUT pin is low, the new count wlL:-t'' t Lw o-aded dii'ficulty with using a 1-Hz interrupt signal is that the
into the counter and couret1 rlown untti the ticxt trigger maximum resolution of any time measurement is I S.
pulse occurs. In other words, if you use a I-Hz signal, you can Only
For an example of the use ci mod" we will s ow 'ou measure times to the nearest second. To improve the
how to make a Circuit whirh prouuces an interrupt rcsoiution of time measurements, most microcomputer
signal if the ac power fails. This circuit could bi- con- systems use a higher-frequency signal such as I kHz for
nected to the NMI input of an 80b6 to i-all an inter -ur't a real-time clock Interrupt. With a 1-kHz interrupt
procedure which saves parametrs in battery-backed signal. the time resolution is 1 ms. An 8254 counter
RAM when the ac power falls. Operating in mode 2 can be used to produce a stable
Figure 8-20 shows a circuit whith oscs an optical 1 -hHz signal by dividing down the processor clock signal.
coupler (an LED and a phototransistor packaged to- Figure 8-21 shows the waveforms for an 8254 counter
gether) to produce logic-level pulses at power line Ire- operating in mode 2. E.ets look at the top set of waveforms

FILTERED
1N914 2.45 MHZ
J AAA •5V PCuc

OPTICAL 1K
270 t COUPLER 8254
4533

OUT 0
c___ I
POWER L
TRANSFORMER TO 8086 SMI

FIGURE 8-20 Circuit to produce logic-level pulses at power tine frequency.

228 CHAPTER EIGHT


first. The two dips in the WR waveform represent a the processor clock signal to the CLK Input on one of
control word and the LSB of a count being written to the 8254 counters and tie the GATE input of that Counter
the count register. The next clock pulse after the count high. You initialize that counter for BCD counting, mode
Is written will transfer the count from the count register 2, and read/write LSI3 then MSB. Since you want to
to the actual counter. Since the GATE input is high. divide the 8 MHz by 8000 decimal to get I kHz. you then
succeeding clock pulses will count down this value until write OOH to the counter as the LSB and 80H to the
it reaches 1. When the count reaches 1. the OUT pin, counter as the MSB.
which was previously high. will go low for one clock A question that may occur to you at this point is. How
pulse time. The falling edge of the next clock pulse will do I count seconds if (lie interrupts are coming in every
cause the OUT pin to go high again and the original millisecond? The answer to the question is that you set
count to be loaded into the counter again. Successive aside a memory location as a milliseconds counter and
clock pulses will cause the countdown and load cycle to initialize that location with 1000 decimal (3E8H). The
repeat over and over. If the counter is loaded with a interrupt . servlce procedure decrements this count each
number N. the OUT pin will go low (or one clock cycle time an interrupt occurs and checks to see if the count
every N input clock pulses. The frequency of the output is down toO yet. If the count is not 0. then execution is
waveform then will be equal to the input clock frequency simply returned to the mainline. If the Count is down to
divided by N. 0. 1000 interrupts or I s has passed. The milliseconds
Now, for a specific example, suppose that you want to counter location is then reloaded with 3E8H, and the
produce a l'kHz signal for a real-time clock from an seconds . minutes-hours procedure is called to update
8-MHz processor clock signal. To do this, you Connect the count of seconds, minutes, and hours. An exercise
in the accompanying lab manual gives you a chance to
develop a real-time clock in this way. Incidentally, the
I -kHz Interrupt-service procedure can be used to meas-
CW-14 LS53 ure off several different time intervals that are multiples
of lms.
The middle set of mode 2 waveforms in Figure 8-21
CLK ,J1J1J'lJlJlJ'lJlJlJlJlJ' demonstrates that if the GATE input is made low while
the counter is counting, counting will stop. If the GATE
GATE input is made high again, the original count will be
reloaded into the counter by the next clock pulse.
Succeeding clock pulses will decrement the loaded count.
The bottom set of mode 2 waveforms in Figure 8-21
shows that ifa new count is written to the count register.
this new count will not be transferred to the counter
CW14 LSB3 until the previously loaded count has been decremented
to I.

CL K MODE 3—SQUARE .WAVE MODE


If an 8254 counter is programmed for mode 3 and
GATE an even number is written to its count register. the
waveform on the OUT pin will be a square wave. The
OUT frequency of the square wave will be equal to the
0000000 frequency of the input clock divided by the number
N N N 3 2 I written to the count register. 11 an odd number is
2 2 3 3
written to a counter programmed [or mode 3. the output
CW=i4 LSB4 LS85 waveform will be high for one more clock cycle than Ii
is low, so the waveform will not be quite symmetrical.
Figure 8-22. p. 230, shows some example waveforms [or
CL K mode 3. By now these waveforms should look quite
familiar to you.
GATE The top set of waveforms shows thai after a control
word is written to the control register and a Count is
OUT_J
U written to the coufll register. the Count is transferred
N N 000 0000 to the Counter on the next clock pulse. As shown by
N N 4 3 2 I 54 3 the Count sequence under the OUT waveform, each
additional clock pulse decrements the counter by 2.
NOTE A GATE TRANSITION SHOULD NOT OCCUR ONE CLOCK When the count is down to 2. the OUT pin goes low and
PRIOR TO TERMINAL COUNT the original count is reloaded. The OUT pin stays low
whilc the loaded count is again counted down by 2's.
MODE 2
When the count is down to 2. the OUT pin goes high
FIGURE 8-21 8254 MODE 2 example timing wavetorms again and the original Count is again loaded into the
lintel Corporation counter, The cycle then repeats.

8086 INTERRUPTS AND INT[RRUPT APPLICATIONS 229


CWl6 LS84
loon
C UK
GATE
OUT
0000000000
N N N N 4242424242 IN PUT
El
CW-1S LS85

FIGURE 8-23 Audio speaker buffer for 8254 timer output


CL
or port.
GATE
OUT and the OUT pin is connected to an audio buffer such
0000000000 as that shown in Figure 8-23.
N N N N 4204242042
As an example of this application, suppose that you
want to produce a tone that Is a musical A of 440 Hz
CWi6 LSB4
from the 2.4576-MHz PCLK signal. Dividing the PCLK
signal by 5585 will give the desired 440 Hz. Therefore.
CLK you simply send a control word which programs a
counter for mode 3, read/write LSB then MSB. and BCD
HiATt 1 I counting. You then write the LSB of 85H and the MSB
of 55H to the counter, if you want to change the
frequency, all you have to do is write a new count to the
Count register. With a few programmable counters and
some relatively Simple programming, you can play your
favorite songs.
NOTE: A GATE TRANSITION SHOULD NOT OCCUR ONE CLOCK
PRIOR TO TERMINAL COUNT. MODE 4—SOF1WARE-TRIGGERED STROBE
MODE 3 This mode and mode 5 are often confused with mode I,
but there is an obvious difference. Mode I is used to
GURE 8-22 8254 MODE 3 example timing waveforms. produce a low-going pulse that is N clock pulses wide.
teI Corporation) If you look at the top set of waveforms for mode 4 in
Figure 8-24. you should see that mode 4 produces a low-
lie center set of waveforms in Figure 8-22 shows going pulse after N + I clock pulses. For mode 4. the
hat happens ii an odd number is written to the Count output pulse is low for the time of one input clock pulse
register. As you can see from this waveform, the number and then returns high. in other words. in mode 4. a
of clock cycles for each waveform is still equal to the counter produces a low-going strobe pulse N + I clock
number loaded Into the count register. However, as we cycles after a count is written to the count register. Mode
mentioned before, the clock is high for one more clock 4 is referred to as soft ware-tnggered because it is the
Cycle than It Is low. writing of the count to the count register that starts the
The bottom set of waveforms In Figure 8-22 shows process. Note that after the loaded count is counted
thit counting stops if the gate is made low at any time. down, the counter decrements to FFFFH and then
Alter the GATE Input is made high again, the countdown continues to decrement from Ehere.
will continue. Mode 4 can be used in a case where you want to send
Mode 3 can be used for any case where you want a out some parallel data on a port and then after some
repetitive square-wave-type signal. An 8254 counter delay send out a strobe signal to let the receiving system
operating in mode 3 can be used to generate the baud know that the data Is available.
rate clock for a USART such as the 825 IA. Also, mode
3 could be used to generate interrupt pulses for a real- MODE 5—HARDWARE-TRIGGFRED STROBE
tim clock as we described for mode 2. The square-wave Mode 5 is used where we want to produce a low-going
signal has the advantage that it Is more easily observed strobe pulse some programmable time Interval after a
with a scope than the narrow pulse produced by mode rising-edge trigger signal is applied to the GATE Input.
2 operation. This mode is very useful when you want to delay a rising.
Another use of 8254 counters operating In mode 3 edge signal by some amount of time.
Is as programmable audio-tone generators. For this Figure 8-25 shows some example waveforms for a
application, a high-frequency clock such as the 2.4576- counter operating In mode 5. For a start, lets look at
MHz PCLK signal on an SDK-86 board is connected to the top set of waveforms. As usual, we write a control
the counter CLK Input, the GATE input Is tied high. word and the desired Count to a counter. As shown

230 CHAPTER EIGHT


CW18 LS93 CW1A LSB3


w
w LflI
C LK ...f1J1J%fi,,,J1,f1.f1..f1..flfl...f
CL K •..j1jiJ1...Jl.J1..flJl,j1..Tl.Jl.,1
GATE GATE iflfl
OUT LJ OUT
0 0 0 0 FF FF FF 0 0 0 0 FF U
N N N N 3 2 1 0 FF FE FD N N N N N 3 2 0 FF 3

CW18 LSS3 CW1A LSB3


g

CLX _f1,fl_f1f1.f1L11..J1.f1_fl.flr
CLK ,...J1J•1J'lflJ•'lJ'l.JlJlJ-l..fl,..J.l..fl.J-
GATE GATE PL__Jl--
OUT
OUT _fJ-
000000FF
IN N IN IN 31 31 31 2 I 1 Ia FF1
CW1A LS83 LSB5
=
CW 1B LSB3 LSB2 W4

CLX ...jiJljlJ1,fl,J'1J'1J'1flfl.J1.J'1..f
C LK .....ffLJ1...J1.fl.J1..f1..Jl.fl..f1J
GATE
GATE jfl
OUT _fLf ouij
0 0 0 0 FF FF 0 0
Li
NIN(NINIIIfjI?IoIFFl N N N N F. 3 2 1 0 FF FE 5 4

MODE 4 MODE 5

FIGURE 8-24 8254 MODE 4 example timing waveforms. FIGURE 8-25 8254 MODE 5 example timing waveforms.
(Intel Corporation) )InteI Corporation)

by the count sequence under the OUT waveform, how- count will not be loaded Into the counter until a new
ever, the count does not get transferred to the counter trigger pulse occurs.
until the GATE (trigger) Is made high. When the trigger
input is made high. the count will be transferred to the USING A NONSYSTEM CLOCK
Counter on the next clock pulse. Succeeding clock pulses WITH AN 8254 IN MODES 2 AND 3
will decrement the counter. When the counter reaches
0. the OUT pin will go low for one clock pulse time. The If you are applying a signal which is not derlvcd from
OUT pin will go low N + 1 clock pulses after the trigger the system clock to the CLK input of an 8254 in mode
input goes high. 2 or mode 3, then a small note in the Intel data sheet
The second set of waveforms In Figure 8-25 shows Indicates that the GATE input of the counter must be
that If another trigger pulse occurs during the count- pulsed low just alter the count Is written to the counter.
down time, the original count will be reloaded on the An easy way to do this is to connect the GATE Input of
next clock pulse and the countdown will start over. The the counter to an otherwise unused output port pin.
OUT pin will remain high until the count is finally You can then pulse the GATE by outputting a low and
counted down, If trigger pulses continue to come before then outputting a high to that port pin.
the countdown Is completed, the OUT pin will continue
to stay high. Therefore, you can use a counter In mode READING THE COUNT FROM AN 8254 COUNTER
5 to produce a power fail signal. as we showed in the
previous discussion of mode I. Note that for mode 5. For many counter applications, we want to be able to
however, the OUT pin will bc high if the power is on and read the current count in the counter. Suppose. for
go low when the power fails. example. that we are using an 8254 counter to count
The bottom Set of waveforms En Figure 8-25 shows the cars coming into a parking lot, as we did In our
that if a new count is written to a counter, the ne' example for mode 0 In an earlier section. In that case

8O&, INTERRUPTS AND INTERRUPT APPLICATIONS 231


we used the Counter to produce an Interrupt when the AO,A1 = Ii CSO R0= WR=O
parking lot was full, so we could shut the gatc. Now
further suppose that as part of a traffic flow study, we i7 t6
want to find Out how many cars have come into the
lot by 7:30 AM. An interrupt-driven real-time clock
I IT5IC21CNT1ICNTOI 10j

procedure can, at 730 AM., call a procedure which reads 05 0 = LATCh COUNT or SELECTED COUNTERS(S)
in the current count from the counter. Since the Counter 04: 0 LATCh STATUS OF SELECTED COUNTER(S)
was initially loaded with 1000 decimal and is being 03 1 =SELECTCOUNTER2
Counted down as cars come in. we can simply subtract 02: I SELECT COUNTER I
the current count from 1000 to determine how many Dl: 1 SELECTCOUNTEAO
cars have come in. 00: RESERVED FOR FUTURE EXPANSION, MUST BE 0
The Counters in an 8254 have latches on their outputs.
FIGURE 8-26 8254 read-back control word format.
When you read the count from a counter, what you are
actually reading Is the data on the outputs of these
latches. These latches are normally enabled during This method is available in the 8254 but not in the
counting so that the latch outputsjust follow the counter 8253. It is essentially an enhanced version of the counter
outputs. If you try to read the count while the counter latch command approach described in the preceding
is counting, the count may change between reading the paragraphs.
LSB and the MSB. This may give you a strange count. Figure 826 shows the format for the 8254 counter
To read a correct count, then, you must in some way read-back command word. It is sent to the same address
stop the counting or latch the current count on the that other control words are for a particular 8254. The
output of the latches. There are three major ways of l's in bits D7 and D6 identify this as a read-back
doing this. command word. To latch the count on a counter, you
The first is to stop counting by turning off the clock put a 0 in bit D5 of the control word and put a 1 in the
signal or making the GATE Input low with external bit position that corresponds to that counter In the
hardware. This method has the disadvantages that it control word. The advantage of this control word is that
requires external hardware and that a clock pulse which you can latch one, two, or all three counters by putting
occurs while the clock is disabled will obviously not be l's in the appropriate bits. Once a counter is latched.
counted. the count is read as shown in the previous example
The second way of reading a stable value from a program. After being read, the latch outputs return to
counter is to latch the current count with a counter following the counter outputs.
latch command and then read the latched count. A If a read-back command word with bit D4 = 0 is sent
counter is latched by sending a control word to the to an 8254, the status of one or more counters will be
control register address in the 8254. If you look at the latched on the output latches. Consult the Intel data
format for the 8254 control word in F'tgure 8-17. you sheet for further information on this latched status.
should see that a counter latch command is specified by The preceding sections have shown how 8254
making the RWI and RWO bits both 0. The SC! and counters can be used to do a wide variety of tasks around
SCO bits specify which counter we want to latch. The microcomputers. Many of these applications produce an
lower 4 bits of the control word are dont cares" for a interrupt signal which must be connected to an inter-
counter latch command word, so we usually make them rupt input on the microprocessor. In the next section
Os for simplicity. As an exam ple, here is the sequence we show how a prionty interrupt controller device, the
of instructions you would use to latch and read the LSB Intel 8259A, is used to service multiple interrupts.
and MSB from counter I of the 8254 in Figure 8-14. We
assume that the counter was already programmed for
read/write LSB then MSB when the device was initial-
ized. If the counter was programmed for only LSB or 8259A PRIORITY INTERRUPT CONTROLLER
only MSB. then Only that byte can be read.
Previous sections of this chapter show how interrupts
MOVAL.ol000000B Counter I latch command can be used for a variety of applications. In a small
MOV DX,OFFO71-{ Point at 8254 control register system, for example, we might read ASCII characters in
OUT DX.AL Send latch command from a keyboard on an interrupt basis: count interrupts
MOV DX.OFFO3H ; Point at counter 1 address from a timer to produce a real-time clock of seconds,
IN AL.DX Read LSB of latched count minutes, and hours: and detect several emergency or
MOV A1-I,AL Save [SB of latched count job-done conditions on an interrupt basis. Each of these
IN AL,DX Read MSB of latched count interrupt applications requires a separate interrupt
XCI-{G AH,AL Count now in AX input. If we are working with an 8086, we have a problem
here because the 8086 has only two interrupt inputs,
When a counter latch command is sent, the latched NM1 and INTR. If we save NMI for a power failure
count is held until it Is read. When the count is read interrupt, this leaves only one interrupt input for all the
from the latches, the latch outputs return to following other applications. For applications where we have
the Counter outputs. interrupts from multiple sources, we use an external
The third method of reading a stable count from a device called a priority interrupt controller (PlC) to "fun-
counter is to latch the count with a read-back Command. nel" the interrupt signals into a single interrupt input

232 CHAPTER EIGHT


on the processor. in this section. we show how a common bus allows the 8086 to send control words to the 8259A
PlC. the Intel 8259A, is connected in an 8086 system, and read a status word from the 8259A. The RD and
how it is initialized, and how It is used to handle WR inputs control these transfers when the device is
Interrupts from multiple sources. selected by asserting its Chip select (CS) input low. The
8-bit data bus also allows the 8259A to send interrupt
types to the 8086.
8259A Overview and System Connections Next, in Figure 8-27. observe the eight interrupt
To show you how an 8259A functions In an 8086 system, inputs labeled IRO through 1R7 on the right side of the
we first need to review how the 8086 INTR input works. diagram. If the 8259A is properly enabled, an interrupt
Remember from Figure 8-5 and a discussion earlier in signal applied to any one of these inputs will cause the
this chapter that if the 8086 interrupt flag is set and 8259A to assert its INT output pin high. If this pin is
the INTR input receives a high signal. the 8086 wIll connected to the INTR pin of an 8086 and if the 8086
Interrupt flag Is Set, then this high signal will cause the
1. Send Out two interrupt acknowledge pulses on its previously1escribed INTR response.
INTA pin to the INTA pin of an 8259A PlC. The INTA The INTA input of the 8259A is connected to the INTA
pulses tell the 8259A to send the desired interrupt output of the 8086. T-he 8259A uses the first INTA pulse
type to the 8086 on the data bus. from the 8086 to do some activities that depend on the
mode in whichit is programmed. Wben it receives the
2. Multiply the interrupt type it receives from the 8259A second INTA pulse from the 8086. the 8259A outputs
by 4 to produce an address in the interrupt vector an interrupt type on the 8-bit data bus, as shown in
table. Figure 8-6. The Interrupt type that It sends to the 8086
3. Push the flags on the stack. is determined by the IR input that received an interrupt
signal and by a number you send the 8259A when you
4. Clear IF and IF. initialize it. The point here Is that the 8259A "funnels"
5. Push the return address on the stack. interrupt signals from up to eight different sources into
the 8086 INTR Input, and it sends the 8086 a specitied
6. Get the starting address for the interrupt procedure interrupt type for each of the eight Interrupt inputs.
from the interrupt-vector table and load that address At this point the question that may occur to you is,
in CS and lP. What happens if interrupt signals appear at, for example.
7. Execute the interrupt-service procedure. 1R2 and 1R4 at the same time? In theJixed -priority mode
that the 8259A is usually operated in, the answer to this
Now let's take a little closer look at how the 8259A question is quite simple. In this mode, the IRO input
functions during this process. To statt, study the inter- has the highest priority, the lRl input the next highest.
nal block diagram of an 8259A in Figure 8-27. In the and so on down to lR7, which has the lowest priority.
figure, first notice the 8-bit data bus and control signal What this means is that if two interrupt signals occur
pins in the upper left corner of the diagram. The data at the same time, the 8259A will service the one with

NT
DATA
D7-D0 BUS
BUFFER
CONTROL LOGIC

RD
REAO/ lAO
WRITE Ri
LOGIC
AD - IN INTERRUPT 1A2
SERVICE PRIORITY REQUEST 1R3
REQ RESOLVER REG
(IRA) 1R4
CS ISR
1R5
IRS
Ri
CAS 0
CASCADE
CAS1 BUFFER/
COM PA A A TO R INTERRUPT MASK REQ
CAS2 - IIMRI

SP/EN

FIGURE 8-27 8259A internal block diagram. (Intel Corporation)

8086 INTERRUPTS AND INTERRUPT APPLICATIONS 233


the highest priority first, assuming that both inputs are than the highest-priority interrupt currently being ser-
unmasked (enabled) in the 8259A. viced, it will set the appropriate bit In the ISR and
Now let's look again at the block diagiam of the 8259A activate the circuitry which sends a new [NT signal to
In Figure 8-27 so we can explain in more detail how the the 8086. For our example here. lR2 has a higher priority
device will respond to multiple interrupt signals. In the than lR4, so the priority resolver will set bit 2 of the ISR
block diagram note the four boxes labeled Interrupt and activate the circuitry which sends a new INT signal
request register (IRR). interrupt mask register (IMR). to- to the 8086. II the 8086 INTR input was reenabled
service register ([SRI. and priority resolver. with an STI instruction at the start of the iR4 service
The interrupt mask register is used to disable (mask) procedure, as shown in Figure 8-28a. then this new INT
or enable (unmask) individual interrupt inputs. Each signal will interrupt the 8086 again. When the 8086
bit in this register corresponds to the interrupt input sends out a second INTA pulse in response to this
with the same number. You unmask an interrupt input interrupt, the 8259A will send it the type number for
by sending a command word with a 0 in the hit position the lR2 service procedure. The 8086 will use the received
that corresponds to that input. type number to find and execute the lR2 service pro-
The interrupt request register keeps track of which cedure.
interrupt inputs are asking for service. If an interrupt At the end of the lR2 procedure, we send the 8259A
input has an interrupt signal on it. then the correspond. a command word that resets bit 2 of the In-service
ing bit in the interrupt request register will be Set. register so that lower-priority interrupts can be serviced.
After that, an IRET instruction at the end of the lR2
NOTE An interrupt signal must remain high on procedure sends execution back to the interrupted lR4
aniR input until after the falling edge of the first procedure. At the end of the lR4 procedure, we send the
INTA pulse. 8259A a command word which resets bit 4 of the In-
service register so that lower . priority interrupts can be
The inservice register keeps track of which interrupt
inputs are currently being serviced. For each input that
is currently being serviced, the corresponding bit will MAINLINE
INITIALIZE 8259A
be set in the in-service register. UNMASK R2, R4
The priority resolver acts as a "judge" that determines STI 1R4 IR2
if and when an interrupt request on one of theiR inputs PROCEDURE PROCEDURE
gets serviced. ST I
As an example of how this works, suppose Ihat lR2
and lR4 are unmasked and that an interrupt signal
comes in on the 1R4 input. The interrupt request on the
1R4 input will set bit 4 in the interrupt request register. EOI EOI
COMMAND
The priority resolver will detect that this bit IS set and RET
check the bits in the in-service register (ISR) to see if a
higher-priority input is being serviced, If a higher- (a)
priority Input Is being serviced, as indicated by a bit
being set for that input in the ISR, then the priority MAIN
resolver will take no action, If no higher-priority inter- INITIALIZE 8259A
rupt is being serviced, then the priority resolver will UNMASK 1R2. tR4
STI R4
activate the circuitry which sends an inte, t signal PROCEDURE
to the 8086. When the 8086 responds with INTA pulses,
the' 8259A will send the interrupt type that was specified
for the lR4 input when the 8259A was initialized. As we
said before, the 8086 will use the type number it receives
from the' 8259A to find and execute the inierrupt.scrviee EOI COMMAND
IRET
procedure written for the 1R4 interrupt.
Now, suppose that while the 8086 is executing the 52
lR4 Service procedure, an interrupt signal arrives at the PROCEDURE
lR2 input of the 8259A. This will set bit 2 of the interrupt
request register. Since we assumed for this example
that 1R2 was unmasked, the priority resolver will detect
that this bit in the IRR is set and make a decision
EOI COMMAND
whether to send another interrupt signal to the' 8086.
To make the decision, the priority re-solver looks at the
in-scr'ice register. If a higherpriorlty hit in the [SR is
(11)
set, then a higher . priority interrupt is being serviced.
The priority resolver will wait until the higher-priority FIGURE 8-28 8259A and 8086 program flow for lR4
bit in the' ISR is re-set before sending an itlle'rrupt signal Interrupt followed by tR2 Interrupt. (a) Response with
to the 8086 for Ito' new interrupt input. Ii the priority INTR enabled in 1R4 procedure. (b) Response with INIR
resolver finds that the' neW Interrupt has a higher priority not enabled in 1R4 procedure.

234 CHAPTER EtGH


siviced An IRET instruction at the end 01 the lR4 master are connected to the corresponding pins of the
procedure returns execution to the mainline program. slave. For the master, these pins function as outputs,
This all sounds very messy, but it is really just a and for the slave device, they function as inputs. A
special case 01 nested procedures. Incidentally. If the IR4 further difference between the master and the slave is
procedure did not reenabie the 8086 1NTR input with that on the slave the SP/EN pin Is tied low to let the
an STI instruction, the 8086 would not respond to the device know that it is a slave.
lR2-caused INT signal until it finished executing the 1R4 Briefly, here Is how the master and the slave work
procedure. as shown in Figure 8-28b. when the slave receives an Interrupt signal on one of its
We can't describe all the possible cases, but the main IR Inputs. If that iR input is unmasked on the slave and
point here Is that the 8086 and the 8259A can be if that input isa higher priority than any other Interrup
programmed to respond to Interrupt signals from multi- level being serviced in the slave, then the slave will send
ple sources in almost any way you want them to. Now. an INT signal to the IR input of the master, If that lR
before we can show you how to initialize and write input of the master is unmasked and if that input is a
programs for an 8259A. we need to show you more higher prIority than any other IR inputs currently being
about how one or more 8259As are connected In a serviced in the master, then the master will send an tNT
microcomputer system. signal to the 8086 INTR input. If the 8086 INTR is
enabled, the 8086 will go thrg its INTR Interrupt
procedure and send out two INTA pulses to both the
8259A System Connections and Cascading master and the slave. The slave ignores the first Interrupt
Figure 8-14 shows how an 8259A can be added to an acknowledge pulse, but when the master receives the
SDK-86 board. As shown by the truth table in Figure first INTA pulse, it outputs a 3-bit slave identification
8-15, the 74LS138 address decoder will assert the CS number on the CASO. CASI. and CAS2 lines. (Each
input of the 8259A when an I/O base address of FF0011 slave in a system is assigned a 3-bit ID as part of its
is on the address bus. The A0 input of the 8259A is initIalization.) Sending the 3-bit ID number enables the
used to select one of two Internal addresses in the device. slave. When the slave receives the second INTA flulse
This pin is connected to system address line Al, so the from the 8086, the slave will send the desired interrupt
system addresses for the two internal addresses of the type number to the 8086 on the lower eight data bus
8259A are FF0011 and FF0211. The eight data lines of lines.
the 8259A are always connected to the lower half of the If an interrupt signal is applied directly to one of the
8086 data bus because the 8086 expects to receive IR inputs on the master, the master will send the desired
interrupt types on these lower el,gt data lines. RD and interrupt type to the 8086 when it reccives the second
WR are connected to the system RD and WR lines. INTA INTA pulse from the 8086.
from the 8086 is connected to INTA on the 8259A. Now that we have given you an overview of how an
The interrupt request signal. tNT. from the 8259A is 8259A operates and how 8259As can be cascaded, the
connected to the INTR input of the 8086. The multipur- initialization command words for the 8259A should
pose SP/EN pin is tied high because we are using only make some sense to you.
one 8259A in this system. When just one 8259A is used
in a system, the cascade lines (CASO. CASI. and CAS2) Initializing an 8259A
can be left open. The eight IR inputs are available for
interrupt signals. Unused IR inputs should be tied to Earlier In this chapter, when we showed you how to
ground so that a noise pulse cannot accidentaily cause initialize an 8254, we listed a series of steps you should
an Interrupt. In a later section we will show you how to go through to initialize any programmable device. To
initialize this 8259A. but first we need to show you how refresh your memory of these very important steps. we
more than one 8259A can be added to a system. will work quickly through them again for the 8259A
- The dashed box on the right side of Figure 8-14 shows The first step in initializing any device is to find the
how another 8259A could be added to the SDK-86 system base address for the device from the schematic
system to give a total of 15 interrupt inputs. If needed. or from a memory map for the system. In order to have
an 8259A could be connected to each of the eight a specific example here, we will use the 8259A shown in
IR inputs of the original 8259A to give a total of 64 Figure 8-14. The base address for the 8259A in this
interrupt Inputs. Note that since the 8086 has Only one system is FFOOH.
INTR input, Only one of the 8259A tNT pins is connected The next step is to find the internal addresses for the
to the 8086 INTR pin. The 8259A connected directly device. For an 8259A the two internal addresses are
into the 8086 LNTR pin is referred to as the master. The selected by a high or a low on the AU pin. In the circuit
INT pin from the other 8259A connects Into an IR input in Figure 8-14, the A0 pints connected to system address
on the master. This secondary. or cascaded, device is line Al, so the internal addresses correspond toO and
referred to as a staue. Note that the INTA signal from 2.
the 8086 goes to both the master and the slave devices. Next, you add the internal addresses to the base
Each 8259A has its own addresses so that command address for the device to get the system address for each
words can be written to it and status bytes read from internal part of the device. The two system addresses
it. For the cascaded 8259A in Figure 8-i4. the two for this 8259A then are FF0011 and FFO2H.
system 110 addresses will be FF081-I arid FFOAH. Next, look at Figure 8-29a for the format of the
The cascade pirs (CASO. CASt, and CAS2) from the command words that must be sent to an 8259A to

- 32 8Dm INTERRUPTS AND INT[RRUPT APPLICATIONS 235


ICW 1
AD 07 D6 05 04 03 02 01 DO
0 A7 A6 A5 1 jLTIMf ADI ! SNGL 1C4 I 1 __________________________
___________I i__I 1 CW4 NEEDED
[ ONOICW4NEEDED

1 SINGLE
0 CASCADE MODE

CALL ADDRESS INTERVAL


1 INTERVAL OF 4
0 INTERVAL OF B

1 LEVEL TRIGGERED MODE


0 EDGE TRIGGERED MODE

(MCS8O/B5MODEONLyI

AO 01 I CW2
1 A15 A14 A13 Al2 All
,.ç' ,4 / / AlO A9 AB 1 A15-A8OF INTERRUPT
VECTOR ADDRESS
I I I I I I )MCS80185 MODE)
T,-TOF INTERRUPT
ICW3 (MASTER DEVICE) VECTOR ADDRESS
(8086/8088 MODEl
AD 07 06 05 04 03 02 ADE

his, I I S6 S l S .
Dl DO
_____________
Ii = IR INPUT HAS A SLAVE
I
I
I
I
I
I
I
I I I I ES
-JOIRINPUTOOE5NOTHAVEI (SNGL-O)
[ A SLAVE
ICW3 (SLAVE DEVICE)
ICW3

1413 II[ib0uib001sLAvEi

I CW4
AU D7 0:
SFNM BUF !AEOi ___________________

H
ICW4

H READY TO
ACCEPT
INTERRUPT
o x7 NON BUFFERED MODE REQUESTS
[ 1 0 BUFFERED MODE/SLAVE
1 I BUFFERED MODE/MASTER

NOTE 1 SLAVE ID IS 1 SPECIAL FULLY NESTED


EQUAL TO THE
CORRESPONDING OT SPECIAL F UL LV
MASTER IR INPUT NESTED MODE

Ia) (b)

FIGURE 8-29 8259A InIllalizaton command word formats and sending order.
(a) lormals. (b) SendIn rder and requirements. (Intel Corporation)

236 CI-IAPTER Er
initialize it. The sight of all these command words may don't need to send an ICW3. If you are using a slave
seem overwhelming at first, but taken one at a time, 8259A in a system, you have to send an ICW3 to the
they are quite straightforward. To help you see which master to tell it which IR inputs have slaves. The master
Initialization command words (ICWs) are needed for has to be told this so that it knows for which IR input
various 8259A applications. Figure 8-29b shows this in signals it has to send out a slave ID number on the
flowchart form. According to this flowchart, an ICW1 CASO, CAS 1, and CAS2 lines. You have to send an ICW3
and an ICW2 must be sent to any 8259A in the system. to a slave 8259A to give it an ID number. The ID number
If the system has any slave 8259As (cascade mode), then you give a slave is equal to the IR input of the master
an ICW3 must be Sent to the master, and a different that its INT output is connected to. When the master
ICW3 must be sent to the slave. If the system is an 8086 sends out an ID number on the CAS lines, the slave will
or if you want to specify certain special conditions, then recognize Its ID number and opit the desired type to
you have to send an ICW4 to the master and to each the 8086 when it receives an INTA pulse.
slave. Now let's look at the formats for the different For our example here, the only reason we need to send
ICWs, an ICW4 is to let the 8259A know that it is operating in
The first thing to notice about the ICW formats in an 8086 system. We do this by making bit DO of the
Figure 8-29a is that the bit labeled AO on the left end of wor&a 1. Another interesting bit in this command word
each of these Is not part of the actual command word. is Dl, the automatic end-of-interrupt bit. If this bit is
This bit tells you the internal address that the control set in ICW4, the 8259A will automatically reset the in-
word must be sent to. The A0 = 0 next to ICWI. for service register bit for the interrupt input that is being
example, tells you that ICW 1 must be sent to internal responded to when the second interrupt-acknowledge
address 0. which for our 8259A corresponds to system pulse is received. The effect of this is that the 8259A
address FFOOH. will then be able to respond to an interrupt signal on a
The next step in the initialization procedure is to lower-priority IR input. In other words, a lower-priority
make up the control words. The least significant bit of interrupt input could then interrupt a higher-priority
ICW1 tells the 8259A whether it needs to look for an procedure. Since we don't want automatic end of inter-
ICW4 or not. Since we are using the device in an 8086 rupt, the ICW4 for our example here is 00000001.
system, we need to send ICW4. Therefore we make bit In addition to the initialization command words
DO a 1. We only want to use one 8259A for now, so we shown in Figure 8-29a. the 8259A has a second set of
make bit Dl a 1. When used with an $086, bit D2 isa command words called operation command words, or
don't care, so we make it a 0. Bit D3 is used to specify OCWs. These are shown in Figure 8-30.p. 238. An
level-trIggered mode or edge-triggered mode. In level- OCW1 must be sent to an 8259A to unmask any IR
triggered mode, service will be requested whenever a inputs that you want it to respond to. For our example
high level Is present on an IR input. In edge-triggered here, let's assume that we want to use only 1R2 and IR3,
mode, a signl on an IR input must go from low to high Since a 0 in a bit position of OCWI unmasks the
and stay high until serviced. We usually use the edge- corresponding IR input, we put 0's in these two bits and
triggered mode so that a signal such as a square wave is in the rest of the bits. Our OCWI is 111110011.
will not cause multiple interrupts. Making bit D3 a 0 OCW2 is mainly used to reset a bit in the in-service
does this. Bit D4 has to be a 1. For operation in an 8086 register. This is usually done at the end of the interrupt-
system, bits D5, D6. and D7 are don't cares, so we make service proredure. but it can be done at any time in the
them Os for simplicity. Therefore, the ICWl for our procedure. 'l'he effect of resetting the ISR bit for an
example here is 00010011. interrupt level is that once the bit is reset, the 8259A
In an 8086 system, ICW2 is used to tell the 8259A the can respond to interrupt signals of lower priority. In
type number to send In response to an interrupt signal small systems we usually use the nonspecific End-
on the IRO input. In response to an interrupt signal on of-Interrupt command word. The OCW2 for this is
some other IR input, the 8259A will automattcally add 00100000. When the 8259A receives this OCW, it will
the number of the IR input to this base number and automatically reset the in-service register bit for the IR
send the result to the 8086 as the type number for that input currently being serviced. If you want to reset a
input. Because 8086 Interrupt types 0 through 31 are specific ISR bit, you can send the 8259A an OCW2 with
either dedicated or reserved, type 32 idecimal) is the 011 in bits 137. 136, and D5, and the number of the ISR
lowest type number available for us to use. If we send bit you want to reset in the lowest 3 bits of the word.
the 8259A an ICW2 of 00100000 binary or 32 decimal, You can also use OCW2 to tell the 8259A to rotate the
the 8259A will send this number as the type to the 8086 priorities of the IR inputs so that after an IR input is
in response to an !R0 interrupt. For an interrupt request serviced, it drops to the lowest priority. If you are
on the IRI input, the 8259A will send 00100001 binary interested, consult the Intel data sheet for more informa-
or 33 decImal, arid for an interrupt request on the 1R2 tion on this and on the use of OCW3.
input, the 8259A will send an Interrupt type 001000010 Now thai we have made up the required iCWs and
binary or 34 decImal. The same pattern continues for OCWs. the next step is to write the instructions to send
interrupt requesis on the remaining IR inputs. In any these command words to the 8259A.
ICW2 you send the 8259A, the lowest three bits must Figure 8-31. p. 239-40. shows an 8086 assembly
always be Os because the 8259A automatically supplies language program which initializes an 8259A and dem-
these bits to correspond to the number of the IR Input. onstrates many of the concepts of this chapter. You can
Since we are not usmg a slave in this examplr. we use this program as a pattern for writing programs

8086 INTERRUPTS AND INTERRUPT AP 'iONS 237


OCw1
AU 01 DC 05 04 D3 02 Dl DO
Mi [ M6 MS M4 M3 M2 Ml
I MO] TERIPT MASK

AU 07 D6DS D4

NON-SPECIFIC EOI COMMAND


} END OF INTERRUPT
SPECIFIC EOI COMMAND
ROTATE ON NON-SPECIFIC 001 COMMAND
ROTATE IN AUTOMATIC EOI MODE (SET) } AUTOMATIC ROTATION
ROTATE IN AUTOMATIC 001 MODE (CLEAR)
ROTATE ON SPECIFIC EOi COMMAND
} SPECIFIC ROTATION
SET PRIORITY COMMAND
NO OPERATION
'LO-L2ARE USED

OCW3
AU 07 06 D4 D5 03 02 Dl DO
I 0 0 JESMMJ SMM j 0 7 P RR RIS
READ REGISTER COMMAND
oji I
0 0 7
I
IREAD IR flOG ONIREAD IS flOG ON
I
I.
I NOACTION
1NEXTfi5PULSE !NEXTRDPULSE I
iIlroili

FIGURE 8-30 8259A operational command words. (Intel Corporation)

which service one or more interrupts. This program that the key-pressed strobe from the ASCII keyboard is
ln)tializes the SDK-86 system in Figure 8-14 for generat- connected to the 1R2 input of the 8259A.
ing a real-time clock of seconds. minutes. and hours In the program. we first declare a segment called
from a l-kl-lz interrupt signal and for reading ASCII AINT_TABLE to reserve space for the vectors to the
codes from a keyboard on an interrupt basis. This interrupt procedures. The statement TYPE_64 DW 2
program assumes that the 2.4576-MHz PCLK signal on DUP(0). for example, sets aside a word space for the
the board Is connected to the CLK Input of the 8254 offset of the type 64 procedure and a word for the
counter 0, the GATE input of the 8254 counter 0 is tied segment base of the procedure. The statement TYPE_65
high. and the OUT pin of counter 0 is connected to the DW 2 DUP(Oi Sets aside a word for the offset of the type
IRO input of the 8259A. The program further assumes 65 procedure and a word space for the segment base

238 CHAPTER EIGHT


;8086 PROGRAI F8-31.ASM


2 Program fragment to show the initialization of interrupt ji.p table,
3 8259* priority interrupt controLler, and 8254 prograiimable counter/timer
4
5 0000 AINT_TABLE SEGMENT D PUBLIC
6 0000 021(0000) TYPE 64 DU 2 DUP(0) ;Reserve space for clodc procedure address
7 0004 02*(0000) TYPE_65 OW 2 DtJP(Q) ;Not used in this program
8 0008 o2*c0000) TYPE 66 Ow 2 DUP(0) ;Reserve space for keyboard procedure address
9 000C AINI_TABLE ENDS
10
11 0000 DATA SEGMENT WORD PUBLIC
12 0000 00 SECONDS 08 0
13 0001 00 MINUTES DB 0
14 0002 00 HJRS D8 0
15 0003 03E8 INT_CJNT DV 03E8H ;1 kHz interrupt coL,iter
16 0005 64(00) KEY_BUt DB 100 DUP(0) ;Buffer for 100 ASCII characters
17 0069 DATA ENDS
18
19 0000 STACK_SEG SEGMENT ;No STACK directive used because

20 0000 64* (0000) OW 100 DUP(0) wilt be using EXE2BIN
21 TOP_STACK LABEL WORD
22 0008 STACK_SEG ENDS
23
24 0000 CE SEGMENT PUBLIC
25 ASSUME CS:COE, DS:AINT_TABLE, SS:STACK SEC

26 0000 88 0000s
NOV AX. STACK_SEG ;lnitiatize stack
27 0003 BE DO NOV SS, AX ;segment register

28 0005 BC OOCBr NOV SP, OFFSET TOP_STACK ;Initialize stack pointer register
29 0008 88 0000s NOV AX, AINT_TABLE ;Initialize data
30 0008 BE 08 NOV OS, AX ;segment register
31 ;Defirie the addresses for the interrupt service procedures

32 0000 C7 06 0002r 0000s NOV TYPE_642, SEC CLOCK Put in clock procedure address
33 0013 C7 06 0000r 004Er NOV TYPE_64, OFFSET CLOCK

34 0019 C7 06 000Ar 0000s NOV TYPE_66.2, SEC KEYBOARD Put in keyboard procedure address

35 OO1F C7 06 0008r OOSSr NOV IYPE_66, OFFSET KEYBOARD
36 ;Initialize data Segment register
37 ASSUME DS:DATA

38 0025 88 0000s
NOV AX, DATA
39 0028 8E 08 NOV OS, AX
40 ;Initia(ize 8259* priority interrupt controller
41 002A 80 13 NOV AL, 000100118 Edge triggered, single, ICW4
42 002C BA FF00 NOV DX, OFFOOH Point at 8259A control
43 002F EE JT DX, AL Send ICU1
44 0030 80 40 NOV AL, 010000008 Type 64 is first 8259A type
45 0032 BA FF02 NOV DX, OFFO2I4 Point at ICV2 address
46 0035 EE JT DX, AL Send 1CW2
47 0036 80 01 NOV Al, 000000018 1CW4, 8086 mode
48 0038 EE QJT DX. AL Send 1CW4
49 003 80 TA NOV AL, 111110108 OCWI to uranask IRO and 1R2
50 003B EE DJT DX, AL Send OCW1
51 ;Initiatije 8254 counter 0
52 003C 80 37 NOV Al, OOI1OI11B 1 kHz square wave, LSB then MSB, BCO
53 003E BA FF07 NOV DX, OFFO7H Point at 8254 controL address
54 0041 EE tUT DX, AL Send counter 0 comnand word
55 0042 80 58 NOV AL, 58H Load LSB of count
56 0044 BA FF01 NOV DX, OFFO1K Point at counter 0 data address
57 0047 EE JT DX, AL Send LSB of count
58 0048 80 24 NOV AL, 24K load NSB of count
59 004* EE JT OX, AL ; Send NSB of count
60 ;Enable interrupt input of 8086
61 004B FB 511

62 004C EB FE HERE:JNP HERE wait for interrupt
63
64 004E CLOCK PROC FAR
65 Clock procedure instructions
66 004E 80 20 NOV AL, 001000008 0CW2 for non-specific EOI
67 0050 BA FF00 NOV DX, OFFOOM Address for OCW2
68 0053 JT DX, AL Send 0CW2 for end of interrupt
69 0054 CF IRE!
70 0055 CLOCK EP4DP

FIGURE 8-31 Assembly language program showing initialization of 8086, 8259A, and 8254 for real-time
clock and keyboard interrupt procedures. (Continued on next page.)

8086 INTLRRUPTS AND INTERRUPT APPLICATIONS 239


71
72 0055 KEYBOARD PROC FAR
T3 K*yboard procedure instructions
74 0055 80 20 MOV AL, OOl00000b OCW2 for no . specific tOl
75 0057 BA FF00 V DX, OFFOON Addresa for 0042
76 OOSA ft )T DX, AL Send OCW2 for end of interrupt
77 0058 CF IRET
78 005C KEYBOARD ENDP
79 005C CE ENDS
80 END
FIGURE 8-31 (continued).

address of the type 65 procedure, etc. As you will soon For the two interrupt . service procedures, we showJust
see, we use program instructions to load the actual the skeletons and the End-of-Interrupt instructions. We
starting addresses of the interrupt procedures in these leave it to you to write the actual procedures. Note that
locations. the interrupt procedures must be declared as far so that
the assembler will load both the IP and the CS values
NOTE: Because of the way the EXE2BIN program in the interrupt-pointer table. Also note the End-of-
works, the AINT_TABLE segment must be first In Interrupt operation at the end of each procedure.
your program so that It will be located at absolute Remember from a previous discussion that when the
address 0000:01001-1, where it must be for the 8259A responds to an lR signal, it sets the corresponding
program to work correctly when downloaded to an bit in the ISR. This bit must be reset at some time
SDK-86 board. during or at the end of the Interrupt-service procedure
so that the priority resolver can respond to future
The next thing we do in our program Is to declare a interrupts of the same or lower priority. At the end of
data segment and Set aside some memory locations for our procedures here we do this by sending an OCW2 to
seconds count. minutes count, hours count, and 100 the 8259A. The OCW2 of 00100000 that we send tells
characters read in from the keyboard. After the data the 8259A to reset the ISR bit for the IR level that Is
segment. we set up a stack segment. currently being serviced. This is a nonspecific End-of-
At the start of the mainline, we Initialize the stack Interrupt (EOl) Instruction.
segment register and the stack pointer register. Then
we initialize the DS register to point to the interrupt-
vector table we set up at the Start of the program. SOFTWARE INTERRUPT APPLICATIONS
The next four instructions load the addresses of the
clock and keyboard procedures in the type 64 and type In an earlier section of the chapter, we described how
66 Locations In the interrupt-pointer table. the 8086 software Interrupt instruction INT N can be
After we load the Interrupt-vector table, we ASSUME used to test any type of interrupt procedure. For example.
DS:DATA and initialize DS to point to the data segment to test a type 64 interrupt procedure without the need
which contains the data for the clock and keyboard. for external hardware such as we described in the
The next step is to Initialize the 8259A as we described preceding section. you can just execute the instruction
in the preceding section. The AU bit next to lCWl in [NT 64.
Figure 8-29 is a 0, so ICW1 Is sent to the lower of the Another important use of software Interrupts is to call
two addresses for the 8259A, FFOOH. For the example Basic Input Output System, or BIOS. procedures in an
here we chose type 64 to correspond to an IRO interrupt. IBM PC-type computer. These procedures in the system
so the needed ICW2 will be 01000000. The A0 bit next ROMs perform Specific input or output functions, such
to ICW2 in Figure 8-29 Is a 1. so ICW2 is sent to the as reading a character from the keyboard, writing some
higher of the two addresses for the 8259A. FFO2H. characters to the CRT. or reading some Information
Likewise, ICW4 and OCW1 are sent to system address from a disk.
FFO2H. To call one of these procedures, you Ibad any required
The next section of the mainline program initializes parameters In specified registers and execute an INT N
counter 0 of the 8254 for mode 3, BCD countdown, and instruction. N In this case is the interrupt type which
read/write LSB then MSB. To produce a 1-kHz signal vectors to the desired procedure. You can read the BIOS
from the 2.4576-MHz PCLK. we then write a count of section of the IBM PC technical reference manual to get
2458 to counter 0. This will not give exactly 1 kHz. but all the details of these if you need them, but here's an
it is as close as we can get with this particular Input example of how you might use one of them.
clock frequency. The PCLK frequency for this board was Suppose that, as part of an assembly language pro-
chosen to make baud rate clock frequencies come out gram that you are writing to run on an IBM PC-type
exact, not a 1-kHz real-time clock. computer. you want to send some characters to the
Finally, after the timer is initialized, we enable the printer. The [NT 17H instruction can be used to call a
8086 INTR input with the STI instruction so that the procedure which will do this.
8086 can respond to tNT signals from the 8259A. Figure 8-32 shows the header for the INt 17H proce-
and wait for an interrupt with the HERE:JMP HERE dure from the IBM PC BIOS listing. Note that the DX,
instruction. .\i1. and AL registers are used to pass the required

240 CHAPTER EIGHT


;INT 17 parameters to the procedure. Also note that the proce-
;Printerlo - Provides comy nication with the printer dure is used for two different operations: initializing the
INPUT:
printer port and sending a character to the printer. The
AHO Print the character in AL.
On eturn AH=1 if character could not be operation performed by the procedure Is determined by
printed (Time out). Other bits set as on the number passed to the procedure in the AH register.
; normal status call. Al-I = I means Initialize the printer port. AH 0 means
*11=1 InitiaLize printer port. print the character In AL, and AH = 2 means read the
Returns with AK set with printer status
*14=2 Read the printer status into AK printer status and return It in AH. if an attempt to print
bit 7 6 5 4 3 2 1 0 a character was not successful for some reason, such as
the printer not being turned on. not being selected, or
LL±:t being busy. Oils returned in Al-i.
1=1/0 error
lselec ted Now work your way through the program example in
lout of paper Figure 8-33 to see how the INT 17H procedure is called
lacknowl edge to Initialize the printer and how it is called over and
1=Not busy over to send a text string to the printer. Note that we
sent a carriage return character and a linefeed character
DX = Printer to be used (0,1,2) corresponding to
actual values in Printer_Base area after the text string because the printer will not print a
line until it receives a carriage return.
Data area Printer_Base contains the base address to The main advantage of calling procedures with soft-
the printer card(s) available (Located at beginning ware Interrupts is that you don't need to woriy about the
of data segment 408H absolute, 3 words)
Data area Print_Tim_Out (byte) may be changed to absolute address where the procedure actually resides or
cause different time out waits. Defautt2O about trying to link the procedure into your program.
All you have to know is the interrupt type for the
REGISTERS: *14 is modified, all others unchanged. procedure and how to pass parameters to the procedure.
This means that a program you write for an IBM
FIGURE 8-32 Header for INT 17 procedure.
computer will work on a compatible COMPAQ computer,
(18M Corporation)
even though the BIOS printer driver procedures are

;8086 PROGRAM F8'33.ASN


2 ;ABSTRACT : This program sends a string of characters to a printer
3 fra en IBM type PC. To run this program, first asserèle
4 and use the LINK program to create the .EXE file. Then
5 turn on your printer, & at the DOS proapt type F8-33.
6 ;REGISTERS : Uses CS, SS, OS, BX, AX, CX. DX
7 ;PORTS : Uses printer port 0
a ;PROCEDURES: Calls BIOS printer 10 procedure HIT 17
9
10 0000 STACK_SEC SEGMENT STACK
11 0000 C8(0000) DW 200 DUP(0) Set aside 200 words for stack
12 STACK_TOP LABEL WORD Assign name to word above stack top
13 0190 STACK_SEC ENDS
14
15 = 001€ CHAR_C00NT EQU 30
16
17 0000 DATA SEGMENT
18 0000 48 45 4C 4C 4F 20 54 + MESSAGE 08 'HElLO THERE, HOW ARE YW?
19 48 45 52 45 2C 20 48 +
20 4F 57 20 41 52 45 20
21 59 4F 55 3F
22 0019 00 0* 00 0* MESSAGE_END DB 0014, OAK, 0DM, OAK return & line feed
23 COlD DATA ENDS
24
25 0000 CE SEGMENT
26 ASSUME CS:COOE, SS:STACK_SEG, DS:DATA
27 0000 88 0000s START: NOV AX. STACK_SEC nitialize stack segment register
28 0003 8€ DO NOV SS, Ax
29 0005 BC 0190r NOV SP, OFFSET STACK_TOP Initialize stack pointer register
30 0008 88 0000s NOV AX, DATA Initialize data segment register
31 0008 8€ 08 NOV OS, AX
32 0000 84 01 NOV AN, 01 Set up registers to initialize printer
33 DOOr BA 0000 NOV DX, C port 0
34 0012 CD 17 lIlT 1714 CaLl procedure to intitialize printer port
35 0014 80 1E 0000r LEA BX, MESSAGE Get to start of message
36 0018 B9 001E NOV CX, CHAR_COuNT Set up a count ,'eriabte
37 0018 84 00 AGAIN: NOV AN, 0 Load code for procedure to send character
FIGURE 8-33 8086 assembly language program for outputting characters to a
printer. (Continued on next page.)

8086 INTERRUPTS AND INTERRUPT APPLICATIONS , 241


8 0010 8A 07 NOV AL, (BX] Load character to be sent into AL


39 0011 CD 17 INT uN Use BI(S routine to send character to printer
40 0021 80 FC 01 CHP AH, DiN If character not printed then returns AN -1
41 0024 75 04 JNE NEXT IF character not printed THEN
42 0026 F9 NOT_RDY:STC Set carry to indicate message not sent
43 0027 U 05 90 JI4P EXIT and Leave Loop
44 002A F8 NEXT: CLC ELSE CLear carry fLag (character sent)
45 002B 43 INC BX Move to address of next character
46 t02C E2 ED L00P AGAIN Send the next character
47 002E B8 4C00 EXIT: NOV AX, 4COOH GracefuL exit to DOS
48 0031 CD 21 INT 21H with ftxction caLL 4CH
49 0033 C00E ENDS
50 END START
FIGURE 8--33 (continued).

located at very different absolute addresses in the two Single-step interrupt—type I


machines. In later chapters we show more examples of Nonmaskable interrupt—type 2
using BIOS procedures.
This chapter has introduced you to interrupts and Breakpoint interrupt—type 3
some interrupt applications. The following chapters will
show you many more applications of interrupts because Overflow interrupt—type 4
almost every microcomputer system uses a variety of Software interrupts—INT types 0 through 255
interrupts.
INTR interrupts—types 0 through 255
Edge- and level-activated interrupt input
CHECKLIST OF IMPORTANT TERMS AND
CONCEPTS IN THIS CHAPTER Interrupt priority
If you do not remember any of the terms in the following Programmable timer/counter devices—.8253. 8254
list, use the index to help you find them in the chapter Initialization steps for peripheral devices
for review.
internal addresses
8086 interrupt response Control words, command words, mode words
Interrupt-service procedure 8259A priority interrupt controller
Interrupt vector, interrupt pointer In-service register (ISR)
Priority resolver
interrupt-vector table, Interrupt-pointer table interrupt requet rg'?r "RRI
interrupt type Interrupt mask register (IMR)
Divide-by. zero interrupt—type 0 BIOS

REVIEW QUESTIONS AND PROBLEMS


I. List and describe in general terms the steps an 6. Briefly describe the condition(s) which cause the
8086 will take when it responds to an interrupt. 8086 to perform each of the following types of
interrupts: type 0, type I, type 2. type 3. type 4.
2. Describe the purpose of the 8086 interrupt.vector
table. 7. Why is it necessary to PUSH all registers used in
the procedure at the start of an Interrupt-service
3. What addresses In the interrupt-vector table are procedure and to POP them at the end of the
used for a type 2 interrupt? procedure?
4. The starting address for a type 4 interrupt-service 8. Why must you use an IRET instruction rather
procedure is 0010:0082. Show where and in what than the regular RET instruction at the end of an
order this address should be placed In the interrupt. interrupt-service procedure?
vector table.
9. Show the assembler directive and instructions you
5. Address 00080H in the Interrupt-vector table con- would use to initialize the interrupt-pointer table
tains4A24H. and address 0008211 contains 0040H. locations for a type 0 procedure called DIV_0_ER-
a. To what interrupt type do these iocattons corre- ROR and a type 2 procedure called POWER_-FAIL.
spond?
b. What is the starig aidress for the interrupt- 10. a. Describe the main use of the 8086 type 1
service procedu interrupt.

242 CHAPTER EIGHT


b. Show the assembly language instructions nec- to a running total kept in two successive memory
essaly to set the 8086 trap flag. locations. If the MSB of data is 1. showing that the
value is out of range, ignore the input. After 100
II. In a system which has battery-backed RAM for
samples have been totaled, divide by 100 to get the
saving data in case of a power failure, the stack is
average, store this verage in another reserved
often put in the battery-backed RAM. This makes
memory location, and reset the total to 0.
It easy to save registers and critical program data.
Assume that the battery-backed RAM is in the IS. Write the algorithm and the program for an inter-
address range of 08000H through O8FFFH. Write rupt-service procedure which turns an LED con-
an 8086 power failure Interrupt-service procedure nected to bit DO of port FFFAH on for 25 s and off
which for 25 s. The procedure should also turn a second
LED connected to bit Dl of port FFFAH on for I
Sets an external battery-backed flip-flop connected minandofflor 1 min.Assumethata l-Hzinterrupt
to bit 0 of port 28H to indicate that a power failure signal is connected to the NMI input of an 8086
has occurred. and that a high on a port bit turns on the LED
Saves all registers on the stack. connected to it.

Saves the stack pointer value for the last entry at 16. Write the algorithms for a mainline program and
location 8000H. an interrupt-service procedure which generate a
real-time clock of seconds. minutes, and hours in
Saves the contents of memory locations OO100H
three memory locations using a 1-Hz signal applied
through 003FFH after the saved stack pointer value
to the NMI Input of an 8086. Then write the
at the start of the battery-backed memory. (A string
assembly language programs for the mainline and
instruction might be useful for this.)
the procedure. If you are working on an SDK-86
Halts. board, there is a procedure in Figure 9-32 that you
can add to your program to display the time on the
When the power comes back on, the start-up data and address field LEDs of the board. You can
routine can check the power fail flip-flop. If the flip- use this procedure without needing to understand
flop is set, the start-up procedure can copy the saved the details of how it works. To display a word on
data back into its operating locations. initialize the the data field, simply put the wor in the CX
stack segment register, and then get the saved SP register, put OOH in AL. and call the procedure. To
value from address 0800011. Using this value, it display a word on the address field, put the word
can restore the pushed registers and return execu- in CX. OIH in AL. and call the procedure. Hint:
tion to where the power fail interrupt occurred. Clear carry before incrementing a count in AL so
This is called a "warm start." If we dont want it to that DAA works correctly.
do a warm start, we can reset the flip-flop with an
external RESET key so the system does a start from 17. In Chapter 5 we discussed using breakpoints to
scratch, or "cold start." debug programs containing procedures. List the
sequence of locations where you would put
12. a. Why is the 8086 INTR input automatically breakpoints in the example program in Figure 8-9
disabled when the 8086 is RESET? to debug it if it did not work when you loaded it
b. How is the 8086 INTR input enabled to respond into memory.
to interrupts?
c. What instruction can be used to disable the Ii. Suppose that we add another 8254 to the SDK-86
INTR input? add-on circuitry shown in Figure 8-14 and that the
ci. Why is the INTR input automatically disabled CS input of the new 8254 is connected to the Y5
as part of the response to an INTR interrupt? output of the 74LS 138 decoder.
e. How is the INTR input automatically reenabled a. What will be the system base address for this
at the end of an INTR interrupt-service pro- added 8254?
cedure? b. To which half of the 8086 data bus should the
eight data lines from thIs 8254 be connected?
13. Describe the response an 8086 will make if it
c. What will be The system addresses for the three
receives an NMI interrupt signal during a division
counters and the control word register in this
operation which produces a divide . by. zero in-
terru pt. 8254?
ci. Show the control word you would use to initial-
14. The data outputs of an 8-bit analog-to-digital con- ize counter I of this device for readiwrite LSB
verter are connected to bits D0—D7 of port FFF9I-1, then MSB. mode 3. and I3CD countdown
and the end-of-conversion signal from the ND e. Show the sequence of Instructions you would
converter is connected to the NMI input of an 8086. use to write this control word and a count of
Write a simple mainline program and an interrupt- 0356 to the counter.
service procedure which, reads in a byte of data f. Assuming that the GATE input is high. when
from the converter. If tbe MSB of the data is a 0. does the counter start counting down in mode
Indicating that the value is in range. add the byte 3?

8O8, INTERRUPTS AND INTERRUPT APPlICATIONS 243


33
g Assuming initialization as in parts d andf. and 22. Describe the use of the CASO, CASI. and CAS2
that a 712-kHz signal is applied to the CLK lines in a system with a cascaded 8259A.
Input of counter I in mode 3. describe the 23. DescrIbe the response that an 8259A will make if
frequency, period, and duty cycle of the wave- It receives an tnterrupt signal on Its ikj and 1R3
form that will be on the OUT pin of the counter. inputs at the same time. Assume fixed priority for
Describe the effect that a control word of the IR inputs. What response will the 8259A make
10010000 sent to this 8254 will have. if it is servicing an lR5 interrupt and an 1R3
interrupt signal occurs?
i9. Show the instructions you would use to Initialize
counter 2 of the .8254 In Figure 8-14 to produce a 24. Why Is it necessary to send an End-of-Interrupt
1.2-ms-wide STROBE pulse on its OUT pin when lEOl) command to an 8259A at some time in an
it receives a trigger Input on its GATE input. interrupt-service routine?
25. Show the sequence of command words and instruc-
20. Show the instructions needed to latch and read a tions that you would use to initialize an 8259A
16-bit Count from counter 1 of the 8254 in Figure with a base address of FFIOH as follows; edge-
8-14. triggered; only one 8259A; 8086 system; interrupt
type 40 corresponds to IRO input; normal EOl;
flescrlhe the sequence of actions that, an 8259A nonbuffered mode, not special fully nested mode:
and an 8086. as connected in Figure 8-14. will take lRl and 1R3 unmasked.
wtien the 8259A receives an interrupt signal on its
2 input. Assume only 1R2 is unmasked in the 26. What is the major advantage of calling BIOS proce-
i259A and that the 8086 INTR Input has been dures with software interrupts instead of calling
nab1ed with an STI instruction. them with absolute addresses?

244 CHAPTER EIGHT


Interfacing

The major goal of this chapter and the next Is to show II. Describe how optical encoders are used to deter-
you the citcuitry and software needed to Interface a mine the position, direction of rotation, and speed
basic microcomputer with a wide variety of digital and of a motor shalt.
analog devices. In each topic we try to show enough
detail so that you can build and experiment with these
circuits. Perhaps you can use some of them to control PROGRAMMABLE PARALLEL PORTS AND
appliances around your house or to solve some problems HAN DSHAKE INPUT/OUTPUT
at work.
in this chapter. we concentrate on the devices and Throughout the program examples in the preceding
techniques used to get digital data into and out of the chapters. we have used port devices to input parallel
basic microcomputer. Then, in the next chapter, we data to the microprocessor and to output parallel data
concentrate on analog interfacing. from the microprocessor. Most of the available port
devices, such as the 8255A on the SDK-86 board, contain
two or three ports which can be programmed to operate
in one of several different modes. The different modes
OBJECTIVES allow you to use the devices for many common types of
At the conclusion of this chapter, you should be able to: parallel data-transfer. First we will discuss some of these
common methods of transferring parallel data, and then
I. Describe simple input and output. strobed input we will show how the 8255A is initialized and used In
and output, and handshake input and output. a variety of 110 operations.
2. Initialize a programmable parallel-port device such
as the 8255A for simple Input or output and for Methods of Parallel Data Transfer
handshake input or output. SIMPLE INPUT AND OUTPUT
3. Interpret the timing waveforms for handshake in- When you need to get digital data from a simple switch.
put and output operations. such as a thermostat, into a microprocessor, all you
4. Describe how parallel data is sent to a printer on a have to do is connect the switch to an input port line
handshake basis. and read the port. The thermostat data is always present
and ready, so you can read It at any time.
5. Show the hardware connections and the programs Likewise, when you need to output data to a simple
that can be used to interface keyboards to a micro- display dev1e such as an LED, aU you have to do is
computer. connect the input of the LED buffer on an output port
6. Show the hardware connections and the programs pin and output the logic level required to turn on the
that can be used to interface alphanumeric displays light. The LED is always there and ready, so you can send
to a microcomputer. data to It at any time. The timing waveform In Figure
9-Ia, p. 246. represents this situation. The crossed lines
7, DescrIbe how an 8279 can be used to refresh a on the waveform represent the time at which a new data
multiplexed LED display and scan a matrix key- byte becomes valid on the output lines of the port. The
board. absence of other waveforms indicates that this output
operation is not directly dependent on any other signals.
8. Initialize an 8279 for a given display and keftord
format.
SIMPLE STROBE I/O
9. Show the circuitry used to interface high-power In many applications, valid data is present on an external
devices to microcomputer ports. device only at a certain time, so it must be read in at
10. Describe the hardware and software needed to that time. An example of this is the ASCII-encoded
control a stepper motor. keyboard discussed in Chapter 4. When a key is pressed.

245
read In data only when a strobe pulse tells you that the
DATA
data is valid.
(i Figure 9-lb shows the timing waveforms which repre-
sent this type of operation. The sending device, such as
a keyboard. outpuparallel data on the data lines, and
_____Jf-- then outputs an STB signal to let you know th valid
data is present.
For low rates of data transfer, such as from a keyboard
DATA to a microprocessor. a simple strobe transfer works well.
b) However, for higher-speed data transfer this method
does not work, because there is no signal which tells
the sending device when it is safe to send the next data
STB __ byte. In other words, the sending system might send
data bytes faster than the receiving system could read
them. To prevent this problem, a handshake data
ACK transfer scheme is used.

SINGLE-HANDSHAKE I/O
DATA
Figure 9-2 shows the circuit connections and Figure 9-Ic
shows some example timing waveforms for a handshake
data transfer from a peripheral device to a microproces-
sor. The peripheral outputs some parallel data and sends
STB
f_f an STB signal to the microessor. The microproces-
sor detects the asserted STB signal on a polled or
interrupt basis and reads In the byte of data. Then the
ACK
microprocessor sends an Acknowledge signal lACK) to
the peripheral to indicate that the data has been read
DATA and that the peripheral can send the next byte of data.
From the viewpoint of the microprocessor, this operation
Id) is referred to as a handshake or strobed input.
These same waveforms might represent a handshake
FIGURE 9-1 Parallel data transfer. (a) Simple output. output from a microprocessor to a parallel printer. In
(b) Simple strobe I/O. (C) Single handshake i/O. (d) this case, the microprocessor outputs a character to the
Double handshake i/O. printer and asserts an STB signal to the printer to tell
the printer. "Here is a character for you." When the
printer is ready, it answers back with the ACK signal to
circuitry on the keyboard sends out the ASCII code for tell the microprocessor. "I got that one: send me an-
the pressed key on eight parallel data lines, and then other." We will show you much more about printer
sends out a strobe signal on another line to indicate interfacing In a later section.
that valid data is present on the eight data lines. As The point of this handshake scheme is that the
shown In Figure 4-19. you can connect this strobe line sending device or system is designed so that it does not
to an input port line and poll it to determine when send the next data byte until the receiving device or
you can input valid data from the keyboard. Another system indicates with an ACK signal that it is ready to
alternative, described in Chapter 8. is to connect the receive the next byte.
strobe line to an interrupt input on the processor and
have an interrupt service procedure read in the data DOUBLE-HANDSHAKE DATA TRANSFER
when the processor receives an interrupt. The point For data transfers where even more coordination is
here is that this transfer Is time dependent. You can required between the sending system and the receiving

FIGURE 9-2 Signti directu,ns for handshake input data transfer.

246 CHAP1) NINE


system, a double handshake is used: The circuit con- register. The internal addresses for the device are: port
nections are the same as those in Figure 9-2. Figure A.0O; port B, 01: port C. 10; control. 11. Asserting the
9-Id shows some example waveforms for a double- CS inut of the 8255A enables It for reading or writing.
handshake input from a peripheral to a microprocessor. The CS input will be connected to the output of the
Perhaps It will help you to follow these waveforms by address decoder circuitry to select the device when It is
thinking of them as a conversation between two people. addressed.
In these waveforms each sgpl edge has meaning. The The RESET input of the 8255A is connected to the
sending device asserts its.STB line low to ask, "Are you system reset line so that, when the system is reset, all
ready?" 'the receiving system raises its ACK line high the port lines are initialized as input lines, This is done
to say. "I'm ready." The peripal device then sends the to prevent destruction of circuitry connected to port
byte of data and raises its STB line high to say. "Here lines. If port lines were initialized as outputs after a
is some valid data for you." After it has read in the data. power-up or reset, the port might try to output to the
the receiving system drops its ACK line low to say. "I output of a device connected to the port. The possible
have the data, thank you, and I await your request to argument between the two outputs might destroy one
send the next byte of data." or both of them. Therefore, all the programmable port
For a handshake output of this type, from a micropro- devices initialize their port lines as inputs when reset,
cessor to a peripheral, the waveforms are the same, but We discussed in Chapter 7 how two 8255As can be
the microprocessor sends the STB signal and the data. connected in an 8086 system. Take a took at Figure 7-8
and the peripheral sends the ACK signal. In the accompa- (sheet 5) to refresh your memory of these connections,
nying laboratory manual we show you how to interface Note that one of the 8255As is connected to the lower
with a speech-synthesizer device using this type of half of the 8086 data bus, and the other 8255A is
handshake system. connected to the upper half of the data bus. This is done
so that a byte can be transferred by enabling one device.
or a word can be transferred by enabling both devices
Implementing Handshake Data Transfer at the same time, According to the truth table for the
1/0 port address decoder in Figure 7-16, the A40 82'55A
For handshake data transfer, a microprocessor can
on the lower half of the data bus will be enabled for a
determine when it is time to send the next data byte on
base address of FFF8H. and the A35 8255A will be
a polled or on an interrupt basis. The interrupt approach
enabled for a base address of FFF9H.
is usually used, because it makes better use of the
Another point to notice in Figure 7-8 is that system
processor's time,
address line Al Is connected to the 8255A A0 inputs,
The STB or ACK signals for thesç handshake transfers
can be produced on a port pin by instructions in the and system address line A2 i connected to the 8255A
Al inputs. With these connections, the system addresses
program. However, this method usually uses too much
for the three ports and the control register In the A40
processor time, so parallel-port devices such as the
8255A will be FF'FSH, FFFAH, FFFCH, and FFFEH. as
8255A have been designed to automatically manage the
shown in Figure 7-16. Likewise, the system addresses
handshake operation. The 8255A. for example, can be
for the three ports and the control register of the A35
programmed to automatically receive an STB signal from
8255A are FFF9H, FFFBH. FFFDH. and FFFFI-I.
a peripheral. send an interrupt signal to the processor,
and send the ACK signal to the peripheral at the proper
times. The following sections show you how to connect.
initialize, and use an 8255A for a variety of handshake 8255A Operational Modes and Initialization
and nonhandshake applications. Figure 9-4. p. 249. summarizes the different modes in
which the ports of the 8255A can be initialized,
8255A Internal Block Diagram
and System Connections MODE 0
When you want to use a port for simple input or output
Figure 9-3. p. 248. shows the internal block diagram of
without handshakin'. you initialize that port in mode
the 8255A. Along thc right side of the diagram. you can
0. If both port A and port B are initialized in mode 0.
see that the device has 24 input/output lines. Port A can
then the two halves of port C can be used together as
be used as an 8-bit input port or as an 8-bit output port.
an additional 8bit port, or they can be used individually
Likewise, port B can be used as an 8-bit input port or as
as two 4-bit ports. When used as outputs, the port C
art 8-bit output port. Port C can be used as an 8-bit
lines can be individually set or reset by sendtrig a special
input or output port, as two 4-bit ports, or to produce
handshake signals for ports A and B. We will discuss control word to the control register address. Later we
will show you how to do this. The two halves of port C
the different modes for these tines in detail a little later.
are independent. so one half can be initialized as input.
Along the left side of the diagram. you see the signal
lines used to connect the device to the system buses. and the other half initialized as output.
Eight data lines allow you to write data bytes to a port
or the control register and to read bytes from a port or MODE 1
the status register under the control of the RD and WR When you want to use port A or port B for a handshake
lines. The address inputs, A0 and Al. allow you to (strobed) input or output operation such as we discussed
selectively access one of the three ports or the control in previous sections, you initialize that port in mode I.

DIGITAL INTERFACING 247


• +5V GROUP
POWER
SUPPLIES { A I/O
- GND PORT
GROUP PA7-PAO
A
CONTROL (8)

GROUP
A I/O
PORT C pci-PCI
UPPER
BIDIRECTIONAL (41
DATA BUS
DATA
DI DO BUS
BUrFER 8-BIT
INTERNAL GROUP
DATA BUS 8 I/O
PORT C PC3-PCO
LOWER
(4)

AEAD/
WRITE GROUP GROUP
CONTROL I/O
Al P87-P80
AO

R ESE

FIGURE 9-3 Internal block diagram of 8255A programmable parallel port


device. (Intel Corporation)

in this mode, some of the pins of port C function as board. If port A is Initialized in mode 2, then pins PC3
handshake lines. Pins PCO. PC!. and PC2 function as through PC7 are used as handshake lines for port A.
handshake lines for port BJ1 it is initialized In mode 1. The other three pins. PCO through PC2, can be used for
if port A is initialized as a handshake (mode 1) input 110 if port B is in mode 0. The three pins will be used
port, then pins PC3, PC4, and PC5 function as hand- for port B handshake lines if port B is initialized in
shake signals. Pins PC6 and PC7 are available for use mode I. After you work your way through the mode I
as Input lines or output lines. If portAls Initialized as examples in the following sections, you should have little
then tC pins PC3, PC6, difficulty understanding the discussion of mode 2 in the
and PC7 fctIon as haihkè signâ]: Dort-C- pins Intel data sheet if you encounter it in a system.
1C4 and PC5 are available for use as input or output
lines. Since the 8255A is often used in mode 1. we show
several examples in the foUowlng sections. Constructing and Sending 8255A Control Words
Figure 9-5 shows the formats for the two 8255A control
MODE 2 words. Note that the MSB of the control word tells the
Only port A can be InItialized in mode 2. In mode 2. port 8255A which control word you are sending it. You use
A can be used for bidirectional handshake data transfer. the mode dejinitton control word format in Figure 9-5a
This means that data can be output or Input on the to tell the device what modes you want the ports to
same eight lines. The 8255A might be used in this mode operate In. You use the bit set/reset control word format
to extend the system bus to a slave microprocessor or In Figure 9-Sb when you want to set or reset the output
to transfer data bytes to and from a floppy disk controller on a pin of port C or when you want to enable the

248 CHM'TER NINE


CONTROL WORD

07 106 105 104 103 ID? 101100 GROUP B

PORT C (LOWER)
1 = INPUT
O = OUTPUT

PORT B
07-DO AO-AI I = INPUT
O OUTPUT
•255A
C MODE SELECTION
SI - A
0 MODE 0
1 - MODE 1
'C
HANOSI4AKE j" 'IO j'o
•GRM.0 j'I0

P87-RIO PC-PcO PC7-PC4 A7-PAO


GROUP A

PORT C (UPPER)
INPUT
S P PCI PC? PC? PC' PCS PC6 PC? A f O OUTPUT

1.11111110
P87 -P80 11T8 ISP 1 rtç 1NTR 8
OR OR
fl1
OR
ISF I/O I/O PA7.P*O
OR OR OR
PORT A
INPUT
O = OUTPUT

HANDSHAKE ____- oiç IIO 00 MODE 0


I-UT 01 - MODE 1
SIGNALS 1X MODE 2
- PORT A. PORTS CONTROL HANDSHAKE
Oar-UT
SIGNALS

MODE SET FLAG


PC? PCI PC? PC? PC PCS PC? PC? A J 1 - ACTIVE

S S

P.7-Plo INTH IBPj OäF Pn7-P*O


";—
CONTROL -___________________ El-
PORT ACONTROI. CONTROL WORD
___________________________ DIR ECTIONAL
PONTIMAVIE SUS
51005 0 OR 51000 07 06 05 04 03 02 DI DO BIT SET/RESET
= SET
0 = RESET
FIGURE 9-4 Summary of 8255A operating modes.
(Intel Corporation)
.75-S. BIT SELECT
interrupt output signals for handshake data transfers. DON'T 01 2 3 4 5 6 7 J
O 1 0 1 _0 I 0 1
CARE
Both control words are sent to the control register 001 1001 1(511
address of the 8255A. 0000tli i

As usual. Initializing a device such as this consists of


working your way through the steps we described in the
last chapter. As an example for this device, suppose that BIT SET/RESET FLAG
you want to initialize the 8255A (A40) in Figure 7-8 as 0 = ACTIVE
foUows:
It)
Port B as mode 1 input
FIGURE 9-5 8255A control word formats. (a) Mode-set
Port A as mode 0 output control word. (b) Port C bit set/reset control word.
Port C upper as inputs
Port C bIt 3 as output any Control wordsyou make up for use in your programs.
Using Figure 9-5a, work your way through this word to
As we said previously, the base address for the A40 make sure you see why each bit has the value it does.
8255A is FFFSH. and the control register address is To send the Control word, you load the control word
FFFEH. The next step is to make up the control word in AL with a MOV AL,I000IIIOB instruction, point
by figuring out what to put in each of the little boxes. DX at the port address with the MOV DX.OFFFEH
one bit at a time. Figure 9-6a. p. 250. shows the control instruction, and scnd the control word to the 8255A
word which will program the 8255A as desired for this ex- control register with the OUT DX.AL instruction.
ample. The figure also shows how you should document As an example of how to use the bit set/reset control

DIGITAL INTERFACING 249


tape. Each instruction is represented by a series of holes
07 D6 D5 04 03 02 Di o
in the tape. A tape reader pulls the tape through an
1IG optical or mechanical sensor to detect the hole patterns
and converts these to an 8-bit parallel code. The micro-
PORT C BIT 3 computer reads the instruction codes from the tape
PORT B INPUT
reader on a handshake basis and sends the appropriate
PORT B MODE 1
PORT C UPPER - control instructions to the lathe. The microcomputer
PORT A OUTPUT must also monitor various conditions around the lathe.
PORT A MODE It must, for example. make sure the lathe has cutting
- - MODE SET WORD lubricant oil, is not Out of material to work on. and'is
not Jammed up in some way. Machines that operate in
this way are often referred to as computer numerical
control, or CNC. machines.
07 06 D5 04 D3 02 Figure 9-7 shows in diagram form how you might use
an 8255A to interface a microcomputer to the tape
I Ø I G I B I B I °l Ii reader and lathe. Later in the chapter. we will show you
some of the actual circuitry needed to interface the port
SET BIT
pins of the 8255A to the sensors and the high-power

-- L
I________________________ } BIT #3

BIT SET/RESET WORD


motors of the lathe. For now, we want to talk about
initializing the 8255A for this application and analyze
the timing waveforms for the handshake input of data
from the tape reader.
Ib) Your first task is to make up the control word which
will initialize the 8255A in the correct modes for this
FIGURE 9-6 Control word examples for 8255A. application. To do this, start by making a list showing
(a) Mode-set control word. (b) Port C bit set/reset how you want each port pin or group of pins to function.
control word to set bit 3. Then put in the control word bits that implement those
pin functions. For our example here.

word, suppose that you want to output a Ito (set) bit 3 Port A needs to be initialized for handshake input (mode
of port C. which was initialized as an output with the 1) because instruction codes have to be read In from the
mode set control word above. To set or reset a port C tape reader on a handshake basis.
Output f)ifl, you use the bit set/reset control word shown
in Figure 9-5b. Make bit D7 a 0 to identify this as a bit
set/reset control word. and put a I in bit DO to specify
that you want to set a bit of port C. Bits D3. D2. and INTERRUPT
P E DUE ST
Dl are used to tell the 8255A which bit you want to act
on. For this example you want to set bit 3, so you put
PC3 IAOl.
011 in these 3 bits. For simplicity and compatibility IpAIL---1
with future product. make the other 3 bits of the A? 8 LEVEL
IPA2 L— PAPER
control word 0's. Th result. 0000011 lB. is shown with IPA3I___________ TAPE
proper documentation in Figure 9-6b. 1PA41
l'AsI
-lR5 READER
To send this control word to the 8255A. simply load MODE 1 _________
INPUT)
it into AL with the MOV AL.00000I jiB instruction,
point DX at the control register address with the MOV
DX.OFFFEH Instrucuon if DX is not already pointin& ACK
there, and send the control word with the OUT DX.AL STOP/GO
instruction. As part of the application examples in the
8255A
following sections. we will show you how you know
which bit in port C to set to enable the interrupt output MODE 0
signal for handshake data transfer. (INPUT) PC2
OUT OF FLUID

8255A Handshake Application Examples P80 - CHANGE TOOL


P81 LEFT/RIGHT
PB? UP/DOWN
INTERFACING TO A - HOP. STEP STROBE
MICROCOMPUTERCONTROlLED LATHE MODE 0 P3
(OUTPUT) P84 VERT. STEP STROBE
PBS SLEW/STEP
All the machines tn the machine shop of our computer.
P96 - FLUID ENABLE
controlled electronics factory operate under microcom- P97 EMERGENCY STOP
puter control. One example of these machines is a lathe
which makes bolts from long rods of stainless steel. The FiGuRE 9-7 interfacing a microprocessor to a tape
cutting instructions for each type of bolt that we need
to make are storeJ on a 3/4ifl,-widC teletype like metal reader and lathe.

250 CHAF'TtR ..i?'t


Port B needs to be initialized for simple output (mode Port C To Enabte
0). No handshaking is needed here because this port is Interrupt Sgnat Interrupt Request
Pin Nasber Set Port C bit
being used to output simple on or off control signals to MODE 1
the lathe. Port A IN P03 PC4
Port 8 IN PCO PC2
Port C. bits PCO. 1.and PC2 are used for simple Input Port A OUT PCO PC6
of sensor signals from the lathe. Port 8 OUT PCO PC2
Port C, bits PC3, PC4, and PC5 function as the hand- MODE
shake signals for the data transfer from the tape reader Port A IN PC3 PC4
connected to port A. Port A OUT PC3 PC6

Port C, bit PC6 is used for output of the STOP/GO signal FIGIJRL 9-9 Port C bits to set to enable interrupt
to the tape reader. request outputs for handshake modes.
Port C. bit PCi is not used for this example.
Figure 9-8 shows the control word to initialize the After initializing everything, you would probably read
8255A for these pin functions. You send this word to port C. bits PCO, PCI. and PC2 to check if the lathe was
the control register address of the 8255A as described ready to operate. For any 8255A mode, you read port C
above. by simply doing an Input from the port C address. Then
Before we go on. there is one more point we have to you output a start command to the tape reader on
make about initializing the 8255A for this microcom- bIt PC6. ThIs Is done with a bit set/reset command.
puter-controlled lathe application. in order for the hand- Assuming that you want to reset bit PC6 to start the
shake input data transfer from the tape reader to work tape reader, the bit set/reset control word for this Is
correctly, the interrupt request signal from bit PC3 has. 00001100. When the tape reader receives the Go com-
to be enabled. This is done by sending a bit set/reset mand, it will start the handshake data transfer to
control word for the appropriate bit of port C. Figure 9-9 the 8255A. Lets work our way through the timing
shows the port C bit that must be set to enable the waveforms in Figure 9-10, p. 252. to see how the'data
Interrupt output signal for each of the 8255A handshake transfer takes place.
modes. For the example here, port A is being used for The tape reader starts the process by sending out a
handshake input, so according to Figure 9-9. port C. byte of data to port A on its eight data lines. The tape
bit PC4 must be set to enable the interrupt output for reader then asserts its STB line low to tell the 8255A
this operation. The bit set/reset control word to do this that a new byte of data has been sent. In response, the
is 000010015. You send this bit set/reset control word 8255A raises its Input Buffer Full (IBF) signal on PC5
to the control address of the 8255A. high to tell the tape reader that it is ready for the data.
Handshake data transfer from the tape reader to the When the tape reader detects the ISP signal at a high
8255A can be stopped by disabling the 8255A interrupt level, it raises its STB signal high again. The rising edge
output on port C, pin PC3. Th's Is done by resetting bit of the STB signal has two effects on the 8255A. It first
PC4 with a bit set/reset control word of 00001000. You latches the data byte in the input latches of the 8255A.
will later see another example of the use of this interrupt Once the data is latched, the tape reader can remove the
enable/disable process in Figure 9-16. data byte in preparation for sending the next data byte.
As another example of 8255A interrupt output en- This Is shown by the dashed section on the right side
abling, suppose that you are using port B as a handshake of the data waveform in Figure 9-10. Second. if the
output port. According to Figure 9-9. you need to set, bit interrupt sig output has been enabled, the rising
PC2 to enable the 8255A Interrupt output signal. The edge of the STB signal will cause the 8255A to output
bit set/reset control word to do this is 00000:101. an Interrupt Request signal to the microprocessor on
Now let's talk about how the program for this machine bit PC3.
might operate and how the handshake data transfer The processor's response to the interrupt request will
actually takes place. be to go to an interrupt service procedure which reads
in the byte of data latched In port A. When the RD signal
from the microprocessor goes low for this read of port A,
the 8255A will automatically reset its Interrupt Request
07 06 05 D4 03 02 Dl D
signal on PC3. This Is done so that a second interrupt
1 1 1 0 1 1 1 iloIsIiI cannot be caused by the same data byte transfer. When
the processor raises its RD signal high again at the end
I PORTCLOWERIN of the read operation, the 8255A automatically drops Its
PORT 8 OUTPUT IBF signal on PC5 low again. 1SF going low again is the
PORT B - MODE 0 signal to the tape reader that the data transfer is
PORT C UPPER OUT complete and that it can send the next byte of data. The
PORT A INPUT
PORT A MODE I time between when the 8255A sends the Intemapt
MODE SET WORD Request signal and when the processor reads the data
byte from port A depends on when the processor gets
FIGURE 9-5 Control word to intialize 8255A for around to servicing that interrupt. The point here Is
interface with tape reader and Iahe. that this time doesn't matter. The tape reader will no

DIGITAL INTERFACING 251


34
MODE 1 ISTROBED INPUT)

FROM TAPE STB


READER TO
8255
FROM 8255 1SF
TO TAPE
READER
FROM 8255 INTR
TO 8259A

FROM 8086 AD
TO 8255

DATA INPUT FROM


PERIPHERAL

FIGURE 9-10 Timing waveforms for 8255 handshake data input from a tape
reader.

C -nd the next byte of data until It detects that the IBF a printer must he done on a handshake basis because
signal has gone low again. The transfer cycle will then the microcomputer can send characters much faster
repeat for the next data byte. than the printer can print them. The printer must in
After the processor reads in the lathe control instruc- some way let the microcomputer know that its buffer is
tion byte from the tape reader, it will decode this full and that it cannot accept any more characters until
instruction, and output the appropriate control byte to it prints some out. A common standard for interfacing
the lathe on port B of the 8255A. The tape reader then with parallel printers is the Cent ronics Parallel Interface
sends the next instruction byte. If the instructldn tape Standard, named for the company that developed it. In
is made into a Continuous loop, the lathe will keep the following sections, we show you how a Centronics
making the specified parts until it runs out of material, parallel interface works and how to implement it with
The unused bit of port C. PCi, could b. "nnnected to a an 8255A.
mechanism which loads jr. more matr, m'I so the lathe
continue,
The microcomputer-controlled ithe w. htve thrbe'i Centronics Interface Pin Descriptions
here is a small example ( uomated manuiacurrIg. and Circuit Connections
The advantage of this approac th t relieves hum-s Centronics-type printers usually have a 36-pin interface
of the drudgery of standing mi h of a ma-hlne connector. Figure 9-li shows the pin assignments and
continually making the sime part. rh after day, We dscriptions for this connector as it is used in the IBM
hope society can find more productive for the human C printer and the Epson printers. Some manufacturers
time made available. use one or two pins differently, so consult the manual
for your specific printer before connecting it up as we
PARALLEL PRINTER INTERFACE—i-1AN)SI lAKE show here.
OUTPUT EXAMPLE 'ihirty-six pins may seem like a lot of pinsJust to send
At the end of Chapter 8. we showed you how to send a ASCII characters to a printer. The reason for the large
string of text characters to a printer by calling a BIOS number of lines is that each data and signal line has its
procedure with a software Interrupt. In this section own individual ground return line. For example, as
we show you the hardware connections and software shown In Figure 9-il. pin 2 is the LSB of the data
required to interface with a parallel printer in a system character sent to the printer, and pin 20 is the ground
which does not have a BIOS procedure you can call to return for this signal. Individual ground returns reduce
do the Job. the chance of picking up electrical noise in the lines. If
For most common printers, such as the IBM PC you are making an interface cable for a parallel printer.
printers, the Epson dot-matrix printers, and the Pana- these ground return lines should only be connected
sonic dot-matrix printers, data to be printed is sent to together and to ground at the microcomputer end of the
the printer as ASCII characters on eight parallel lines. cable, as shown in Figure 9-12. p. 254.
The printer receives the characters to be printed and While we are talking about grounds. note that pIn 16
stores them in an internal RAM buffer. When the printer is listed as logic ground and pin 17 is listed as chassis
detects a carriage return character IODH). It prints out ground. In order to prevent large noise currents from
the first row of charactès from the print buffer. When flowing in the logic ground wires, these wires should
the printer detects a second carriage return, it prints only be connected together in the microcomputer. (This
Out the second row of characters. etc. The process precaution is necessary whenever you connect any exter-
continues until all the desired characters have been nal device or system to a microcomputer.)
printed. The rest of the pins on the 36-pin connector fall into
Transfer of the ASCII codes from a microcomputer to two categories: signals sent to the printer to tell it what

252 CHAPTER NINE


SIGNAL RETURN DIRECTION


SIGNAL DESCRIPTION

STROBE puIw to read data in. PuI,. width mss ben ethnO.Siesstr.ceivingtermfrisl. The
1 -
______ 19 SIR IN level is normally 'lsjgh"; reed-in of data ii performed at the "(Ow" livel of this signal.
2 20 DATA1 IN
3 21 DATA2 IN
4 22 DATA3 IN
5 23 DATA 4 IN These tignalt represent information of the let to 8th bits of petellil data r,ectively. Each
24 DATA5 IN t1,Mnduog1 and'iow"wh.nlogical"O."
7 25 DATA6 IN
8 26 OATA7 IN
• 27 DATA8 IN
28 ACKNLG Approeimate!y5pspolw"iratesthetdatahaibeenrecaivsdandth.pnnteri.
OUT
reedy to accept other data.
A "high" signal indicates that the printer cannot receive data. The signal becomes "high"
in the following cases:
Ii BUSY OUT 1. During data envy. - 3. in "offima" dat..
2. During printing operation. 4. Owing printer error satus,
12 30 Pt OUT A"hgh"tign.Iindicete.th.tth.print.risoototpaper.
13 - SLCT OUT Th,ssignaIiatesthatthprinterisintheielictadRate.
14 - AUTO With this ,ign.I being C 'low" level, the pap. ii automatically fed one Iln.alter printing, (The
IN signal level can be fixed to "low"with DIP SW pin 2-3 provided on the control clrcuitboald.)
_________ _________ FEED XI
IS - NC Not oued.
18 - DV Logic GNO level,
17 - CHASIS- Printer chatis GNO. In the printer, the chassis GNO and the logic GNO are ilased front
ONO - eachothar.
18 - NC - Notud. -
19-30 - GND - "1w Ii, etun,' sign.I ONO level.
When the level of this signal b,comes "low" the prInter controller is reset to its initial date
31 - 1Th'f IN - and the print buffer is cleared. This signal is normally at "hig" level, and it. pulls width
must be nor, than 50 ss at the receiving terminal,
The level of this signal becomes "(ow" when the printer is in "Paper End" seats, "Off line"
0 OUT state and 'Error" state.
33 - GNO - San, atwith pin number, 19 to 30.
34 - NC - Notuted.
35 Polled op to +5 Vdc throtgh 4,7 k-ohms resistance.
Data entry to the printer is possibl, only when the level of thu signet is "low." (Intirnel
- SLCT IN IN fising can be carried out with DIP SW 1-8. The condition at the time of thipvn.m is let
___________ ___________ ___________- __________ "low" for thi, aignal,l

Notes: 1. "Direction" refers to the direction of signal flow as viewed from th, printer.
2. "Return' denotes "Twisted-Pair Return" and is to be connected at signal-ground level,
When wir,trg the nterfec., be sure to use a twisted-pair cable for each signal and never fail tø complete connection on the return side. To prevent
noise effectively, these cables should be shielded and connected to the chiuls of the system unit.
3. All interface conditiont are based on TTL level. Both the rise and fall tirnesof each signal most be lela than 02 so'
4. DaIs transfer stunt not be carried Out b y ignoring the ACKNLG or BUSY signal. Data transfer to thu printer can be carried out only after
confirming the ACXNLG signal or when the level of the BUSY signal is "low."l

FIGURE 9-11 Pin connections and descriptions for Centronics-type parallel


interface to IBM PC and EPSON FX-ltE printer, (IBM Corporation)

operation to do, and signals from the printer that 2. The BUSY signal on pIn 11. which Is high If. før
Indicate Its status. The major control signals to the some reason such as being out of paper, the printer
printer are INIT on pin 31, which tells the printer to is not ready to receive a character.
perform its Internal initialization sequence, and
STROBE on pin 1, which tells the printer, "Here Is a 3. The PE signal on pIn 12. winch goes high If the out-
character for you." Two additional input pins, pin 14 of-paper switch In the printer Is activated.
and pIn 36, are usually taken care of inside the printer.
The major status signals output from the printer are 4, The SLCT signal on pin 13, which goes high if the
printer Is selected for receiving data.
I. The ACKNLG signal on p1 n 10. which, when low,
indicates that the data character has been accepted 5. The ERROR signal on pin 32. which goes low for a
and the printer Is ready for the next character. variety of problem conditions in the printer.

OICITM INTERFACING 253


IBM 25-FIN PRINTER


INTR TO 8086 OR 825A CONNECTOR-i r- CONNECTOR
PIN NUMBERS
PIN NUMBERS

ERROR
PE
SLCT OUT
BUSY
NC
PlC
NC
NC
NC
NC
ACKNLG

STB
INIT

DATA 1
DATA 2
DATA 3
DATA 4
DATA 5
- DATA 6
DATA 7
DATA 8
30. 33-RET
LOGIC GND
IC 1 AND 2 ARE 74LS07 CHASSIS GND
Vc -PIN 14
OND PIN 7

SURE 9-12 Circuit for interfacing Centronics-type parallel input printer to


on SDK-86 board.

hgure 9-13 shows the timing waveforms for transfer- Indication that the printer is ready to accept the next
ring data characters to an IBM printer using the basic character. Some systems use the ACKNLG signal for the
handshakesignals. Here how this works. handshake, and some systems use the BUSY signal.
Assuming the printer has been initialized, the BUSY Now let's see how you can do this handshake printer
signal is checked to see ic the 1 rinter is ready to receive interface With an 8255A.
data. if this signal is low, indicating the printer is ready
(not busy), an ASCII code is sent out on the eight parallel 8255A CONNECTIONS AND INITIALIZATION
data lines. After at least 0.5 p.s. the STROBE signal is
asserted low to tell th printer that a character has been For this example, we disconnected our printer cable
sent. The STROBE signal going low causes the printer from the printer output and connected It to an 8255A
to assert its BUSY signal high. After a minimum time on an SDK-86 board, as shown in Figure 9-12. The
of 0.5 p.s. the STROBE signal can be raised high again. 74L507 open-collector buffers are used on the signal
Note that the data must be held valid on the data lines and data lines from the 8255A because the 8255A
for at ieast 0.5 p.s after the STROBE signal Is made high. outputs do not have enough current drive to charge and
-When the printer is ready to receive the next character. discharge the capacitance of the connecting cable fast
it asserts its ACKNLO_signal low for about 5 s. The enough. Pull-up resistors for the open-collector outputs
rising edge of the ACKNLG signal tells the microcom- of the 74LSO7s are built Into the printer.
puter that it can send the next_character. At the same Port B of the 8255A Is used for the handshake output
time as the rising edge of the ACKNLG signal. the printer data lines. Therefore, as shown in Figure 9-4, bit PCO
also resets the BUSY signal. A low on BUSY is another functions as the Interrupt request output to the 8086.

25-4 CHAPTER NINE


the upper 4 bIts of port C as outputs. Figure 9-14b


BUSY
L__J shows the bit set/reset control word necessay to enable
—1 I-- APt' R oXIM A T E LY 5p3 the Interrupt request signal on bit PCO for the hand-
shake. The addresses for the 8255A, A35, on the SDK.
ACKNLG 1j 86 board are, as shown in Figure 7-16. port P1A—FFF9H;
1—O.5(MINlMUMl
-1 port P1B—FFFBH; port P1C—FFFDH; and control Pt-
DATA ______ I FFFFH. For that system, then, both control words are
output to FFFFH.
I H h-°•'' IMINIMUMI
STROBE [__J THE PRINTER DRIVER PROGRAM
—I .- 0.5s (MINIMUM) Procedures which input data from or output data to
peripheral devices such as disk drives, modems, and
FIGURE -13 Timing waveforms for transfer of a data
printers are often called I/O driuers. Here we show you
characte'r to a Centronics-type parallel printer such as
one way to write the I/O driver procedure for our pas'allel
the IBM-PC or Epson printer. (IBM Corporation)
printer interface.
The first point to consider when writing any I/O driver
is whether to do it on a polled or on an Interrupt basis.
The ACKNLG signal from the printer is connected to the
For the parallel Centronics interface here, the maximum
8255A ACK input on bit PC2. The OBF signal on PC!
data transfer rate is about 1000 characters/second. Thiá
of the 8255A would normally be used as the strobe signal
means that there is about I ms between transfers. If
for this type of handshake data transfer. Unfortunately.
characters are sent on an interrupt basis, many other
however. it does not have the right timing parameters
program instructions can be executed while waiting for
for this handshake, so it is left unconnected. Therefore.
the interrupt request to send the next character. Also.
the STROBE input of the printer is connected to bit
when the printer buffer gets full, there will be an even
PC4. The STROBE signal will be generated by a bit setl
longer time that the processor can be working on some
reset of this pin.
other Job while waiting for the next Interrupt. This is
The four printer status signals are connected to port
another illustration of how interrupts allow the com-
A so the program can read them In to determine the
puter to do several tasks "at the same time." For our
condition of thpinter.
elcample here, assume that the lnterrupt . request from
Finally, the INIT input of the printer is connected to
PCO of the 8255A is connected to the 1R6 interrupt Input
bit PC5 so that the printer can be initialized under
of the 8259A shown in Figure 8-14. The higher-prIority
program control.
interrupt Inputs on the 8255A are left for a clock
Now, while the hardware configuration is fresh In your
interrupt and a keyboard interrupt.
mind. let's look at the control words we have to send to
the 82.55A for this application. Figure 9-15a, p. 256. shows the steps needed In the
Figure 9-1 4a shows the mode control word to initialize mainline to initialize everything and "call" the printer
port B for mode I output, port A for mode 0 input, and driver to send a string of ASCII characters to the printer.
At the start of the mainline some named memory
locations are set aside to store parameters needed for
transfer of data to the printer. The memory locations
07 06 05 04 03 02 Dl DO
set aside for passing information between the mainline
I ilololilolilolol and the i/O driver procedure are often called a control
block. In the control block, a named location is set aside
ft
I CLOWERX for a pointer to the addresr of the ASCII character that
B"0UT is currently being sent. Another memory location is set
a MODE 1 aside to store the number of characters to be sent. The
C UPPER OUT
A INPUT
number In this location will function as a counter so
A MODE 0 you know whe(t you have sent all the characters in the
MODE SET WORD buffer. Instead of uing this counter approach to keep
track of how many characters have been sent, a sentinel
(I
method can be used. With the sentinel approach you put
a sentinel character in memory after the last character to
07 06 05 D4 D3 D2 01 00 be sent Out. MS/DOS. for example, uses a $ (24H) as a
sentinel character for some of the 110 drivers. As you
IoIoIo!olo!lIoIil read each character in from memory, you compare It
with the sentinel value. If it matches, you know all the
L_ SET TO ENABLE
BIT 2 CONTROLS INTR ON PCO characters have been sent. The sentinel approach and
DONT CARES the count-r approach are both widely used, so you
BIT SET/RESET CONTROL WORD should be lamliar with both.
Ib) To get the hardware ready to go. you need to initialize
the 8259A and unmask the IR Inputs of the 8259A that
FIGURE 9-14 8255A control words for printer interface. are used. The 8086 INTR input must also be enabled.
(a) Mode control word. (b) Bit set/reset control word. Next, the 8255A must be Initialized by sending it the

DIGITAL INTERFACING 255


MAINLINE ALGORITII FOR PRINTER &LY! PlNTER PR0EDURE ALGORITHM
I NIT I AL I ZAI 1011 Save registers
Set ç control block Enable 8086 INTR for higher priority interrI.ts
Word for storing pointer to ASCII string Get pointer to string
Word for n.rt.r of charatars in string Get ASCII character from buffer
Initialization control vords to RS9A Send character to printer
Urisesk 8259A IR6 end any other IR inputs used Wait 5 .s
Mode set word to 8255A Send STROBE tow
Unaask 8086 INTR input Welt 5 g
Send STROBE high to printer Send STROBE high
Initialize printer (pulse 1*111 tow) Increment pointer to string
TO SEND ASCII STRING Decrement character coij'ter
Read printer status from port IF character co.rt 0 THEN
IF error THEN Disable 8255A interri,t request output
send massage Send EOI command to 8259A
exit, ter*lnate progr Restore registers
Set print done status bit Return from interrt proce&l-e
Lo.d starting doress of string into pointer store
Load length of string Into character Coslter
Enable 8255A IPITR output
Wait for interrt
(a) (5)

FIGURE 9-15 Algorithm for printer mainline and interrupt-based printer driver
procedure. (a) Mainline steps. (b) Printer driver procedure steps.

mode control word shown in Figure 9-14a. A bit seti priority interrupts such as a clock can Interrupt this
reset control word is then sent to the 8255A to make procedure. The string address pointer is then read in
the STROBE signal to the printer high, because this is from the control block and used to read a character In
the unasserted level for the signal. When interfacing from the memory buffer to AL. The character in AL is
with hardware, you must always remember to put control then output to port B of the $255A.
and handshake signals such as this in known states. From here on. the program follows the timing diagram
Also, to make sure the printer is internally initialized, in Figure 9-13. After sending the character,_the program
we pulse the INIT line to the printer low for a few waits at least 0.5 p.s. asserts the STROBE input low,
microseconds. waits at least another 0.5 p.s. and raises the STROBE
When we reach a point in the mainline where we line high again. As we said before, the strobe signal
want to print a string, we first read the printer status must be generated with program instructions because
from port A and check if the printer is selected, not the hardware strobe signal generated by the 8255A does
out of paper, and not busy. In a more complete not have the correct timing for this handshake. The
program, we could send a specific error message to data hold parameter in the timing diagram Is satisfied
the display indicating the type of error found. The because the data byte will be latched on the port B
program here Just sends a general error message. If output pins until the next character is sent. Sending of
no printer error condition is found, the starting the character is now complete, so the next step is to get
address of the string of ASCII characters is loaded ready to send another character.
into the control block location set aside for this, and To do this, the buffer pointer in the control block is
the number of characters in the string is sent to incremented by 1. and the characier counter In the
a reserved location in the control block. Finally, the control block is decremented by 1. If the character
interrupt request pin on the 8255A is enabled so that counter is not down to 0, there are more characters to
printer interrupts can be output to the 8259A IR input. send, so the EOI command is sent to the 8259A, the
Note that this interrupt is not enabled until everything registers are popped off the stack, and execution is
else is ready. To see how this algorithm is implemented returned to the mainline to wait for the next Interrupt.
in assembly language, work your way through Figure If the character counter in the control block Is down to
9-1 6a. The JMP wr at the end of this program represents 0. all the characters have been sent, so the Interrupt
continued execution of the mainline program while Request output of the 8255A is disabled with a bit
waiting for an interrupt from the printer. set/reset control word. This prevents further interrupt
A high on the ACKNLG line from the printer will cause requests from the 8255A until we enable it again to send
the 8255A to output an Interrupt Request signal. This another buffer of characters to the printer. Work your
Interrupt Request signal goes through the 8259A to the way through Figure 9-16b to see how this algorithm is
processor and causes it to go to the interrupt service easily implemented. One part of the program that we do
procedure. want to expand and clarify is the generation of the
Figure 9-15b shows the algorithm for the procedure STROBE signal with bit PC3.
which services this interrupt and actually sends the We could use external hardware to "massage" the OBF
characters to the printer. After some registers are signal from the 8255A so it matches the timing and
pushed, the 8086 INTR input is enabled so that higher. polarity requirements of the receiving device. However.

256 CHAPTER NiNE


;8086 MAINLINE PROGRAM F9-16A.ASM


2 ;ABSTRACT Printer-driver lnline Inttiatizes the 8259A and the 8255A
3 en an SDK-86 board so that a message in a buffer can be sent
4 to a printer. It also sets t a control block and initializes
S all variables used
6 ;REGISTERS : Us.s CS.DS,SS,SP,AX,DX,Cx,
7 ;PORTS SD-86 port P1A (FFF9H) - used to input status of printer
8 port P15 (FFFBH) - used to output a character
9 port PlC used for handshake signals for port B
10 ;PROCEDURES: Uses PRINT_IT used to output characters
ii
12 0000 A_tNT_TABLE SEGMENT K)RD
13 0000 0C(O000) TYPE_64_69 DV 12 DUP(0) Reserved for IRO-1R5
14 0018 02*(0000) TYPE 70 DV 2 DUP(0) IR6 interrupt
15 OO1C 02*(0000) TYPE_71 DV 2 DUP(0) 187 interrupt - not used
16 0020 A_INT_TABLE ENDS
17
18 0000 DATA SEGMENT D PUBLIC
19 0000 54 68 69 73 20 69 73 * MESSAGE_i DB 'This is the message from the printer driverH
20 20 74 68 65 20 60 65 +
21 73 73 61 67 65 20 66 +
22 72 6F 60 20 74 68 65 +
23 20 70 72 69 6€ 74 65 +
24 72 20 64 72 69 76 65 •
25 72 21
26 002C 00 OA 00 DB 0011, OAM, 0011 Return & line-feed for printer
27 002!' MESSAGE_LENGTH EQU (S-MESSAGE_i) Coipute length of message
28 002F 00 PRINI_DORE 08 0
290030 0000 POINTER DV 00 Storage for pointer to MESSAGE_i
30 0032 00 WiNTER 05 0 Counter for length of MESSAGE_i
31 0033 00 PRINTER_ERROR DB 0
32 0034 DATA ENDS
33
34 PtLIC PRINT_DONE, POINTER, C00NTER, MESSAGE 1
35 EXTRN PRINT_IT:FAR
36
37 0000 STACK_SEC SEGMENT
38 0000 1 E* <0000) DV 30 DUP(0)
39 STACK_TOP LABEL lRD
40 003C STACK_SEG ENDS
41
42 0000 C00E SEGMENT LRD PUBLIC
43 ASS*J4E CS:CCOE, DS:A_INT_TABLE, SS:STACK_SEG
44 ;Initialize stack and data segment registers
45 0000 88 0000s NOV AX, STACK_SEC Initialize stack
46 0003 SE DO NOV SS, AX segment register
47 0005 BC 003Cr NOV SP, OFFSET STACK_TOP Initialize top of stack
48 0008 88 0000s NOV AX, A_HIT_TABLE Initialize data
49 0005 SE D8 NOV DS, AX segment register
50 ;Set ç interrupt table and put in address for prin:er interrupt subroutine
51 0000 Cl 06 OOlAr 0000s NOV TYPE_70+2, SEC PRINT_IT
52 0013 Cl 06 0018r 0000e NOV TYPE_TO, OFFSET PRINT_IT
53 ;Initielize data segment register
54 ASSLME DSOATA
55 0019 88 0000s NOV AX, DATA
56 OO1C 8€ 08 NOV OS, AX
57 ;Initialize 8259A and urynask 186
58 OO1E BA FF00 NOV DX, OFFOOII ; Point at 8259A control address
59 0021 BO 13 NOV AL, 000100118 ICW1, edge triggered, single, 8086
60 0023 EE 00T DX, AL Send ICW1
61 0024 BA FF02 NOV DX, OFFO2H Point at 1CW2 address
62 0027 50 40 NOV AL, 010000008 Type 4 is first 8259A type
63 0029 EE 001 DX, AL Send 1CW2
64 002A BO 01 NOV AL, 000000018 ICW4, 8086 mode
65 002C EE 00T DX, AL Send 1CW4
66 0020 SO SF NOV AL, 101111119 OCWi to .nnask 186
67 002F EE 001 DX, AL Send OCWi
68 ;Initialize 8255A, MA-model input. P1B-niodeO output. Unused PlC bits-output
69 0030 BA F!'!'!' NOV DX, OFFFFH Control address for 8255A
70 0033 80 94 NOV AL, 100101008 Control word for above conditions
71 0035 EE 001 DX, AL Send control word
72 0036 FB 511 ; IJr'mask 8086 !NTR interrupt

FIGURE 9-16 8086 assembly language program for driver. (a) Mainline.
(Continued)

DIGITAL INTERFACING 257


73 ;Send strobe hIg4 to pcinter with bit set on PCI.


74 0037 80 09 NOV AL, 000010018
75 0039 EE J1 DX, AL
76 ;lnitiatize printer-pulse lull tow for 50 useconds (on PC5)
77 003A 80 CC NOV AL, 000011018 Bt set on PCS
78003C EE JT DX, AL Send 11411 high
790030 80 OC NOV AL, 000011008 ; Bit reset on PC5
80 003F EE O.JT DX, AL Send 11411 tow
81 0040 89 0017 NOV CX, uN Wait 50 useconds
82 0043 E2 FE PAUSEI: L PAUSEI
83 0045 no CC NOV AL, 000011018 Bit set on PC5
84 0047 EE OJT DX, Al Send 11411 high again
85 ;Read printer status from port A, status OK - AL XXXXO1O1
86 ;PA3-BUSYO, PA2-SLCTI. PA1-PEO, PA0-ERR0R1
87 0048 Co oo 0033r 00 NOV PRINTER_ERROR. 0 Printer OK so far
88 0040 BA FFF9 NOV DX, OFFF9II Point at port A
89 0050 EC IN AL, DX Get printer status
90 0051 24 OF AND AL, OFH ; Upper 4 bits not used
91 0053 3C 05 CMP AL. 000001O1B If Status OK then
92 0055 74 14 JZ SEND_IT ; send It
93 ;etse printer not ready, wait 20 ms and try again
94 0057 B9 16€A NOV CX, I6EAH Load cotxt for 20 s
95 OOSA E2 FE PAUSE: LCCP PAUSE and wait
96 005C EC IN AL, DX Repeat steps to read status
97 005D 24 OF AND AL. OFH
98 005F 3C 05 CIP AL, 000001018
99 0061 74 08 JZ SEND IT If printer not ready then
100 0063 C6 06 0033r 01 NOV PRINTER_ERROR, 01 set error code and
101 0068 EB 19 90 JMP FIN terminate program
102 ;eise Set U pointer to message storage and say print not done yet
103 0069 98 0000r SENO_IT:MOV AX. OFFSET MESSAGE_I
104 006E A3 0030r NOV POINTER, AX
105 0071 C6 06 OO2Fr 00 NOV PRINT_DONE, 00
106 0076 C6 06 0032r 2F NOV CI).JNTER, MESSAGE_LENGTH
107 ;Enable 8255A interrupt request output on PCO by settng PC2
108 007B BA FFFF NOV OX, OFFFFH ; Point at port controL addr
109 OOTE 80 05 NOV AL, 000001018 Bit set word for PCO intr
110 0080 EE J1 L'X, AL
111 ;Wait for an interrupt from the printer
112 0081 EB FE UT: JNP UT
113 0083 90 FIN: NOP
114 0084 CCCE ENDS
115 END
(a)

FIGURE 9-16 (Continued) ( a) Mainline.

here we generate thç strobe directly under software is more than enough time for STROBE low. In this case.
control. ________ creating the STRODE signal with software does not use
in the mainline we make the STROBE signal on PC4 much of the processors time, so this is an efikient way
high by sending a bit seUrset control word of 00001001 to do it.
to the control register of the 8255A. In the printer driver
procedure a character is sent to the printer with the OUT
A FEW MORE POINTS ABOUT THE 8255A
DX,AL instruction. According to the timing diagram in
Figure 9-13. we then want to wait at least 0.5 t.s before Before leaving our discussion of the 8255A. we want to
asserting the STROBE signal low. This Is automatically show you a little more about how port C can be used.
done in the program because the instructions required Any bits of port C which are programmed as Inputs
to assert the strobe low take longer than 0.5 i.s. The can be read by simply doing a read from the port C
MOV AL,0000 I 000B instruction requires 4 clock cycles. add,ress. You can then mask out any unwanted bits of
and the OUT DX.AL instruction requires 8 clock cycles the word read In. If port A and/or port B is programmed
to execute. Assuming a 5-MHz clock l0.2-s period). 'in a handshake mode. -theti some of the bits of a byte
these two Instructions take 2.4 j,s to execute, which Is read in from port C represent status information about
more than required. the handshake signals. Figure 9-17. p. 260, shows the
Again_referring to the timing diagram In Figure 9-13. meaning of the bits read from port C for port A and/or
the STROBE time low must also be at least 0.5 u.s. The port B in mode I. Here's how you read this diagram. If
MOV AL,0000IOOW instruction takes 4 clock cycles. port B is initialized as a handshake (mode 1) input port,
and the OUT DX.AL Instruction takes 8 clock cycles. then bits DO. Dl, and D2 read from port C represent
With a 5-MHz clock, this totals to 2.5 p.s. which again the status of the port B handshake signals. Bit D2 will

258 CFIAPTER NINE


:8086 PROCEDURE F9-168.AS$ use with ..intin. F9-1U.ASII
2 ;ASSTRACT : Printer Driver procetàire outputs a character froa a buffer
3 to a printer. If no characters ar. Left in th. buffer the
4 the interrWt to the 8086 on lR6 of th 8259A is disabled.
5 ;PROCEDIJtES Non. used /
6 ;PTS : Use* SDK-86 board POrt P18 (FFFBH) to output characters
7 and port c bits for handshake signaL, and printer Intr
8 ;REGISTERS Destroys nothing
9
10 PUBLIC PRINT_IT
110000 DATA SEONENI PUBLIC
12 EXTRN CLXJNTER :BYTE, POINTER :tD
13 EXIRN MESSAGE 1:BYTE, PRINT_DONE:BYTE
14 0000 DATA ENDS
15
16 0000 C00E SEENT D PUBLIC
17 0000 PRINT_IT PROC FAR
18 ASS1JIE CS:C00E, DS:DATA
19 0000 cc PUSNF ; Save registers
20 0001 50 PUSH AX
21 0002 53 PUSH BX
22 0003 52 PUSH DX
23 0004 TB STI EnabLe higher interrt.ts
24 0005 BA FFFB NOV DX, OFFFBN Point at port B
25 0008 88 iT 0000e NOV BX, POINTER ; Load pointer to s.age
26 000C 8A 07 NOV AL, (BXI ; Get a character
27 000E EE DUT DX, AL ; Send th. character to printer
28 ;Send printer strobe on PC4 low then high
29 000F BA FFFF NOV DX, OFFFFH Point at port control addr
30 0012 80 08 NOV AL, 000010008 ; Strobe low control word
31 0014 EE DUT DX, AL
32 0015 80 09 NOV AL, 000010018 Strobe high control word
33 0017 EE DUT DX, AL
34 ;Increment pointer and decrement cotrter
35 0018 FT 06 0000e INC POINTER
36 001c FE OE 0000e DEC CDUNTER

37 0020 75 08 JNZ NEXT Wait for next character?
38 ;No are characters-disable 8255* mt request on PCO by bit reset of PC2
39 0022 80 04 NOV AL, 000001008 Bit reset word for PCO InterrLçt
40 0024 EE DUT DX, AL
41 0025 C6 06 0000e 01 NOV PRINT_DONE, 1
42 002A 80 20 NEXT: NOV AL, 001000008
OCW2 for non-specific E0l
43 002C BA FF00 NOV DX, OTFOOH Point at 8259A control addr
44 002F EE JT DX. AL
45 0030 5A POPDX Restore registers
46 0031 58 POP BX
47 0032 58 POP AX
48 0033 90 POP,
49 0034 CF IRET
50 0035 PRINT_IT ENDP
51 0035 C00E ENDS
52 END
(b)

FIGURE 9-16 (Continued) (b) Procedure.

be hIgh If the port H Interrupt request output has been over and over until you find this bit high. The IBF pin
enabled. Bit D2 is a copy of the level on the input buffer being high means that the input data byte has been
lull (IBF) pin. Bit D3 is a copy of the Interrupt request latched into the 8255A and can now be read. The timing
output, so It will be high it' port B is requesting an waveforms for this case are the same as those in Figure
interrupt. 9-10. except that you are not using the interrupt request
In our previous application examples. we showed how output from the 8255A.
to do handshake data transfer on an interrupt basis to Port C bits that are not used for handshake signals
make maximum use of the CPU time. However, in and programmed as outputs can be written to by
applications where the CPU has nothing else to do while sending bit set/reset control words to the control
waiting to. for example, read in the next character from register. Technically, bits PCO through PC3 can also
some device, then you can save one interrupt input by be written to directly at the port C address, but we
reading data from the 8255A on a polled basis. To do have found It safer to Just use the bit set/reset control
this for a handshake input operatin on port B, you word approach to write to all leftover port C bits
Simply lOOP through reading port C and checking bit Dl programmed as outputs.
-- S-
CGITAL INTERFACING 259
POST C 501 KEY SHEETWITH ROW
o! ________ / CONDuCTORS
107 I 0. 1 05 I I I1 _________
___________________________ / SHEETWITH HOLES
SHEET WITH COLUMN
GSOfrA OSOUPS ________________________ CONOUCTORS
STARS STARS
I4T I*UT
POST POST

KEY CAP
: ________ RETURN SPRING
OUTPUT OUTPUT
POST PLUNGER
FOAM PAD
MOVA8LE PLATE
FIXED PLATES
I c I'f "° I ImTI.I
'z'/VZ /ZZ//Z. . V/'/Z-'/ZZz ./'/ PC BOARD
FIGURE 9-17 8255A status word format for mode 1 (B)
input and output operations.

INTERFACING A MICROPROCESSOR KEY MOT,jjj1


TO KEYBOARDS HJ1

keyboard Types
REFE RE NC
When you press a key on your computer, you are CURRENT
activating a switch. There are many different ways MAGNETIC
of making these switches. Heres an overview of the FIELD
construction and operation of some of the most common
types. I Ti
FIGURE 9-18 Keyswitch types. (a) Membrane.
MECHANICAL KEYSWITCHES (b) Capacitive. (C) Hall effect.
In mechanical-switch keys, two pieces of metal are
pushed together when you press the key. The actual
switch elements are often made of a phosphor-bronze a key, you push the top ink line through the hole to
alloy with gold plating on the contact areas. The key- contact the bottom ink line. The advantage of membrane
switch usually contains a spring to return the key to the keyboards is that they can be made as very thin, sealed
nonpressed position and perhaps a small piece of foam to units. They are often t'sed on cash registers in fast.
help damp Out bouncing. Some mechanical keyswltches food restaurants: on medical instruments, and in other
now consist of a molded silicone dome with a small piece messy applications. The lifetime of membrane keyboards
of conductive rubber on the underside. When a kejr is varies over a wide range.
pressed, the rubber foam shorts two traces on the
printed-circuit board to produce the Key Pressed signal. CAPACITIVE KEYSWITCHES
Mechanical switches are relatively inexpensive but
they have several disadvantages. First, they suffer frc'm As shown in Figure 9-18b, a capacitive keyswitch has
Contact bounce. A pressed key may make and break two smafl metal plates on the printed-circuit board and
contact several times before it makes solid contact. another metal plate on the bottom of a piece of foam.
Second. the contacts may become oxidized or dirty with When you press the key, the movable plate is pushed
age so they no longer make a dependable . connection. closer to the fixed plate. This changes the capacitance
Higher-quality mechanical switches typically have a between the fixed plates. Sense amplifier circuitry de-
rated lifetime of about 1 million keystrokes. The silicone tects this change in capacitance and produces a logic-
dome type typically last 25 million keystrokes. level signal that indicates a key has been pressed. The
big advantage of a capacitive switch is that it has no
MEMBRANE XEYSWITCHES mechanical contacts to become oxidized or dirty. A small
disadvantage Is the specialized circuitry needed to detect
These switches are really just a special type of mechanical the change in capacitance. Capacitive keyswitches typi-
switch. They consist of a three-layer plastic or rubber cally have a rated lifetime of about 20 million keystrokes.
sandwich, as shown in Figure 9-ISa. The top layer has
a conductive line of silver ink running under each row
of keys. The middle layer has a hple under each key HALL EFFECT KEYSWITCHES
position. The bottom layer has a conductive line of silver This is another type of switch which has no mechanical
ink running under each column of keys. When you press contact. It takes advantage of the deflection of a moving
260 CHAPTER NINE
DETECT

}OE BOUNCE

(a)

FIGURE 9-19 Detecting a matrix keyboard keypress,


debouncing it. and encoding it with a microcomputer.
(a) Port connections. (b) Flowchart for procedure.

charge by a magnetic field. Figure 9- 18c shows you how


this works. A reference current is passed through a
semiconductor crystal between two opposing faces.
When a key is pressed. the crystal is moved through a
magnetic field which has its flux lines perpendicular to
the direction of the current flow in the crystal. (Actually,
It is easier to move a smal! magnet past the crystal.)
Moving the crystal through the magnetic field causes a ENCODE
small voltage to be developed between two of the other
opposing faces of the crystal. This voltage is amplified
and used to indicate that a key has been pressed. Flail
effect sensors are also used to detect motion in many
electrically controlled machines.) Hall effect keyboards
are more expensive because of the more complex switch
mechanisms, but they are very dependable and have
typical rated lifetimes of 100 million or more keystrokes.

Keyboard Circuit Connections and Interfacing


In most keyboards, the keyswitches are connected in a
matrix of rows and columns, as shown in Figure 9-I 9a. (b

DIGITAL INTERFACING 261


We will use simple mechanlcaJ switches for our examples The final task Is to determine the row and column of
here, but the principle Is the same for other types of thc pressed key and convert this row and column
switches. Getting meaningful data from a keyboard such information to the hex code for the pressed key. To get
as this requires the following three major tasks: the row and column information, a low is output to one
row and the columns are read, If jione of the columns
1. Detect a keypress. is low, the pressed key is not in that row, so the low is
2. Debounce the keypress. rotated to the next row and the columns are checked
again. The process is repeated until a ow on a row
3. Encode the keypress (produce a standard code for produces a low on one of the columns, The pressed key
the pressed key). then is in the row which is low at that time, With the
connections shown in Figure 9-i9a, the byte read in
The three tasks can be done with hardware, software, from the input port will contain a 4-bit code which
or a combination of the two. depending on the applica- represents the row of the pressed key and a 4-bit code
tion. We will first show you how they can be done with which represents the column of the pressed key. As we
software, as might be done in a microprocessor-based show later, a lookup table can be used to easily convert
grocery scaje whei'e the microprocessor Is not pressed this row-column code to the desired hex value.
for time. Later we describe some hardware devices which Figure 9-20 shows the assembly language program for
do these tasks. this procedure. The detect, debounce, and row-detect
parts of the program follow the flowchart "ely closely
and should be easy for you to follow. Work your way
Software Keyboard Interfacing
down through these parts until you reach the ENCODE
label: then continue with the discussion here.
CIRCUIT CONNECTIONS AND ALGORITHM
Figure 9-19a shows how a hexadecimal keypad can be
connected to a couple of microcomputer ports so the CODE CONVERSION
three interfacing tasks can be done as part of a program. There are two important ways of converting one code to
The rows of the matrix are connected to four output. another in a program. The ENCODE portion of this
port lines. The column lines of the matrix are Connected program uses a compare technique, which we will
to four Input-port lines. To make the program simpler, discuss in detail here, In a later section on keyboard
the row lines are also connected to four Input lines. interfacing with hardware, we will show you the other
When no keys are pressed, the column lines are held major code conversion technique, the XLAT method.
high by the pull-up resistors connected to + 5 V. Pressing After the row which produces a low on one of the
a key connects a row to a column, If a low is output on columns is found, executionjumps to the label ENCODE.
a row and a key In that row is pressed, then the low will
The IN AL.DX instruction here reads the row and column
appear on the column which contains that key and can codes from the Input port. Since this 8-bit code read in
be detected on the input port. If you know the row and
represents the pressed key. all that has o be done now
the column of the pressed key, you then know which is to convert this 8-bit code to the hex code for that key.
key was pressed, and you can Convert this information If we press the D key, for example, we want to exit from
Into any code you want to represent that key. Figure the procedure with ODH in AL.
9-19b shows a flowchart for a procedure to detect. The conversion is done with the lookup table declared
debounce, and produce the hex code for a pressed key. with DBs at the top of Figure 9-20. This table contains
This procedure is another example of an VO driver.
the 8-bit keypressed codes for each of the 16 keys. Note
An easy way to detect if any key in the matrix Is that the row-column codes are put in the table in the
pressed is to output 0's to all the rows and then check same order as the hex codes they represent. To convert
the columns to see If a pressed key has connected a low a row-column code read In from the port, we compare it
to a column. in the algorithm in Figure 9-19b. we first with each value in the table until we reach the value it
output lows to all the rows and check the columns over matches. For several reasons, we Start by comparing a
and over until the columns are all high. This is done to row-column code with the highest entry in the table. A
make sure a previous key has been released before counter is used to keep track of how far down the table
looking for the next one. In standard keyboard terminol- we have to go to find a match for a particular input code.
ogy, this is called two-key Lockout. Once the columns
Because the entries in the table are in numerical order.
are found to be all high, the program enters another the counter will contain the hex code for the pressed
loop, which waits until a low appears on one of the key when a match is found, Let's look at the actual
columns, Indicating that a key has been pressed. This program Instructions in Figure 9-20 to help you see how
second loop does the detect task for us. A simple 20-ms this works,
delay procedure then does the debounce task. The BX register is used as a counter and as a pointer
After the debounce time, another check Is made to see to one of the codes in the table, so to start we load 000FH
if the key is still pressed. If the columns are now all In BX. The CMP AL.TABLELBXJ after this compares the
high. then no key is pressed and the initial detection code at offset IBXI in the table with the row-column code
was caused by a noise pulse or a light brushing past a in AL. Initially. BX contains 000FH. so the row-column
key. If any of the columns are still low, then the assump. code in AL is compared with the row-column code at the
lion Is made that it was a valid keypress. highest location in the table. As shown In the data
262 CHAPTER NINE
;8086 PROGRAI4 F9-20.ASM
;ABSTRACT : Program scans and decodes a 16-switch keypad.
2 it initia&izes the ports beLow and then calls a procedure
3 to input an 8-hit vaLue from a 16-switch keypad and encode it.
4 : SDK-86 board Port MA (FFF9H) - output, P18 (FFFBH) - input
5 ;PORTS
;PROCEDURES: CalLs KEYBRD to scan and decode 16-switch keypad
6
7 ;REGISTERS : Uses CS,DS,SS,SP.AX,DX
8
9 0000 DATA SEGMENT WORD PU8LC
0 1 2 3 4 5 6 7
10 7714, 7814, 7014, 7tH, 08714,08844,080K, OBEII
11 0000 777870 7E 87 BB 80 * TABLE D8
¶2 BE B C 0 E F
8 9 A
13 06 00714.00844,00014, ODEN, 08714, OEBH, OEOH, QEEK
14 0008 070800 DE E7 ES ED *
15 8€
16 0010 DATA ENDS
17 0000 STACK_SEG SEGMENT
OW 30 DUP(0) Set stack of 30 words
18 0000 1E*(0000) ; Pointer to top of stack
Tap_STACK LABEL 0
19
20 003C - STACK_SEG ENDS
21
22 0000 COUE SEGMENT WORD PUBLIC
ASSIJIE CS:COUE, DS:DAIA, SS:STACK_SEG
23 Initialize stack
24 0000 68 0000s START: NOV AX, STACK_SEG
NOV SS, AX segment register and
25 0003 8€ 00 NOV SP, OFFSET TOP_STACK top of stack
26 0005 BC 003Cr
27 0008 88 0000s NOV AX, DATA
28 0008 8€D8 NOV DS,AX
;Initiatiie ports, mode 0, Port A for output, Ports B & C for input
29 Put port control address in DX
30 0000 BA FFFF NOV DX, OFFFFH
NOV AL, 100010118 ; Code 8811
31 0010 80 88 Send controL word.
32 0012 EE JT DX AL
33 0013 €8 0001 CALL KEYBRO
34 0016 90 PlOP
35 ;Progrmfl wiLL continue here with other tasks
36
37 ;8086 PROCEDURE KEYBRO
;ABSTRACT : Procedure gets a code from a 16-switch keypad and decodes it.
38 It returns the code for the keypress in AL and AHOO. if there
39 is an error in the kcypress then it returns AI401.
40 : Uses SDK-86 ports MA (FFF9H) for output and P18 (FFFBH) for input
41 ;PORTS
42 ;INPUTS : Keypress from port
;CIJTPUTS : KeypreSs code or error message in AX
43
44 ;PROCEDURES: None used
45 ;REGISTERS : Destroys AX
46
4? 0017 KEYBRD PROC NEAR
PUSHF Save registers used
-68 0017 9C
49 0018 53 PUSH BX
50 0019 51 PUSH CX
51 OUIA 52 PUSH DX
52 ;Send 0s to all rows
53 0018 80 00 NOV AL, 00
NOV DX, OFFF9H Load output address
54 0010 BA FFF9 Send 0's
55 0020 €8 QJT DX, At.
56 ;Read cotuiws to see i' a(L keys are open
NOV DX, OFFFBH Load input port address
57 0021 BA FFFB
58 0024 EC WAIT_OPEH:IN AL, DX
AND AL, OFH Mask row bits
59 0025 24 OF Wait until no keys pressed
60 0027 3C OF CMP AL, OFII
61 0025 75 F9 JNE WAIT OPEN
62 ;Read cotuwis to see if a key is pressed
WAIT_PRESS:IN AL, DX ; Read coturriS
63 O0 EC
24 OF AHO AL, OFH Mask row bits
64 00 Sc-c if keypresSed
65 OO2E 3C OF CMP AL, OFH
66 O03( 74 F9 JE WAIT_PRESS
67 ;Debounce keypresS
NOV CX, 16€A14 Delay of 20 ms
68 003 B9 16EA
69 003 E2 FE DELAY: LOUP DELAY
70 ;Read coLumns to see if key stilt pressed
71 003 EC Ill AL, DX

FIGURE 9-20 Assembly language instructions for keyboard detect, debounce,


and encode procedure. (Continued)

DIGITAL INTERFAC I NG 263


720038 24 OF AND AL. 0tH
73003A 3C OF NP AL 0tH
74 003C 71. ED JE WAIT_PRESS
75 ;Flnd the key
76 003E ID FE NOV AL, OFEN ; Initialize a row mask with bit 0
77 0060 8AC8 NOV CL, AL ; tow and save the mask
78 0042 BA FFF9 NEXT_RON: NOV DX, OFFF9H Send out a tow on one row
19 0045 EE au os, AL
800066 BA FFFB NOV DX, OFFF8H ; Read cotuws & check for tow
81 0049 EC IN AL, DX
82004* 24 OF AND AL, 0tH Mask out row code
83 004C 3C OF OW AL, 0tH ; If low In a cotuin then
84 004E 7506 JNE ENE ; key coli.jm, fou, so encode it
85 0050 DO Cl 101. CL. 01 else rotate mask
86 0052 8* Cl NOV AL,CL -
87 0054 ED EC JJW NEXT_RON and took it next row
88 ;Encode the row/col Infor.atlon
89 0056 88 000F ENCa)E: NOV IX, 000FH ; Set t 85 as a cou,ter and
90 0059 EC IN AL, DX ; read row and cottmm from port
91 005* 3A 87 ODOUr TRY_NEXT: CNP AL, TA3LE(BX3 ; Ccsre row/cot code With table entry
92 005E 74 08 JE DONE Hex code In 85
93 0060 48 DEC BX ; Point at next table entry
94 0061 79 Fl JNS TRY IEXT
95 0063 84 01 NOV AN, 01 ; Pass an error code in AN
96 0065 (8 05 90 JMP EXIT
97 0068 8* C3 DONE: NOV AL, 81. ; Hex code for key In AL
98 006* 84 DO NOV AN, 00 ; Put key-valid code in AH
99006C 5A EXIT: POP DX ; Restore calLing progru
100 0060 59 POP CX ; registers
101 006E 58 POP BX
102 006F 90 POPF
103 0070 C3 RET
104 0071 KEYBRO ENDP
105 0071 C00E ENDS
106 END

FIGURE 9-20 (Continued)

segment In FIgure 9-20. the row-column code at this ERROR TRAPPING


location in the table is the code for the F key. If the code
The concept of detecting some error condition such as
In AL matches this code, we knowthe F key was pressed.
"no match found" is called error trapping. Error trapping
BX contains 000FH. the hex code for this key. Since we
is a veiy important part of real programs. Even in this
need only the lower 8 bits of BX, the hex code in BL Is
simple program, think what might happen with no error
copied to AL to past' it back to the calling program. AH
trap if two keys in the same row were pressed at exactly
is loaded with OOH to tell the calling program that this
the same time and a column code with two lows in It
was a valid keypress. and a return is made to the calling
was produced. This code would not match any of the
program.
row-column codes in the table, so after all the values in
If the row-column code in AL doesn't match the table
the table were checked, BX would be decremented from
value on the first compare, we decrement BX to point to
0000H to FFFFH. On the next compare. AL would be
the code for the E key in the table and do another
compared with a value in memory at offset FFFFH. Since
compare. Ifa match occurs this time, then we know
this location is not even in the tabk'. the compare-
that the E key was the key pressed and that the hex
decrement cycle would continue -through 65.536 mem-
code for that key. OEH. is In BE.. If we don't get a match
ory locations until, by chance, the value in a memory
on this compare, we cycle through the loop until we get
location matched the row-column code in AL. The con-
a match or until the row-column code for the pressed
tents of BL at that point would be passed back to the
key has been compared with all the values in the table.
calling routine. The chances are I in 256 that this would
As long as the value in BX is 0 or above after the DEC
be the correct value for one of the two pressed keys.
BX instruction, the Jump if Not Sign instruction, JNS
Since these are nct very good odds, you should put an
TRY_NEXT, will cause execution to go back to the
error trap in a program wherever there is a chance for
Compare Instruction. If no match Is found in the table.
it to go off to "never-never land" in thIs way. An error/
BX will decrement from 0 to FFFFH. Since the sign bit
no-error "flag" can be passed back to the calling program
is a copy of the MSB of the result after the DEC
in a register as shown, in a dedicated memory location,
Instruction, the sign bit will then be set. Execution will
or on the stack.
fall through loan instruction which loads an error code
of 0tH In AH. We then return to the calling program.
Tb.. calling program will check All on return to determine Keyboard Interfacing with Hardware
if the contents of AL represent the code for a valid The previous Section descrIbed how you can connect a
keypress. keyboard matrix to a couple of microprocessor ports

264 CHAPTER NINE


and perform the three interfacing tasks with program microcomputer doesn't have to pay any attention to the
Instructions. For systems where the C pu is too busy to keyboard until It receives an Interrupt signal, so this
be bothered doing these tasks In software, an external method uses vel'y little of the microcomputer's time.
device is used to do them. One example of a MOS device The AYS-2376 has a feature called two-key rollover.
which can do this is the General Instrument AYS-2376. This means that ii two keys are pressed at nearly the
whicn can be connected to the rows and columns of a same time, each key will be detected. debounced. and
keyboard switch matrix, The AY5-2376 Independently converted to ASCII. The ASCII code for the first key and
detects a keypress by cycling a low down through the a strobe signal for it will be sent out; then the ASCII
rows and checking the columns just as we did in code for the second key and a strobe signal for it will be
software. When it finds a key pressed, it waits a debounce Sent out. Compare this with two-key lockout, which we
time. If the key is still pressed after the debounce time, described previously in our discussion of the software
the AY5-2376 produces the 8-bit code for the pressed method of keyboard interfacing.
key and sends it out to, for example, a microcomputer
port on eight parallel lines. To let the microcomputer ICATE M CROPROCESSOR
know that a valid ASCII code i on the data lines, he B ARD EN ODERS
AY5-2376 outputs a strobe pulse. The microcomputer Most computers and computer terminals now use de-
can detect this strobe pulse and read in the ASCII code tached keyboards with built-in encoders. Instead of
on a polled basis, as we showed in Figure 4-20. or it can using a hardware encoder device such as the AYS-2376.
detect the strobe pulse on an interrupt basis, as we these keyboards use a dedicated microprocessor. Figure
showed In Figure 8-9. With the interrupt method the 9-21 shows the encoder circuitry for the IBM PC capaci-

+5 VOC ___________________________________________
COl(A011( -

56F1 Lr cc1
P23 'GNO
.SACLOSEO 1C3
n
ciJ 26 VDD P22
SELECT 0 67 'AO -r •'-
56pF T' SELECT I 691
P21 22 CON
40 P20 21
vCC 1c2
J7
87 19 -r 50 pF
2 Xl

LI 27 M000
475H
28 MOOl SENSE B , A9
3 P12 29 M002 SENSE C Al
C5 52
20.1 pP

C4 P15 32 MOOS KEYBOARD SENSE P *1


20,7 pP I CAPACITIVE I
MDO6 MATRIX SENSE 6 C3
P16
MOO? SENSE H El
CO I IA) EA P17
35 MDO8
I 20
VSS P25
_____
MDI0
SENSE I
AMPLIFIER I
P28
P27 38 MOlt
• ZI I
8040
+5 VOC MICROPROCESSOR 83
2 kfl
5 ______________ •SBRIAI
85 17 DAIAOIJT _______________ DATA CDI IAO7I
R6 :
AS
10 kfl
ikil. fI;.;;:;-1..:...-J1
6 OATAIN M2
__________
-P08 4
.
R2 -
-REOLIE.
18 -REOOUT ____________ CLOCK
Ii 86 )CDIIAO9I
ALE
a
tLce
22 pP
I kIl

FIGURE 9-21 IBM PC keyboard scan circuitry using a dedicated


microprocessor. (IBM Coiporation)
DIGITAL INTERFACING 265
tive-awitch matrix keyboard. The 8048 microprocessor TABLE CONTAINING
ASCII CODES
used here contains an 8-bit CPU. a ROM, some RAM.
three ports, and a programmable timer/counter. A pro-
gram stored in the on-chip ROM performs the three
ke4oard tasks and sends the code for a pressed key out
to the computer. To cut down the number of connecting
wires, the key code is sent out in serial form rather than -ASCII A
in parallel form. Some keyboards send data to the
computer in serial form using a beam of infrared light
instead of a wire.
Note in Figure 9-21 that a sense amplifier is used to
detect the change in capacitance produced when a key
OFFSET CiA
Is pressed. Also note that the 8048 uses a tuned LC
Circuit rather than a more expensive crystal to determine
its operating clock frequency.
One of the major advantages of using a dedicated
microprocessor to do the three keyboard tasks is pro-
START OF TABLE. OX
grammability. Special-function keys on the keyboard
can be programmed to send out any code desired for a
particular application. By simply plugging in an 8048 FIGURE 9-22 Memory table setup for using XLAT to
with a different iookup table In ROM, the keyboard convert EBCDIC keycode to ASCII equivalent.
can be changed from outpuuing ASCII characters to
outputting some other character set.
The IBM keyboard, incidentally, does not send out memory table which contains all the ASCII codes. The
ASCII codes, but instead sends out a hex "scarf' code trick here is to put each ASCII code in the table at a
for each key when it Is pressed rind a different scan code dlsp!acement from the start of the table equal to the
when that key is released. This double-code approach value of the EBCDIC character. Forexample, the EBCDIC
gives the system software maximum flexibility because code for uppercase A is CIH. so you put the ASCII code
a program command can be implemented either when for uppercase A. 41H. at offset CIH in the table, as
a key is pressed or when It is released. shown in Figure 9-22. Since EBCDIC code Is an 8-bit
code, the table will require 256 memory locations. For
CONVERTING ONE KEYBOARD CODE EBCDIC values which have no ASCII equivalent, you
TO ANOTHER USING XLAT can just put in OOH because these locations wtlI not be
Suppose that you are building up a simple microcom- accessed. You can use the DB assembler directive to set
puter to control the heating, watering, lighting, and up the tahle, as we did with the row-column table In
ventilation of your greenhouse. As part of the hardware, Figure 9-20.
you buy a high-quality, fully encoded keyboard at the To do the actual conversion, you simply load the BX
local electronics surplus Store for a few dollars. When register with the offset of the start of the table, load the
you get the keyboard home, you find that it works EBCDIC character to be converted In the AL register.
perfectly, but that it outputs EBCDIC codes instead of and do the XLAT instruction. When the 8086 executes
the ASCII codes that you waflt. Here's how you use the the XLAT instruction, it internally adds the EBCDIC
8086 XLAT instruction to easily solve this problem. value in AL to the starting offset of the table in BX.
First, look at Table 1-2. which shows the ASCII and Because of the way the table is made up. the result of
EBCDIC codes. The job you have to do here s to convert this addition will be a pointer to the desired ASCII value
each input EBCDIC input code to the corresponding in the table. The 8086 then automatically uses this
ASCII code. One way to do this is the compare technique pointer to copy the desired ASCII character from the
described previously for the hex . keyboard example. 11or table to AL. Later in the chapter we show you another
that method you would first put the EBCDIC codes ill a example of the use of the XLAT instruction.
table in memory in the order shown In Table 1-2 and The advantage of the XLAT technique for this conver-
set up a register as a counter and pointer to the end of sion is that, no matter where in the table the desired
the table. Then you enter a loop which compares the ASCII value is. the conversion only requtres execution
EBCDIC character in AL with each of the EBCDIC codes of two loads and one XLAT instruction. The question
in the table until a match is found. The counter would may occur to you at this point, If this method is so fast.
be decremented after each compare so that when a why didn't we use it for the hex-keypad conversion
match was found, the count register would contain the described earlier? The answer is that since the row-
desired ASCII code. column code from the hex keypad is an 8-bit code, the
This compare technique works well, but since EBCDIC lookup table for the XLAT method would require 256
contains 256 codes, the program will, on the average. memory locations. but only 16 of these would actually
have to do 128 compares before a match Is found. The be used. This would be a waste of memory, so the
compare technique then is often too time-consuming compare method is a better choice. Since code conver-
for long tables. The XLAT method is much laster. sion is a commonly encountered problem in low-level
The first step in the XLAT method Is to make up a programming, it is important for you to become

266 CHAPTER NINE


familiar with both the compare and the XLAT methods
so that you can use the one which best fits a particular
applicaUon.
00000
00000
00000
INTLRFAC!NG TO DO ODU
ALPHANUMERIC DISPLAYS 00000
00000
To give directions or data values to users, many micro- 00000
processor-controlled instruments and machines need to
display letters of the alphabet and numbers. In systems
where a large amount of data needs to be displayed, a
CRT is usually used to display the data, so in Chapter
13 we show you how to interface a microcomputer to a [a' ibi
CRT. in systems where only a small amount of data
needs to be displayed, simple digit-type displays are COLUMN OP. 1 2 3 4
often used. There are several technologies used to make
these digit-oriented displays, but we have space here to
discuss only the two major types. These are light-
emitting diodes ( LEDs) and liquid-crystal displays ROy
(LCDsI. LCD displays use very low power, so they are
often used in portable. battety-powered Instruments.
LCDs, however, do not emit their own light; they simply
change the reflection of available light. Therefore, for an 2
instrument that is to be used in low-light conditions,
you have to include a light source for the LCDs or use 3
LEDs, which emit their own light. Starting with LEDs,
the following sections show you how to interface these
two types of displays to microcomputers.

Interfacing LED Displays to Microcomputers


Alphanumeric LED displays are available in three com-
mon formats. i"or displaying only numbers and hexadeci - 6
mal letters, simple 7-segment displays such as that
shown in Figure J-4a arc used.
To display numbers and the entire alphabet. 18-
segment displays such as that shown in Figure 9-23a TOP VIEW ORIENTATiON
TIL 305
or 5 by 7 dot-matrIx displays such as that shown In
Figure 9-23b can be used. Th 7-segment type is the
least expensive, most commonly 'sed. and easiest to
interface with so we will concentrate first on how FIGURE 9-23 Eighteen-segment and 5 by 7 matrix LED
to interface with this type. Later we will show the displays. (a) 18-segment display. (b) 5 by 7 dot-matrix
modifications needed to interface with the other types. display format. (C) 5 by 7 dot-matrix circuit connections.

DIRECTLY DRIVING LED DISPLAYS 1.5 V. The output low voltage for the 7447 isa maximum
Figure 9-24. p. 268. shows a circuit that you might of 0.4 Vat 40 mA, so assume that it Is about 0.2 Vat
connect to a pataliel port on a mkroeornputcr to drive 20 mA. Subtracting these two voltage drops from the
a single 7-segment, common-anode display. For a com- supply voltage of 5 V leaves 33 V across the current-
mon-anode display, a segment Is turned on by applytng limiting resistor. Dividing 3.3 V by 20 mA gives a value
a logic low to it. The 7447 converts a 13C1.) code applid of 168 fI for the current-limiting resistor. The voltage
io its Inputs to the pattern of lows required to dtspla drops across the LED and the output of the 7447 are
the number represented by the I3CD code. This Circuit not exactly predictable, and the exact current through
connection is referred to as a static display because the LED Is not critical as long as we don't exceed Its
current is being passed through the displa y ai all times. maximum rating. Therefore, a standard value of 150 fl
Here's how you calculate the value of the current-limiting is reasonable.
resistors that have to be connected in series with eact'
segment. SOFTWARE-MULTIPLEXED LED DISPLAYS
Each segment requires a current olhetwcen 5 and 30 The Circuit in Figure 9-24 works well for driving just
mA to light. Let's assume you want a current of 20 mA, one or two LED digits with a parallel output port
The voltage drop across the LED when It Is lit is about However, this scheme has several problems if you want

-36 DIGITAL INTERFACING 267


+5 V all highs to port A. The BCD code for dIgit 2 isih,'rc
MAN?
output to the 7447 on port B, and a word to turn on
digit 2 is output on port A. After I or 2 nis. digI! 2 is
turned off and the process is repeated for digit '3. rh
I-I procesS is continued until all tli ligits have had a turn.
Then digit I and the lollowirig digits are lit agaIn In
I-I turn. We leave It to you as an exercise at the end of the
chapter to write a procedure which is railed on an
interrupt basis every 2 ms to keep these displava rr-
150(2EACH freshed wi:fj some values stored in a table.
WIth 8 digits and 2 ms per digit, you get hack to digit
13 12 Ii 10 9 15 14 1 every 16 ins, or about 60 times a second. This relrech
5V
= a b C 0 e rate is fast enough that, to your eye, the digits will eah
appear to be lit all the time. Refresh rates of 40 to 20u
+5
times a second are acceptable.
The immediately obvious advantages of multiplexing
the displays are that only one 7447 is required, and only
A B C one digit is lii at a time. We usually increase the current
per segment to between 40 and 60 mA for multiplexed
displays so that they will appear as bright as they would
aco iNpuTs if they were not multiplexed. Even with this increased
FIGURE 9-24 Circuit for driving single 7-segment LED segment current, multiplexing gives a large saving in
display with 7447. power and parts.

NOTE: If you are calculating the current-limiting


to drive, for example, eight digits. The first problem is resistors for multiplexed displays with increased
power consumption. For worst-case calculations, as- segment current, check the data sheet for the
sume that all 8 digits are displaying the digit 8. so all 7 displays you are using to make sure you are not
segments are lit. Seven segments times 20 mA er exceeding their maximum current rating.
segment gives a current of 140 mA per digit. Multiplying
this by 8 digits gives a total current of 1120 mA, or 1.12 The software . multiplexed approach we have jusE de-
A. for the 8 digits! A second problem o "" static scrio "art also be used to drive 18-segment LED devices
approach is that each display digit requires a separate and dot-matrix LED devices. For these devices, however,
7447 decoder, each of which uses, perhaps. another 13 you rep!ace the 7447 in Figure 925 with a ROM which
mA. The current required by the decoders and the LED generates the required segment codes when the ASCII
displays might be several times the current required by code for a character is applied to the addiess inputs of
the rest ofthe circuitry in the instrument. the ROM.
To solve the problems of the static display approach,
we use a multiplex method. A circuit example is the
easiest way to explain to you how this multiplexing
Display and Keyboard Interfacing with the 8279
works. Figure 9-25 shows a circuit you can add to a A disadvantage of the software-multiplexing approach
couple of microcomputer ports to drive some common- shown here Is that it pu ! s an additional burden on the
anode LED displays in a multiplexed manner. Note that CPU. Also, if the CPtJ gets involved in doing SOme lengthy
the circuit has Only One 7447 and that the segment task which cannot be Interrupted to t-efresh the display.
outputs of the 7447 are bused in parallel to the segment only one digit of tb.. display will be left lit. An alternative
inputs of all the digits. The question that may occur to approach t. nterfacimig multiplexed displays to a micro-
you on first seeing this is: Aren't all the digits going to computer is to use a dedicated display controller such
display the same number? The answer is that they as the Intel 8279. As we show you in the nexi Section.
would if all the digits were turned on at the same time. an 8279 independently keeps a bank of 7-segment
The trick of multiplexing displays is that only one display displays refreshed and performs the three tasks for a
digit is turned on at a time. The PNP transistor in Series matrix keyboard at the same time.
with the common anode of each digit acts as an on/off
switch for that digit. Here's how the multiplexing process
works. 8279 CIRCUIT CONNECTIONS AND
The BCD code for digit I is first output from port B OPERATION OVERVIEW
to the 7447. The 7447 outputs the corresponding 7- Sheets 7 and 8 of the SDK-86 schematics in Figure 7-
segment code o'the segment bus lines. The transistor show the circuit connections for the keypad and the
connected to digit I is then turned on by outptttimg a multiplexed 7-segment displays. First lets look at Ihe
low to the appropriate bit of port A. (Remember, a low display circuitry on sheet 8. The displays there are
turns on a PNP transistor.) All the rest of the bits of port common-anode, and each digit has a PNP transistor
A are made high to make sure no other digits are turned switrh between its anode and the -5-V supply. A logic
on. After1 or 2 ms. digit 1 is turned off by outputting low is iqu red to tutu on one of these switches. Note

268 CHAPTER NINE


R2 R3 R7.' +5V
OUTPUT
PORT
A
0O R4 l!r_:r AS t..r' 07
Di

02

03 NC-

04 iNC!!

05 c il_2
(6
D6 OP --
(DECIMAL
POINT) MSD LW
NC
1500 1500 1500 15Ofl 1S0 0 1500

OUTPUT
PORT
B 1(12( (ii) (10) 1(9) 1(15) i"
+5 V +5 V
DO vcc LI
1447 RBO
Di
GND RB1
02 COMMON ANODE
DISPLAYS - DL 707
03 Ri-i 1 kO
01-7 2N3906

FIGURE 9-25 Circuit for multiplexing 7-segment displays with a


microcomputer.

the 22-pI capacitor between +5 V and ground at the Note that the 22-fl current-limiting resistors In series
top of the schematic. This is necessary to fIlter Out with the segment lines are much smaller in value than
tra'islents caused by switching the large currents to the those we calculated for the static circuit in Figure
LEDs off and on. 9-24. There arc two reasons for this. First, there is an
The segments of each digit are all connected on a additional few tenths of a volt drop across the transistor
common bus. Since these are common-anode displays, switch on each anode. Second. when multiplexing dis-
a low is needed to turn on a segment. Now let's look at plays. we pass a higher current through the displays so
sheet 7 in Figure 7-8 to see how these displays are that they appear as bright as they would if they were not
driven. multiplexed. Here's how the 8279 keeps these displays
The drive for the digit-switch transistors comes from refreshed.
a 7445 BCD-to-declmal decoder. This device is also The 8279 contains a 16-byte display refresh RAM.
known as a one-of-ten-l')w decoder. When a 4-bit BCD When you want to display some letters or numbers on
code is applied to the inputs of this device, the output the LEDs. you write the 7-segment codes for the letters
corresponding to that BCD number will go low. For or numbers that you want displayed to the appropriate
example, when the 8279 outputs 0100 or BCD 4, the location in this display RAM. The 8279 then automati-
7445 output labeled 04 will go low, In the mode used cally cycles through sending out one of the segment
for this circuit, the 8279 outputs a continuous count codes, turning on the digit for a short time and then
sequence from 0000 to liii over and over. This causes moving on to the next digit. The top five lines in Figure
a low to be stepped from output to output of the 7445 9-26, p. 270. show this multiplex operation in timing
in ring ccunter fashion, turning on each LED digit in dtagram form.
turn. Only one output of the 7445 will ever be low at a The 8279 first outputs the binary number for the first
time, so only one LED digit will be turned on at a time. digit to the 7445 on the SLO to SL3 lines (Figure 7-8.
The segment bus lines for the displays are connected sheet 7) to turn on the first of the digit-driver transistors.
to the A3--AO and B3—B0 outputs of the 8279 through The lines SLO and SLI in Figure 9-26 represent the SLO
some high-current inverting buffers In the ULN2003A. and SL1 lines from the 8279. During this time. the 8279

DIGITAL iNTERFACING 26
PRESCALER PROGRAMMED FOR IN-
TERNAI. FREQUENCY 100 EH SO

510

511

*0 - *3
ACTIVE HIGH

80-83
ACTIVE HIGH

RIO- Rh

NQTE SHOWN IS ENCODED SCAN LEFT ENTRY


S2-S3 ARE NOT SHOWN BUT THEY ARE SIMPLY SI DIVIDED BY 2 AND 4

FIGURE 9-26 8279 display refresh timing and keyboard scan timing. (Intel
Corporation)

outputs on the A3—A0 and 3—BO segment lines a code the microprocessor. As we will show you later, the 8279
which turns off all the segments. For the circuit in can be connected and initialized to refresh a wide variety
Figure 7-8. sheet 7, this blanking code will be all zeros of display configurations.
(OOH). The display is blanked here to prevent "ghosting" The 8279 can also automatically perform the three
of information from one digit to the next when the digit tasks for interfacing to a matrix keyboard. Remember
strobe is switched from one digit to the next. from previous discussions that the three tasks involve
After about 70 ps. the 8279 outputs the 7-segment putting a low on a row of the keyboard matrix and
code for the first digit on the A3—A0 and 83—BO lines. checking the columns of the matrix, if any keys are
This will light the first digit with the desired pattern. pressed in that row, a low will be present on the column
After 490 ps. the 8279 outputs the blanking code again. which contains the key because pressing a key shorts a
While the displays are blanked, the 8279 sends out the row to a column. If no low- is found on the columns, the
BCD code for the next digit to the 7445 to enable the low is stepped to the next row and the columns checked
driver transistor for digit 2. it then sends out the 7- again. If a low is found on a column, then, after a
segment code for digit 2 on the A3—A0 and B3—B0 lines, debounce time, the column is checked again. If the
This lights the desired pattern on digit 2. After 490 ps, keypress was valid, a compact code representing the key
the 8279 blanks the display again and goes on to digit is constructed. Take a look at the circuit on sheet 7 of
3. The 8279 steps through all the digits and then returns Figure 7-8 to see how an 8279 can be connected to do
to digit I and repeats the cycle. Since each digit requires this.
about 640 ps, the. 8279 gets back to digit I after about When connected as shown in Figure 7-8. sheet 7. the
5.1 ms for an 8-digit display and back to digit 1 after 74LS156 functions as a one-of-eight-low decoder. In
about 10.3 ms for a 16-digit display. The time it takes other words. If you apply OIl. the binary code for 3. to
to get back to a digit again is referred to as the scan its inputs, the 74LS156 will output a low on its 2Y3
time. output. Now remember from the discussion of 8279
The point here Is that once you load the 7-segment display refreshing that the 8279 is outputting a continu-
codes into the internal display RAM, the 8279 automati- ous counting sequence from 0000 to 1111 on its SL0-
cally keeps the displays refreshed withnllt any help from SL3 lines. Applying this count sequence to the Inputs

270 CHAPTER NINE


of the 74L8156 will cause it to step a low along its schematics I n Figure 7-8. Figure 7-16b shows that the
outputs. The 74LS156 then puts a low on one row of system base address for this device is FFE8H. The 8279
the keyboard at a time, as desired. has only two internal addresses, which are selected by
The column lines of the keyboard are connected to the the logic level on its A0 input, pin 21. If the A0 input is
return lines, RLO—RL7. of the 8279. As a low is put on low when the 8279 is selected, then the 8279 Is enabled
each row by the scan-line counter and the 74LS 156, the for reading data from it or writing data to It. A0 beIng
8279 checks these return lines one at a time to see If high selects the internal control/status registers. For the
any of them are low. The bottom line of the timing circuit on sheet 7 of Figure 7-8. the A0 Input is connected
waveforms In Figure 9-26 shows when the return lines to system address line Al. Therefore, the data address
arc checked. If the 8279 finds any of the return lines for this 8279 Is FFE8H and the control/status address
low, indicating a keypress. it waits a debounce time of Is FFEAH.
about 10.3 ms and checks again. If the keypress is After you have figured out the system addresses for a
still present, the 8279 produces an 8-bit code which device, the next step Is to look at the format for the
represents the pressed key. Figure 9-27 shows the format control word(s) you have to send to the device to make
for the code produced. Three bits of this code represent it operate in the mode you want. Figure 9-28. p. 272,
the number of the row in which the 8279 found the shows the format for the 8279 control words as they
pressed key, and another 3 bits represent the column appear In the Intel data book. After you use up your 5-
of the pressed key. For interlacing to full typewriter minute "freak-out" time, we will help you decipher these.
keyboards the shift and control keys are connected to One question that may occur to you when you see all
pins 36 and 37, respectively, of the 8279. The upper 2 these control words is, If the 8279 only has one control
bits of the code produced represent the status of these register address, how am I going to send it all these
two keys. different control words? The answer to this is that all
After the 8279 produces the 8-bit code for the pressed the control words are sent to the same control register
key, It stores the byte in an internal 8-byte FIFO RAM. address, FFEAH for this example. The upper 3 bits of
The term FIFO stands for first in, first out, whicb means each control word tell the 8279 which control word is
that when you start reading codes from the FIFO, the being sent. A pattern of 010 in the upper 3 bits of a
first code you read out will be that for the first key control word, for example, Identifies that control word
pressed. The FIFO can store the codes for up to eight as a Rad FIFO/Sensor RAM control word. Keep Figure
pressed keys before overflowing. 9-28 Fandy as we discuss this and the pther control
When the 8279 finds a valid keypress. it does two words.
things to let you know about it. It asserts its interrupt The first control word you send to initIalize the 8279
request pin. IRQ, high. and it Increments a FIFO count is the keyboardidlsplay mode set word. The bits labeled
In an internal status register. You can connect the IRQ DD in the control word specify first of all whether you
output to an Interrupt input and detect when the FIFO have 8 digit or 16 digits to refresh. If you have eight or
has a character for you on an interrupt basis, or you fewer displays, make sure to initialize for 8 diglt3 so the
can simply check the Count in the status word to 8279 doesn't spend half its time refreshiug nonexistent
determine when the FIFO has a code ready to be read. displays. The DD bits In this control word also specify
The point here is that once the 8279 is Initialized, you the order in which the characters in the internal 16-
don't need to pay any attention to it until you want to byte display RAM will be sent out to the digits. In the
send some new characters to be displayed, or until It left entry mode, the 7-segment code In the first address
notifies you that it has a valid keypressed code for you of the internal display RAM will be sent to the leftmost
in its FIFO. Now that you have an overview of how the digit of the display. if you want to display the letters
8279 functions, we will show you how to Initialize an AbCd on the 4 leftmost digits of an &digit display. then
8279 to do all of these wondrous things arid more. you put the 7-segment codes for these letters in the first
four locations of the display RAM. as shown in Figure
INITIALIZING AND COMMUNICATING 9-29a. p. 273. Codes put in higher addresses in the
WITH AN 8279 display RAM will be displayed on following digits to the
As we have shown before, the first step in initializing a right. In the right entry mode, the first code sent to the
programmable device is to determine the system base display RAM is put in the lowest address. This character
address for the device, the internal addresses, and the will be displayed or- the rightmost digit of the display.
system addresses for the internal parts. As an example If a second character is written to the display RAM. It
here, we will use the 8279 on sheet 7 of the SDK-36 will be put In the second location In the RAM. as shown
in Figure 9-29b. On the display, however, the new
character will be displayed on the rightmost digit, and
the previous character will be shifted over to the second
MSB LSB
I I I position from the right. This is the way the displays of
I
I CNTL SHIFT SCAN RETURN most calculators function as you enter numbers.
L I I I
SCANNED KE V BOARD DATA F ORMA r
Now let's look at the KKK bits of the mode-set control
word. The first choice you have to make here ii you are
FIGURE 9-27 Formal for data word produced by 8279 using the 8279 with a keyboard is whether you want
keyboard encoding encoded scan or decoded scan. You know that for

DIGITAL INTERFACING 271


K.yboardlDtsplay Mod. S•t Widi. DIsplay RAM


MSd LS8 Code At A A AJ
LJ_!_1_o
Code LoioIoID!0IK IKIKI i'h CPU twI, up the 8279 for a wrIte to tile DispISy RAM
by first writing this command. After writIng fl'ie corn
Wner, OP sine Display Mode and KKK she KeyflOard mind wrlh A0 = tall subsequent write, with A 0 'ri 0 will
Mode ha to the Display RAM. The addressing md Auto-
Increment lunclions are identical to those tor the Reac,l
DD Dniplay RAM Howov.,, tIlts Command does not affect
0 I) 8 8 bil character display - Lell entry thSoorce o l subsequent Data Reads: the CPU wilt read
o I 16 8. t'l charade' Orsplay -- tell entry' front whichever RAM (Display or FIFOlSonsort Which
wa. last specified. If, indeed, the Display PAM was last
t 0 88-bit cha,acle display - Right entry specified, the Write Display RAM will, nevertheless,
1 1 158-bit eflaradler display - Righi entry change the next Read location.
For description 01 right and lell entry. see- Interface Dlipl.y Writ. lnNbffllanklng
Considerations Note that wfleri decoded scan is SO! 0
keyboard mode the display is red-iced to 4 Characters A S A S
independent ot display mode set. Cod.: 11I0I1I*l1wliwSL!iii
KKK
o 0 0 Encoded Scan Keyboali - 2 Key lockonat The IW Bits can be used to masts nibble A and nibble B
in applications requiring separate 4-bit display port,, By
0 ci I Decoded Scan Keyboard - 2-Key Lockout setling the 1W ttag (1W = 1) for one of the ports, the port
o 1 0 Encoded Scan Keyboard - N-Key Rollover becomes marked so that entries to the Display RAM
o 1 1 Decoded Scan Keyboard --' N-idea Roliciser Iron, fIle CPU do not affect lOaf port. Thus, if each nibble
is input to a BCD decoder, the CPU may writes digit to
1 0 0 Encoded Scan Sensor M&ln,v the Display RAM without affecting the other dIgit being
1 0 I Decoded Scan Sensor MaIns displayed. It is inoportarrt to note that bit B 0 corresponds
to bit D0 on the CPU bus, and that bit A5 corresponds to
1 1 0 Strobed Input. Encoded Display Scar, bit 0.
1 I Slrobed Input, Decoded Display Scan -
If life user wishes to bianli the display, the BL flags are
Progeim Clock available for each nibble, The last Ctoar command Issued
deternxines the code to be Used 55 a "blank.' This code
Code: IoIoIilPIPIPIPI defaults to all reros after a reset. Note that both BL
Ilags 11115sf be set to bl5nk a display formatted with a
All tlrtring and multiplexing 5ignais to, the 8279 are single 8-btt port
generated by an internal pnosc.aler. This prescater
divide, the eetemnsl clock (pin 3) by a prograrorssable Cf..'
integer. Bits PPPPP determine the vilue of this Integer
which range. from 2 to 31. Choosing a dl',Isor that yields Cods
100 kH, will give tile spocltied scan anti deboiance
tirrtos. For instance, if Pin iof the 8279 5 being clocked The C11 bits are available in this command to Clear alt
by a 2 MHa signal. PPPPP should be set to 10100 to rows of the Display RAM to a selectable blanking code
divide file clock by 20 to yield the proper tOO kl-4z operat- as follows:
ing ireqlieflCy. C0 C.,, C0
Read FlFOlSnsor RAM 0 X All Zrvs )X Don! Care) -
1 0 Ail U.s 20 iQt 00001
Code: I0HIOIAI!XIAIAIAI XnDOtn'tCire
1 1 All Ones
The CPU sets tap the 8279 tori read of the FIFO/Sensor
RAM by fIrst writing this command. in the Scan Key- - Enabl, clear d.vplay when 1 lot b y Ce 11
board Mode, the Auto-lrtCrerllont flag (Al) and the RAM During hhe time lhe Dioploy RAM is teing cleared 1 -' 160 as),
address bits (AAA) are irrelevant, the 8279 wit) anatornatt. it may vol be enliton to. The 1110sf significant tilt of the
Catty drive the data ills tor each Subsequent read (A0= 0) FIFO status word is svt during Ihis 1:1110 When the Dis-
in the same sequence in which the data first entered the play RAM beco'r:ei avale.,bin aain. if automnalicalty
FIFO. All subsequent reads will be from the FIFO until resets,
anot her command is issued.
It the C bit is as,,u:'r':,' I. , , ' . ' ' i'S" ' . i,s',us iii
In the Sensor MaIns Mode, the RAM address bits AAA cleared and the I tøIi'liii OS'] . ir,r.Air.0
setect one of the 8 rows of the Sensor RAM lithe Al flag Sensor RAM pointer is set fo':'.'r
is set (At = 1), each Successive read will be from the Sub-
Sequent 0W of the sensor RAM. C. lbs Clear All bit, rids Ifto combed shed ,, C,, iiC
Cy: fuses the C 0 clearing coda a'- rho Ospla, 10CM
R..d Display RAM also clears FIFO status Furlh, r,n'orc. 1 'esynr.hrc,n:,es
the internal t:ming chain.
Code: I0I3I1uI*kHHI Cnd int.rrupUErrof Mode Sit
The CPU sets vip the 8279 for a read at the Display RAM
by tirst writing thiS command. The addreSs bIts AAAA
select one of the 18 roes of the Display RAM lithe At
Code F1T ; x Ii x '1 . LiOn I cab
flag is set (At = 1). this row address CIII be incremented
after each following read a, write to the Display PAM, For tile Sensor matrix modes It,iS co-n-and to, i's lne
Since the same Counter is used for both reading and tRO line Sod enables 'drI ller wr,l:r,q 'nb 'AM "I neRO
writing. thrn command sets the next read rn wilts line would nave been raised upon Ire detectrirn 01 5
address and the sense o f the Auto-Increment mode for change in a sensor nalue rI,, WOOd ba-i, also 'ohio-led
both operations. hurther writing nb the RAM uflhl reset'
For ne N-key rollciner mode - if Iced CU . 5 program--re-)
to I life Chip wit ope r ate in life spend! E r-.r mci-be P
urIne, details See Inreniace Consideration. Sec

F(GURE 9-28 8279 command word (ormats and bit descriptions, (Intel CorporatIon)

272 CHAPTER NtN


RAM -. .- you can determine the mode-set control word for these
LOCATION
cowditions. You should get 00000000.
DISPLAY POSITION
o (R) The next control 'word you nave to send the 8279 s
the progra'--ulock word. 'l'he 8279 requires an internal
[R j bI Ej d j I Li clock frequency of about 100 kHz. A programmable
3 ()j
dlvlirr in the 8279 allows you to apply some available
frequency, such as the 2.45-MHz PCLK signal, to its
4' —I
I I (A) REPRESENtS clock input and divide this frequency down to the needed
I 7SEGMNT
5 L 100 kFlz. The lower 5 bits of the program-clock control

Iii_ij
8 L.-...
word simply represent the binary number you want to
divide the applied clock by. For example, if you want to
divide the input clock frequency by 24. you send a
control word with 001 in the upper 3 bits and 11000 in
th' lower 5 bits.
flie final control word needed for basic initialization
RAM
LOCATION Is the clear word. You need to send this word to tell the
8279 what code to send to the segments to turn them
o (R) DISPLAY POSITION
off while the 8279 is switching from one digit to the
next. (Reter to Figure 9-26 and its discussion.) In
___ [If_I Ribicidi
addition to telling the 8279 what blanking character to
(d) use during refresh, this control word can be used to
clear the display RAM and/or the FIFO at any time. For
5 (A) REPRESENTS now we are only concerned with the first function. The
i SEGMENT
6 CODE FOO A lower 2 bits, labeled C0 in the control word in Figure
7 9-20, specify the desired blanking code. The requIred
8
c..rdc will depend on the hardware connections in a
particular system. For the SDK-86 a high from the 8279
lb turns on a segment, so the required blanking code is all
Os. Therefore you can put 0's In the 2 C 0 bits. The
FIGURE 9-29 8279 RAM and display location
resultant control word is 11000000.
relatiorlships. (a) teft entry. (b) Right entry.
Fhe three control words described so far take care of
the basic initialiaation However, before you can send
scanning a keyboard Or turning on digit drivers, you codes to the internal display RAM, you l'iave to send the
need a pattern of stepping lows. In encoded mode the 8279 a write-display-RAM control word. This word tells
8279 puts o'rt a binary Count sequence on its SLO--SL3 the 8279 that data sent to the data address laler should
scan lines, an I ar external decoder such as the 7445 IS be pn.it in the display RAM. and it tells the 8279 where
used to prodc- ie stepping lows. If you have only 4 'o put the data in the display RAM. The 8279 has an
digits to refresh, you .an program the 8279 in decoded internal 4-bit pointer to the display RAM. The lower 4
mode. in this mode, the 8279 directly outputs stepping bits of the write-display-RAM control word initialize the
lows on the four scan lines. The second choice you have pointer to the location where you want to write a data
to make for this control word is whether you want two- byte in the RAM. If you want to write a data byte to the
key lockout or N-key -otlover. in the two-key mode, one first location in the display RAM, for example, you put
key must be released before another keypress will be 0000 in these bits. If you put a I in the auto increment
detected and processed. In the N-key rollover mode. if bit, labeled Al in the figure. the internal pointer will be
two keys are pressed at nearly the some time, both autoniatIcaily Incremented to point to the next RAM
keypresses will be detected and debounced and their location after each datt byte is written. To start loading
codes put In the FIFO RAM in the order the keys were charactei-s in the first location in the RAM and select
pressed. auto increment, then, the control word is 10010000.
In addition to being used to scan a keyboard, the 8279 Figure 930. p. 274. shows the sequence of instruc-
can also be used to scan a matrix of switch sensors, tions to send the conf'rol words we have developed here'
such as the metal strips and magnetic sensors you see to the 8279 on the SDK-86 board. Also shown are
on store windows and doors. In sensor matrix mode. instructions to send a 7-segment code to the first
the 8279 scans all the sensors and stores the condition location in the display RAM. Note that the control words
of up to 64 swItches In the Flf'O RAM, lithe condition are all sent io the control address. FFEAH. .1 toe
of any of the switches changes. an IRQ signal is Sent character going to the display RAM is sent to the data
out on the IRQ pin. An interrupt service procedure can address. FFE8H. Also note from sheet 7 of Figure 7-8
then sound an alarm and let the guard dogs loose. The that the DO bit of the byte sent to the display RAM
return lines of the 8279 can also function as a strobed corresponds to segment output HO. and D7 of the byte
Input port In much the same way as port A or B on an sent to the display corresponds to segment output A3
8255A. This is important to know when you are making up a
The SDK-86 initializes the 8279 for eight-character table of 7-segeent codes to send to the 8279.
display, left entry, encoded scan. two-key lockout. Sec if You now know how to initialize an 8279 and send

DIGITAL INTIRFACINC 273


INITIALIZATION FIFO STATUS WORD
NOV DX, OFFEAI4 Point at 8279 control address
NOV AL. 000000008 Node set word for left entry,
encoded scan, 2-key Lockout
Hs,nI 0 IUl F I N ! NINI
C&IT DX, AL Send to 8279
NOV AL, 001110008 Clock wor-d for divide by 24
(SiT DX, Al 1 LNUMBER O F CHARACTERS IN FIFO
NOV AL. 110000008 Clear iisptay char is all zeros 1 FIFO FULL
tilT DX, AL ER RO ft - U NOt H FlU N
ERROR-OVERRUN
;SLldD SEVEN SEG)ENT CCOE TO DISPLAT RAN SEN0R CLOSURE/ERROR FLAG
NOV AL, 100100008 Write display RAIl, first location, FOR MULTIPLE CLOSURES
auto increlnent - DISPLAY UNAVAIL8LE
NOV DX, OFFEAN Point at 8279 control address
(SiT DX, At, Send control word FIGURE 9-31 8279 status word format.
NOV DX, OFFE8rI
Point at 879 data address
NOV AL, f,FH Seven seg.eot code for 9
(SiT DX, AL Send to display RAM
P40W AL, .8H Seven segment code for 2
liii OX, AL Send to display .AIl
SDK .86 DISPLAY DRIVER PROCEDURE
;READ KEYBOARD CWE FRON FIFO Figure 9-32 shows an example of an i/O driver which
NOV AL, (I1000000B Control word for read FIFO RAM will send the contents of th four nibbles in the CX
NOV DX, OFFEAS Poict at 8279 controL address register to four SDK-86 LED displays. You may have
(lii DX, AL Send content word
NOV DX, OFFEB' Point at 82s ta addrc' Used this procedure for a variety of experiments: now
IN AL, DX , Psad rita RA14 OU et to see how it works.
This procedure assumes the 8279 has already been
FIGURE 9-30 80& instructions to initialize SDK-86 8279, IT',Itiaiized by the SDK-86 monitor program, or a-s shown
write to display RAM, and read FIFO RAM. in the fist part of Figure 9-30. If AL Is 0 when this
procedure La called, the contents of CX will be displayed
on the data field LEDs. If AL is not 0, then the contents
characters to Its display RAM. Two additional points we of CX wit! be displa yed on the addres,s field LEPs There
need to show you are how to read keypressed codes from are two main points For you to see in this procedure.
the FIFO RAM and how to i-cad the status word. in order The first is the sending of the write-display-RAM
to read a code from the FIFO RAM, you first have to send control word to the 8279 so we can write to the desired
a read FIFOIsen.so: R4M control word to the 8279 locations In ihc display RAM. Note that for ihe data field
control address. Fiurc 9-28 shows the format for this we wrIte a control word of 90H. which tells the 8279 to
word. For a read of the FIFO RAM, (he lower 5 bits of put the next data word se;it into the first location in the
the control word are donI. cares, so yol.. can JUSt make display RAM. Since the 8279 is initialized ior left entry.
them 0's. You send the resultant control word. the first location shouki correspond to the leftmost
01000000, to the control registe; Lddress and then do displa y digit. However, if you look at sheet 8 of the SDK-
a read from the data address. The bottom section of 86 schematics, you will see that digit I (leftmost as far
Figure 9-30 shows this, as the 8279 is concerned) is actually the rightmost on
Now, suppose that the processor receives an interrupt Ihe hoard. This means that for the SDK-86, the position
signal from the 8279, indIcating that one or more valid of a 7-segment code in the display RAM corresponds to
keypresses have occurred. Tue question then comes tip, its position in the display starting from the right! All
How do I know how many codes I should read from the you have to do ts send the 7-segment code lor a number
FIFO? The answer to this question is that you read the you want to display in a particular digit position to the
status register from the control register address betore corresponding location In the display RAM.
you read the FIFO. Flguie 9-31 shows the format for The next part of the display procedure to take a close
this status word. The lowest 3 bits of the status word look at Is the instructions which convert the four hex
Indicate the number of valid character In the FIFO. You nibbles in the CX register to the co sponding 7.
can load this number into a memory location and count segment codes for sending to the display RAM. To do
it down as you read In characters !nctdentally, if more this, we first shuffle and mask to get each nibble into a
than eight characters have been etitered in the FIFO. byte by itself. We then use a lookup table arid the Xt.AT
only the last eight will be kept. The erior-overrun bU. instruction to do the actual conversion. Note that when
labeled 0 In the status word. will be set to tell you that making up 7-segmeril codes for the SDK-86 board, a
characters have been lost. high turns on a segment. bit DO of a display RAM byte
Characters can be rad from the 8279 on a polled represents the , "a" segment. bit D6 represents the 'g"
basis as well as on an interrupt basis. To do this, you segment, and bit D7 represents the decimal point. If you
Simply read and test the status word over and over again are displaying only I-3CD digIts, you can replace the
until bit 0 of the status word becomes a 1. Since upper six values in th segment code table with values
the basic SDK-86 does not have an 8259A to receive which allow you t blank a olgit. display an A or P on a
interrupt inputs, the SDK-86 monitor uses this polling clock, etc. Work your way through thc conversion section
method to tell when the FIFO holds a keypressed code, a a review of using the XLA1 iistructiori.

274 CHAPTER NINE


;8086 PROCEDURE F9-32.ASN

2 ;ABSTRACT : Displays a 4-digit hex or BCD nurer onLEDs of the SDK-86.
3 ;INPUTS : Data in CX, control in AL.
4 AL 0014 data displayed rn data-field of LEDs
5 AL .c> CON data displayed in address field of LE05.
6 ;PORTS : None used
7 ;PROCEDURES: None used
8 ;REGISTERS : Destroys nothing
9
10 PUBLIC DISPLAY_IT
11
12 0000 DATA SEGI4ENT 0 PUBLIC
13 ; 0 1 2 3 4 5 6 7
14 0000 3F 06 5B 4F 666070 + SEVEN_SEQ DB 3FH, 0614, 58H, 4FU, 6614,6014, 7DH, 0714
15 07
16 8 9 A b C d E F
17 0008 iF 6F 77 7C 39 SE 79 * 08 7F14, 6FH, 7714, 7CH, 39H, 5EH, 7914, 7114
18 71
19 0010 DATA ENDS
20
21 0000 C00E SEGIIENT WORD PUBLIC
22 ASSt$E CS;CcOE, DS:DATA
23 0000 DISPLAY_IT PROC FAR
24 0000 9C PUSHF Save flags
25 0001 1E PUSH OS Save caller's registers
26 0002 50 PUSH AX
27 0003 53 PUSH BX
28 0004 51 PUSH CX
29 0005 52 PUSH DX

30 0006 BB 0000s NOV BX, DATA Init DS as needed for procedure
31 0009 B 08 NOV OS, BX
32 0008 BA FFEA NOV DX, OFFEAH Point at 8279 control address

33 000E 3C 00 CI4P AL, 0014 ; If data field required then
34 0010 74 05 JZ DATFLD load control word for data field
35 0012 80 94 NOV AL, 9414 else toad address-field control word

36 0014 EB 03 90 JMP SEND Send control word
37 0017 BO 90 OATFLO: NOV AL, 9014 Load control word for data field
38 0019 EE SEND: DUT OX, AL Send control word to 8279

39 OO1A BB 0000r NOV BX, OFFSET SEVEN_SEQ Pointer to seven-segment codes
40 0010 BA FFE8 NOV DX, OFFEBH ; Point at 8279 display RAM
41 0020 BA Cl NOV AL, CL Get low byte to be displayed
42 0022 24 OF AND AL, OFH Mask upper nibble
43 0024 D7 XLATB Translate lower nibble to 7-seg code
44 0025 EE 007 DX, AL Send to 8279 display RAIl
45 0026 BA Cl NOV AL, CL Get low byte again
46 0028 B1 04 NOV CL. 04 Load rotate count
47 002A D2 CO ROL AL, CL ; Move upper nibble into low position
48 002C 24 OF AND AL, OFH Mask upper nibble

49 002E 07 XLATB Translate 2nd nibble to 7-seg code
50 002F EE DUT DX, AL Send to 8279 display RAM

51 0030 BA CS MOV AL, CH Get high byte to translate
52 0032 24 OF AND AL, OFH Mask upper nibble

53 0034 XLATB Translate to 7-seg code
07
54 0035 00T DX, AL Send to 8279 display RAM

55 0036 8* C5 NOV AL, CU Get high byte to fix upper nibble
56 0038 D2 CO ROL AL, CL Hove upper nibble into low position
57 003A 24 OF AND AL, OFH Mask upper nibble

58 003C 07 XL*TB Translate to 7-seg code
59 0030 EE 001 DX, AL 7-seg code to 8279 display RAM
60 003E SA POP DX Restore all registers and flags
61 003F 59 POP CX
62 0040 SB POP BX
63 0041 58 POP AX
64 0042 iF POP OS
65 0043 90 POP F
66 0044 CB RET
67 0045 DISPLAY_IT EN0P
68 0045 C00E 11105
69 END

FIGURE 9-32 Procedure to display contents of CX register on SDK-&, LED


displays.

- 37 DIGITAL INT[RFACING 275


INTERFACING TO 18-SEGMENT AND be connected to drive an LCD segment and backplane.
DOT-MATRIX LED DISPLAYS Figure 9-33b shows typical diivC waveforms for the
backplane and for the on and the off segments. The off
In the preceding examples we used an 8279 to refresh
(in this case unused) segment receives the same drive
some 7-segment displays. The 7-segment codes for each
signal as the backplane. There is never any voltage
digit were stored In successive locations In the display
between them, so no electric field is produced. The
RAM. To display ASCII codes on 18-segment LED dis-
plays, you can store the ASCII codes for each digit in waveform for the on segment is 180° out of phase
the display RAM. (Remember that the A lines are driven with the backplane signal. so the voltage between this
from the upper nibble of the display RAM and the B segment and the backplane will always be + V. The logic
lines are driven by the lower nibble-) An external ROM for this Is quite simple because you only have to produce
Is used to convert the ASCII codes to the required 18- two signals. a square wave and its complement. To the
segment codes and send them to the segment drivers. driving gates. the segment-backplane sandwich appears
Strobes for each digit driver are produced Just as they as a somewhat leaky capacitor. The CMOS gates can
are for the 7-segment displays in Figure 7-8. The re- easily supply the current required to charge and dis-
freshing of each digit then proceeds just as it does for charge this small capacitance.
the 7-segment displays. Older and/or inexpensive LCD displays turn on and
Pefreshing 5 by 7 dot-matrix LED displays is a little off too slowly to be multiplexed the way we do LED
complex because, instead of lighting an entire displays. At 0C. some LCDs may require as much as
;gtt, you have to refresh one row n' one column at a 0.5 s to turn on or off. To interface to these types
time in each digit. To solve this problem, Beckman we use a nonmultiplexed driver device. Newer, more
)nstr irnents. Hewlett-Packard. and several other compa- expensive LCDs can turn on and off faster, so they are
nk snake large Integrated dispiay/driver devices which often multiplexed using a variety of techniques. In
i-c-, Jre you to send only a series of ASCII codes for the the following Section we show you how to Interface a
racters you want displayed. nonmultiplexed LCD display to a microprocessor such
as the SDK-86.

Lquid-Crystal Display Operation and Interfacing INTERFACING A MICROCOMPUTER TO


NONMULTIPLEXED LCD DISPLAYS

.
LCD OPERATION
Liquid crystal displays are crcted by sandw:.iing a
thin (10 to 12-ii.m) layerofa lIqourystai fluid
Figure 9-34 shows how an Intersil ICM72 11 M can be
"on.neted to drive a 4-digit. rionmultipiexed. 7-segment

two glass plates. A transpare.e rically c-oi


fii rbackplane is put on the r "isssheet. Tran4 UNUSED SEGMENT V0 LIQUID CRYSTAL
ent sections of conductive film .'ape - the desired DIELECTRIC
,haracters are coated on the fe. p)atc. Who

.
voltage is applied between a segment and the backpane.
an electric field is created in the regior under the
egment. This electric field changes the transmission of
1
gn through the region under the segment fiho
There are two commonly available types of LC.':
namtc scattering andfie(d-effeet. The dynamic scaiter- m
Ing type scrambles the molecules where the field is /c\
-sent. This produces an etched-glass-looking light
uacter on a dark background. Field-effect types use
* brization to absorb light where the electric field is
ACTIVE SEGMENT BACKPL*NE
'sent. This produces dark characters on a Silver-gray
Lkground. ()
Most LCDs require a voltage of 2 or 3 V between the
backplane and a segment to turn on the segment. You
can't, however, Just connect the backplane to ground
and drive the segments with the outputs of a TTL
OFF-SEGMENT '
--lJ--1J 1J-
ITJTLr'J-
decoder, as we did the static LED display in Figure
v
9-24. The reason for this is that LCDs rapidly and BACKPLANE
ir;eversibly deteriorate if a steady dc voltage of more
than about 50 mV is applied between a segment and the
l)ckptane. To prevent a dc buildup on the segments,
the segment-drive signals for LCDs must be square
wvs with a frequency of 30 to 150 Hz. Even if you
.1i_1JTLTILII[
fbI
pulse the TTL decoder, It still will not work because the
output low voltage of T'TL devices Is greater than 50 mV. FIGURE 9-33 LCD drive circuit arid drive waveforms.
CMOS gates are often used to drive LCDs, (a) CMOS drive circuits, fbi Segment and backplane
Figure 9-33a shows how-two CMOS gate outputs can drive waveforms.

276 CHAPTER NINE


1CM721 1M

D4 D3 D2 Dl
SEGMENT OUTPUTS SEGMENT OUTPUTS SEGMENT OUTPUTS SEGMENT OUTPUTS

iii till Ii ti fit 1111111


WIDE DRIVER 7 WIDE DRIVER 7 WIDE DRIVER 7 WIDE DRIVER

1111111 1111111 11111 H


7 WIDE LATCH EN] 7WIDELATCH ENI WIDE LATCH EN! WIDE LATCH

I I 11111
I PROGRAMMABLE PROGRAMMABL1 [PROGRAMMABLE PROGRAMMABLE
I 4107 DECODER 4107 DECODER I 4107 DECODER 4107 DECODER
SOK-86 _______ I
0AT
ADO
____
AD1 LATCH I
AD2 1111
A03
ENABI E I

Al
rsi 2-BIT
j LATCH
I I 2 TO4
DS2 __________IDECODER
A? I
ENABLE1 II ENABLE
74LS138

_________H__ OSCILLATOR BACK-


PLANE

__ __H
16KHZ BACKPLANE
FREE- DRIVER OUTPUT
RUNNING
+5V OSCENABLE

ENABLEDETECTOR

FIGURE 9-34 Circuit for interfacing four LCD digits to an SDK-86 bus using
Intersil ICM7211M.

LCD display such as you might buy from your local INTERFACING MICROCOMPUTER PORTS
electronics surplus store. The 721 1M Inputs can be TO HIGH-POWER DEVICES
connected to port pins or directly to microcomputer The output pins on programmable port devices can
buses as shown. For our example here, we have con- typically source only a few tenths of a milliampere from
nected the CS inputs to the Y2 output of the 74LS 138 the +5-V supply and sink only 1 or 2 mA to ground. If
port decoder that we showed you how to add to an SDK- you want to control some high-power devices such as
86 board in Figure 8-14. According to the truth table in lights, heaters, solenoids, and motors with a microcom-
Figure 8-15. the device will then be addressable as ports puter. you need to use interface devices between the
with a base address of FFIOH. SDK-86 system address port pins and the high-power device. This section shows
line A2 is connected to the digit-select input (DS2). and you a few of the commonly used devices and techniques.
'v,lrrn address line Al is connected to the DS1 input.
This gives digit 4 a system address of FFIOH. Digit 3 Integrated-Circuit Buffers
will be addressed at FFI2H. digit 2 at FF14H, and digit
I at FFI6H. The data inputs are connected to the lower One approach to buffering the outputs of port devices
four lines of the SDK-86 data bus. The oscillator input is with TFL buffers such as the 7406 hex inverting and
is left open. 7407 hex noninverting devices. In Figure 9-12. for
To display a character on one of the digits. you simpiy example, we show 74LS07 buffers on the lines from
put the 4-bit hex code for that digit In the lower 4 bits ports to a printer. In an actual circuit the 8255A outputs
of the AL register and output it to the system address to the computer-controlled lathe in Figure 9-7 should
for that digit. The ICM72I IM converts the 4-bit hex also have buffers of this type. The 74LS06 and 74LS07
code to the required 7-segment code. The rising edge of have open-collector outputs, so you have to connect a
the CS input signal causes the 7-segment code to be pull-up resistor from each output to 4-5 V. Each of the
latched in the output latches for the addressed digit: An buffers in a 74LS06 or 74LS07 can sink as much as 40
internal oscillator automatically generates the segment mA to ground. This is enough current that YOU can easily
and backplane drive waveforms shown in Figure 9-33b. drive an LED with each output by simply connecting the
For interfacing with LCD displays -which can be multi- LED and a current-limiting resistor in series between
plexed. the Intersti 1CM7233 can be used. the buffer output and +5 V.

DIGITAL INTERFACING 7
Buffers of this type have the advantage that they come Remember. current gain, or 13, as it is commonjy called.
Ix to parkage, and they are easy to apply. For cases is the ratio of collector current to the base current
where you need a buffer on only one or two port pins or needed to produce that current. To produce a collector
you need more current, you can use discrete transistors. current of 20 mA in a transistor with a (3 of 50 requires
a base current of 20 mA/50 or 0.4 mA. To drive this
buffer transistor, then, the output port pin has to supply
Transistor Buffers only the 0.4 mA.
Figure 9-35 shows some single-transistor circuits you The VOH(PER) specification of the 8255A shows that
can connect to microprocessor port lines to drive LEDs an 8255A peripheral port pin can only source 200 A
or small dc lamps. We will show you how to quickly (0.2 mAl of current and still maintain a legal TFL-
determine the parts values to put In these circuits for compatible output voltage of 2.4 V! The outputs can
your particular appiicion. First, determine whether source more than 0.2 mA. but if they source more than
you want a logic high on the output port pin to turn on 0.2 mA. the output high voltage will drop below 2.4 V.
the device or whether you want a logic low to turn on You don't care about the output high voltage dropping
the device. if you want a logic high to turn on the LED. below 2.4 V except in the unlikely case that you are
then use the NPN circuit. If you want a logic low to turn trying to drive a logic gate input off the same port pin
on the device, use the PNP circuit. Let's usen NPN for as the transistor. Let's assume an output voltage of
the first example. 2.0 V for calculating the value of our current-limiting
Next, determine how much current you need to flow resistor, R,. The value of this resistor is not very critical
through the LED, lamp, or other device. For our example as long as it lets through enough base current to drive
here, suppose that you want 20 mA to flow through an the transistor. The base of the NPN transistor will be at
LED. You then look through your transistor collection about 0.7 V when the transistor is conducting, and the
to find an NPN transistor which can carry the required output port pin will be at least 2.0 V. This leaves a
current, has a collector-to-emitter breakdown voltage voltage of 1.3 V across Rb . Dividing the 1.3 V across Rb
(V-Eo) greater than the applied supply voltage, and can by the desired base current of 0.4 mA gives an Rb value
dissipate the power generated by the current flowing of 3.25 kfl. A 2.7-kfl or 3.3-kil resistor will work fine
through it. We usually keep some inexpensive 2N3904 here,
NPNs and some 2N3906 PNPs on hand for low-current if you chose to use the PNP circuit in Figure 9-35b.
switch applications such as this. Some alternatives are an output pin on an 8255A could easily sink enough
the 2N2222 NPN and the 2N2907 PNP. current to drive the base of the transistor, The VOL(PER)
When you decide what transistor you are going to use. specification for an 8255A indicates that an output pin
look up its cuj-rent gain. h. on a data sheet. If you can sink at least 1.7 mA and still have an output low
don't have a data sheet, assume a value of 50 for the voltage no greater than 0.45 V. The base of the PNP
current gain of small-signal transistors such as these. transistor in Figure 9-35b will be at about + 4.3 V when
the transistor is on. and the output of the 8255A will
be at about +0.3 V. This means that the R b in Figure
+5 V 9-35b has about 4 V across it. Dividing this voltage by
the required 0.4 mA gives an Rb value of 10 kf1,
When you need to switch currents larger than about
50 mA on and off with an output port line, a single
1500
transistor does not have enough current gain to do this
dependably. One solutton to this problem is to connect
FROM OUTPUT 2.1 K
two transistors in a Darllngton configuration, as shown
PORT PIN >____vMv___tN39o4
In Figure 9-36. A circuit such as this might be used to
drive a small solenoid valve which controls the flow of a
chemical into our printed-circuit-board-making ma-
(a) chine or a small solenoid in the, print heads of a
dot-matrt.x printer. The dotted lines around the two
transistors in Figure 9-36 indicate that both devices
+5 V
are contained in the same package. Here's how this
N,, configuration works.
FROM OUTPUT
POATFIN 2N3906 The output port pin supplies base current to transistor
82K
OR Ql. This base current produces a collector current 13
times as large in Q I. The collector current ofQ I becomes
the base current of Q2 and is amplified by the current
gain of Q2. The result of this is that the device acts like
1150 a single transistor with a current gain of (3 QI x 13 Q2
and a base-emitter voltage of about 1.4 V. The internal
Ib) resistors help turn off the transistors. The TIP 110 device
we show here has a minimum (3 of 1000 at I A, so if we
FIGURE 9-35 Transistor buffer Circuits for driving LED
assume that we need 400 mA to drive the solenoid, then
from 8255A port pin. (a) NPN. (b) PNF'.
the worst-case current that must be supplied by the

278 CHAPTfR N4INE


Figure 9-36. This Induced voltage, sometimes called
Inductive "kick," will usually be large enough to break
down the transistor if you forget to put in the diode.
RELAY COIL
1N4002 . OR SOLENOID When the coil Is conducting. the diode is reverse-biased.
so it doesn't conduct. However, as soon as the induced
voltage reaches 0.7 V. the diode turns on and supplies
—1 a return path for the induced current. The voltage across
the inductor then is clamped at 0.7 V, the voltage across
FROM
8255A a conducting diode, so the transistor is saved.
OUTPUT TIP 110 Figure 9-37a shows how a device cailed a power
PIN. MOSFET transistor can be used to drive a solenoid,
relay, or motor winding. Power MOSFETS are somewhat
8K 60 more expensive than bipolar Darlingtons. but they have
>WJ
L -J
the advantage that they require only a voltage to drive
them. The Motorola IRFI3O shown here, for example,
requires a maximum gate voltage of only 4 V to turn on
a drain current of 8 A. Note that this MOSFET circuit
FIGURE 9-36 Darlington transistor used to drive relay also needs a reverse-biased diode across the solenoid to
coil or solenoid. protect the transistor from inductive kick.
Figure 9-37b shows a power driver Circuit using a
newer device called an Isolated-Gate Bipolar Transistor
output port pin is about 400 mA/l000 or 0.4 mA. As we (IGBT). In IGBT data books you may see the device
indicated before, a port pin can easily do this. referred to as an IGBT or as an MOSIGT. As you might
If the drive current required for the Darlington is too expeCt from the schematic symbol, these devices are a
high for the port output, you can add, for example, a compromise between bipolar transistors and MOSFETs.
3.3-ku resistor from the transistor base to +5 V to They have the high input impedance and fast switching
supply an additional milhiampere of drive current. The speed of MOSFETs, and they have the low voltage drop
port output can easily sink this additional milliampere and high current-carrying capacity of bipolar transis-
of current when it is in the low state. Also, another tors. The Toshiba MG400HIIJS1. for example, has a
transistor could be added as a buffer between the output collector-emitter breakdown voltage of 560 V and can
pin and the Darlington input. Note that since the V o
the Dartington is about 1.4 V. a smaller Rb is needed
here. Now let's check out the power dissipation.
According to the data sheet for the TIP1 10, it comes
in a TO-220 package which can dissipate up to 2 W at MOTOR WINDING
OR SOLENOID
an ambient temperature of 25CC with no beat sink. With
400 mA flowing through the device, it will have a
collector-emitter saturation voltage of about 2 V. Multi-
plying the current of 400 mA times the voltage drop of
2 V gives us a power dissipation of 0.8W for our circuit I,
here. This is well within the limits for thedevice. A rule FROM
)f thumb that we like to lollow is. If the calculated power OUTPUT
PORT PIN I IRF13O
lissipation for a device such as this is more than half
of its 25CC no-heat-sink rating, mount the device on the
chassis or a heat sink to make sure it will woEk on a hot
day. If mounted on the appropriate heat sink, the device (a)
will dissipate 50W at 25CC:
One more Important point to mention about the
circuit- in Figure 9-36 Is the reverse-biased diode con-
nected across the solenoid coil. You must remember to MOTOR WINDING
put in this diode whenever you drive an Inductive load OR SOLENOID
such as a solenoid, relay, or motor. Here's why. The
basic principle of an inductor is that it fights a change
in the Current through it. When you apply a voltage to
the coil by turning on the transistor, it takes a while for
the current to start flowing. This does not cause any PORT PIN
major problems. However, when you turn off the transis-
tor. the collapsing magnetic field in the inductor keeps
the current flowing for a while. This current cannot flow )b)
through the transistor, because it is off. Instead, this
current develops a voltage across the inductor with the FIGURE 9-37 Circuits for driving solenoid or motor
polarity shown by the + and - signs on the coil in winding. Cal Power MOSIET circuit. (b) IGBT circuit.

DIGITAL INTERFACING 279


switch a maximum current of 400 A. A driver device
such as the National DS0026, Motorola MMH1)fl2, or
Silicon General SG1626 is used to convert the logic
signal from an output port to the voltage and current
levels required to rapidly switch high-power MOSFETs
and IGHTs on and off.

Interfacing to AC Power Devices


To turn 110-V. 220-V. or 440-V ac devices on and off
under microprocessor control, We Usually use mechani-
cal or solid-state relays. The control circuitry for both
of these types of relay is electrically isolated from the
actual switch. This is very important, because if the
110-V ac line gets shorted to the line of a microcom-
puter, It usually ba.es most of the microcomputers ICs.
Figure 9-38a shows a picture of a mechanical relay. SSIRT-120010
This relay has both normally open and normally closed
contacts. When a current is passed through the coil of
the relay, the switch arm is pulled down, opening the
top contacts and closing the bottom set of contacts. The
contacts are rated for a maximum current of 25 A, so
this relay could be used to turn on a 1- or 2-hp motor
or a large electric heater in one of the machines in our
electronics factory. When driven from a 12-V supply, the
coil requires a current of about 170 mA. The Darlington
circuit shown in Figure -*ca*d easily drive this relay
coil from a microcomputer port line.
Mechanical relays, sometimes called conactors. are
available to switch currents from milliamperes up to
several thousand amperes. Mechanical relays, however,
have several Serious problems. First of all, when the
contacts are opened and closed, arcing takes place
between the contacts. This causes the contacts to oxidize
and pit, just as the ignition points in older-style cars
used to do. As the contacts become oxidized, they make
a higher-resistance contact and may get hot enough to PRD-11AY0120
melt. Another disadvantage of mechanical relays is that
they can switch on or off at any point in the ac cycle.
Switching on or off at a high-voltage point in the ac
cycle can cause a large amount of electrical noise, called
electromagnetic interference (EM!). The solid-state re- +5V
lays discussed next avoid these problems to a large 120 VAC
extent.
Figure 9-38b shows a picture of a solid-state relay - - - -
1
which is rated for 25 A at 25°C if mounted on a suitable
heat sink. Figure 9-38c shows a blocI diagram of the
circuitry in the device and how it is connected from an
output port to an ac load.
F
The input circuit of the solid-state relay is Just an T01
LED. A simple NPN transistor buffer and a current-
limiting resistor are all that is needed to Interface the LOAD wsw
relay to a microcomputer output port pin. To turn the HtATtR
relay on, you simply output a high on the port pin. This 2N3904
I IN - ' - k
27K A = PF-IOTOTRANSISTOR
turns on the transistor and pulls the required 11 mA B ZERO CROSSING DETECTOR
through the internal LED. The light from the LED is C = TRIGGER CKT
focused on a phototransistor connected to the actual 0 = SNUBBER CKT
output-controlclrcuitry. Since the only connection be-
tween the Input circuit and the output circuit Is a beam
of light, there are several thousand volts of isolation FIGURE 9-38 Relays for switching large currents. (Potter
between the input circuitry and the output circuitry. a p r! Brumuieldl ( a) techanicaI. lbl Solid-state.
The actual switch in a solid-state relay isa triac. When Ic) Internal circuitry br soIidstate relay.

280 CHAPTER NINE


triggered, this device conducts on either half of the ac Common step sizes for stepper motors range from 0.9°
cycle. Thezerb-voltage detector makes sure that the triac to 30°. A stepper motor is stepped from one position to
is only triggered when the ac line voltage is very close to the next by changing the currents through the fields in
one of its zero-voltage crossing points. If you output a the motor, The two common field connections are re-
signal, to turn on the relay, the relay will not actuajly ferred to as two-phase and four-phase. We will dicuss
turn on until the next time the ac line voltage crosses four-phase steppers here because their drive circuitry
zero. This prevents .the triaC from turning on at a high- is much simpler.
voltage point in the ac cycle, which would produce a Figure 9-39, p. 282. shows a circuit you can use to
burst of EM!. Triacs automatically turn off when the interface a small four-phase stepper such as the Superior
Current through them drops below a small value called Electric M061-FD302, IMC Magnetics Corp. Tormax
the holding current, so the triac automatically turns off 200, or a similar, nominal 5-V unit to five microcomputer
at the end of each half-cycle of the ac power. If the control port lines. If you butld up this circuit, bolt some small
signal is on. the trigger circuitry will automatically heat sinks on the MJE2955 transistors and mount the
retrigger the triac for each half-cycle. If you send a signal l0-W resistors where you aren't likely to touch them,
to turn off the relay, it will actually turn off the next Since the 7406 buffers are inverting, a high on an
time . the alternating current drops to zero. In this type output-port pin produces a low on a buffer output. This
of solid-state relay, the triac Is always turned on or off low turns on the PNP driver transistor and supplies
at a zero point on the ac voltage. Zero-point switching current to a winding. Figure 9-39b shows the switching
eliminates most of the EMI that would be caused by sequence to step a motor such as this clockwIse or
switching the triac on at random points in the ac cycle. counterclockwise, (The directions assume yoti are facing
Solid-state relays have the advantages that they pro- the end of the motor shaft.) Here's how this works.
duce less EMI, they have no mechanical contacts to arc, Suppose that SW1 and SW2 are turned on, Turning off
and they are easily driven from microcomputer ports. SW2 and turning o SW4 will cause the motor to rotate
Their disadvantages are that they are more expensive one step of 1.8° doe wise, Changing to SW4 and SW3 on
than equivalent mechanical relays and there is a voltage will cause the moW to rotate another 1,8° clockwise.
drop of a couple of volts across the triacs when they are Changing to SW3 and SW2 on will cause another step.
on. Another potential problem with solid-state relays After that, changing to SW2 and SW1 on again will cause
occurs when driving large Inductive loads, such as another step clockwle, You can repeat the sequence un-
motors. Remember from basic ac theory that the voltage til the motor has rotated as many steps clockwise as you
waveform leads the current waveform in an ac circuit want. To step the motor counterclockwise, you simply
with inductance. A triac turns off when the current work through the switch sequence in the reverse direc-
through It drops to near zero. In an inductive circuit, tion. The motor is held in position between steps by the
the voltage waveform may be at several tens of volts current through the coils. Figure 9-39c shows the switch
when the current is at zero, When the triac is conducting. sequence that can be used to rotate the motor half-steps
it has perhaps 2 V across it. When the triac turns off. of 0.9° clockwise or counterclockwise.
the voltage across the triac will quickly jump to several A close look at the switch sequence in Figure 9-39b
tens of volts. This large dV/dT may possibly turn on the shows an interesting pattern. To take the first step
triac at a point when you don't want it turned on. To clockwise from SW2 and SWI being on, the pattern of
keep the voltage across the iriac from changing too l's and Os is simpl y rotated one bit position around to
rapidly, an RC snubber circuit is connected across the the right. 't'he 1 from SW1 is rotated around into bit 4,
triac. as shown in Figure 9-38c. A system example in To take the next step, the switch pattern is rotated one
the next chapter uses a solid-state relay to control an more bit position. To step counterclockwise, the switch
electric heater. pattern Is rotated lef'. one bit position for each step
desired. This rotating pattern can easily be produced
with a sequence of 8086 instructions. Suppose that you
Interfacing a Microcomputer to a Stepper Motor initially lOad 00110011 into AL and output this to the
switches. (Duplicating the switch pattern In the upper
A unique type of motor useful for moving things in half of AL will make stepping easy.) To step the motor
small Increments is a stepper motor. Instead of rotating clockwise one step. you just rotate this pattern right one
Smoothly around and around as most motors do, stepper bit position and output it to the switches. To step
motors rotate, or "step," from one fixed position to the counterclockwise one step, you rotate the switch pattern
next. If you have a dot-matrix printer such as an Epson left one bit position and output it. You can repeat the
FX, look inside and.you should see one small stepper rotate and output sequence as many times as needed to
motor which is used to advance the paper to the next produce the desired number of steps.
line position and another small stepper motor which is Alter you output one step code, you must wait a few
used to move the print head to the next character milliseconds before you output another step command
position. While you are in there, you might look for a because the motor can step only so fast. Maximum step-
small device containing all l.Ef) and a phototranslstor ping rates for different types olsteppers vary from a few
which detects when the print head is in the "home huctred steps per second to several thousand steps per
position. Stepper motors arc also used to position the second. To achieve high stepping rates. thetepping rate
rcadiwrite head over the desired track of a flopp y disk is slowtv increased to the maxtmum and then decreased
and to iiiovc the pert around on X-Y plotters. as the desired number of steps is approached.

L)ICITAI. INTIRFACtN(, 281


OPTIONAL LOW POWER
HOLD CIRCUIT. 5V -l?V *12V
CONNECT POINT A TO
+1? V IF SWITCH NOT USED.
I 120 1K
I 2A
I DIODE
SWITCH
PORT BIT STEP
OF SW4 SW3 SW2 SW1 cW
MICROCOMPUTER L--- - ------
1K 1 0 0 I 1
16 7406 I A 2 1 0 0 I
3 1 I 0 0
N4

if 470
4
1

SWITCH ON
0
0
1
0
1
1
0
1
cCW
1/6 7406
1 N 4002 bI
12
01
470
-':: j 2:r-j.. -
1/67406 EIGHT-STEP INPUT SEQUENCE
HALF-STEP MODE)
1 N 4002
02 —I MJE29S5 __________
STEP SW4 SW3 SW?
470 SW1
I K'" RED/WHITE I - 1 0FF OFF ON ON
1/67406 2 OFF OFF OFF ON
1N4002 3 ON OFF OFF ON
03 Mit 2955 ___________ 4 ON OFF OFF OFF
470
GREEN/WHITE 5 ON ON OFF OFF
6 OFF ON OFF OFF
Rl.- A2
80 7 OFF ON ON OFF
1/6 7406 iow1• 10' OFF OFF
8 OFF ON
1 OFF OFF ON ON
D4
(41

FWURE 9-39 Four-phase stepper motor interface Circuit and stepping


waveforms. (a) Circuit. (b) Full-step drive signal order. (C) Half-step drive signal
order.

When you step a stepper motor to a new position. it However, for higher stepping rates and more torque
tends to oscillate around the new position before settling while stepping. we use a higher supply voltage and
down. A common software technique to damp out this current-limiting resistors, as shown. The point of this
oscillation is to first send the pattern to step the motor Is that by adding Series resistance, we decrease the LJR
toward the new position. Wher. the motor has rotated time constant, This allows the current in the windings
part of the way to the new position, a word to step the to change more rapidly. For the motor we used, the
motor backward is output for a short time. This is like current per winding is 0.88 A. Since only one winding
putting the brakes on. The step-for-ward word is then on each resistor is ever on at a time, 6.5 V/0.88 A gives
sent again to complete the step to the next position. The a resistor value of 7.4 fl. To be conservatIve, we used
timing for the damping command must be determined 8-ft. iO-W resistors. The optional transistor switch and
experimentally for each motor and load. diode connection to the + 5-V supply arc used as follows.
Before we go on. here are a couple of additional points When the motor is not stepping, the switch to + 12 V is
about the Circuit in Figure 9-39a. in case you want to off. so the motor is held in position by the current from
add a stepper to your robot or some other project. First the +5-V supply. Before you send a step command, you
of all. dont forget the clamp diodes across each winding turn on the transistor to #12 V to give the motor more
to save the transistors from inductive kick. Second. we current for stepping. When stepping is done, you turn
need to explain the function of the current.limiting off the switch to + 12 V. and drop back to the +5-V
resistors, RI and P2. The motor we used here has a supply. This Cuts the power dissipation.
nominal voltage rating of 5.5 V. This means that we In small printers, one or more dedicated microproces-
could have designed the circuit to operate with a voltage sors are used to control the various operations in the
of about 6.5 Von the emitters of the driver transistors printer. In this case, the microprocessors have plenty of
(5.5 V for the motor plus 1 V for the drop across thc time to control the Print-head and line-feed stepper
transistor). For low stepping rates, this would work fine. motors In software, as we described above. For applica-

282 CHAPTER NINE


tions where the main microcomputer is too busy to be need information about the position, direction of rota-
bothered with controlling a stepper directly. a smart tion, and speed of rotation of various motor shafts. The
stepper controller device, such as the Sprague UCN- microcomputer. of couIe, needs this information in
5804B shown in Figure 9-40. can be used in place of digital form. The circuitry which produces this digital
the circuitry in Figure 9-39. This device is manufactured information from each motor for the microcomputer Is
with a combination of CMOS and bipolar technology, so called a shaft encoder. There are two basic types of shaft
it has high input impedance and high output current encoders, absolute and incremental. Here's how these
drive capability. The device contains a shift resister to two types work.
produce the step patterns, the power driver transistors.
and the clamp diodes. Control inputs allow you to specify Absolute Encoders
half-step or full-step operation. step direction, and type
Absolute encoders have a binary-coded disk such as the
of motor. To step the motor, a pulse or series of pulses
one shown in Figure 9-41. p. 284, on the rotating shaft.
is applied to the STEP input. A programmable counter
Light sections of the disk are transparent, and dark
such as the 8254 we discussed earlier in the chapter
sections are opaque. An LED is mounted on one side of
could be programmed to send a desired number of pulses
each track, and a phototransistor is mounted on the
to the controller.
other side of each track, opposite the LED. Outputs
For applications where steps of 0.9° are not small
from the four phototransistors will produce one of the
enough, a technique called 'microstepping" is used to
binary codes shown in Figure 9-41. The phototransistor
produce as many as 25,000 steps per revolution. For
outputs can be conditioned with Schmitt-trigger buffers
microstep control, each winding is driven with the
and connected to input port lines. Each code represents
output of a D/A converter instead of with on/off switches.
an absolute angular position of the shaft in its rotation.
This means that the current through a winding can
With a 4-bit disk. 360° are divided up into 16 parts, so
have a range of values instead of just zero or maximum.
the position of the shaft can be determined to the nearest
lithe current ratios in the four windings are changed
slightly, the motor will take a tiny step. Microstepping 22.5°. With an 8-bit disk, the position of the disk can
be determined to the nearest 360°1256, or 1.4°.
is much more éomplex to implement. but it produces
Note that the codes in Figure 9-41 follow a Gray-code
very smooth and precise motion.
sequence rather than a normal binary count sequence.
Using Gray code reduces the size of the largest possible
OPTICAL MOTOR SHAFT ENCODERS error in reading the shaft position to the value of the
In order to control the machines in our electronics least significant bit. If the disk used straight binary
factory, the microcomputers in these machines often code, the largest possible error would be the value of the

+29 V

DI AEC
CONTI

STEP
INPUT JL

FIGURE 9-40 UCN-5804B stepper motor driver.

38 DiGITAL. INTERFACING 283


AhnIut' encoding using a Gra y-code disk has the
\t000H/ advantage that each position is represented by a specific
\ IO01\ /0001/ code which can be directly read in by the microcomputer.
Disadvantages of absolute encoding are the multiple
IOu )Ol 1 detectors needed, the multiple lines required, and the
difficulty keeping track of position during multiple rota-
1010 0010 tions. Incremental encoders solve some of these
problems.
1110 011O
Incremental (ncoders
1111 >111 An Incremental encoder produces a pulse for each incre-
ment of shaft rotation. Figure 9-42 shows an early
1101,7 -\ version of the Rhino XR-2 robot arm, which uses Incre-
0100"\ mental encoders to determine the position and direction
of rotation for each of its motors. For this encoder, a
metal disk with two tracks of slotted holes is mounted
FIGURE 9-41 Gray-code optical-encoder dish used to on each motor shaft. An LED is mounted on one side of
determine angular position of a rotating shaft. each track of holes, and a phototransistor is mounted
opposite the LED on the other side of the disk. Each
phototransistor produces a train of pulses as the disk
most significant bit. Look at the parallel listings of Is rotated. The pulses are passed through Schmitt-
binay and Gray codes in Table I-I to help you see why trigger buffers to sharpen their edges.
this is the case. The top part of Figure 9-43 shows a section of the
To start, assume that a binazy-encoded disk was used encoder disk straightened out so it is easier to see the
and that the disk was rotating from position 0111 (7) pulses produced as it rotates. The two tracks of slotted
to position 1000 (8). Now suppose that the detectors holes are 90° out of phase with each other, so as the
pick up the change to 000 on the least significant 3 bits. disk is rotated, the waveforms shown at the bottom of
but don't pick up the change to 1 on the most significant Figure 9-43 wIll be produced by the phototransistors for
bit. The output code would then be 0000 instead of the rotation in one direction. Rotation in the other direction
desired 1000. This is an error equal to the value of the will shift the phase of the waveforms 180°, so that the
MSB. Now, while this is fresh in your mind, look across B waveform leads the A waveform by 90' instead of
the table at the same position change for the Gray-code lagging It by 90°. Now the question is, How do you get
encoder. The Gray code for position 7 is 0100. and the position, speed, and direction information from these
Gray code for positIon 8 Is 1100. Note that Only I bit waveforms?
changes for this transition. If ou look at the Gray-code You can determine the speed of rotation by simply
table closely, you will see that this Is the case for all the counting the number of pulses from one detector in a
transitions. This means that if a detector fails to pick fixed time interval, such as I s. As we described In
up the new bit value during a transition, the resulting Chapter 8. you can use a programmable timer and an
code will always be the code for the preceding position.
This represents a maximum error equal to the value of
the LSB. ENCODER DISK
OUTER
IA)
INNER
ID)

HI
A
LO

B I I
I ____________ I I
I p I I I
0° 90' 180' 270' 360' 90° 190' 270° 360'
I I I
00 I
10 I ii I 01 I 00 10 I 11
I
I
01 I 00 I 10

0.004 SEC.
ONE CYC(E

FIGURE 9-42 Rhino XR robotics system. (Rhino Robots FIGURE 9-43 Optical-encoder disk slot pattern and
Incorporated) output waveforms.

284 CHAPTER NINE


interrupt procedure to count off intervals of 1 s. If you makes the exact posit1'n of the motor shaft less critical.
Connect the output of the detector to another Interrupt Therefore, for the Rhino, six sets of slots in the encoder
input, you can use another interrupt procedure to count disk are sufficient. However, for applications where a
the number of holes that pass by in a 1-s interval. Each much more accurate indication of shaft position is
track has sb holes, so six pulses will be produced for needed, a self-contained shaft encoder such as the
each revolution. Some simple arithmetIc will give you Hewlett-Packard HEDS-5000 is attached to the motor
the speed In revolutions per minute (rpm). shaft. These encoders have two track-encoder disks with
You can determine the direction of rotation with 500 tiny radial slits per track. The waveforms produced
hardware or with software. For the hardware approach. are the same as thos. shown for the Rhino encoder in
connect the A signal to the D input of a D flip-flop and Figure 9-43. but at a much higher frequency for the
the B signal to the clock input of the flip-flop. The rising same motor speed.
edge of the B signal will clock the level of the A signal at Another common application for optical encoders is
that point through the flip-flop to its Q output. If you to produce digital information about the distance and
look at the waveforms in Figure 9-43, you should see direction that a computer mouse is moved. The
that the Q output will be high for rotation in the Logictech mouse, for example, uses one optical encoder
direction shown. You should also be able to convince disk to produce pulses for vertical motion and another
9
yourself that, the output will be low for rotation in the optical encoder disk to produce pulses for horizontal
other direction. motion. As you move the mouse around on your desk.
To determine the direction of rotation with software. the rubber bail on the bottom of the mouse rotates the
you can detect the rising edge of the B signal on a polled encoder disks. Data from the encoders is processed and
or an Interrupt basis and then read the logic level on sent to the microcomputer. The microcomputer uses
the A signal. As shown In the waveforms, the A signal the data from the mouse to move the on-screen cursor
being high when B goes high represents rotation in oie to the desired location.
direction, and the A signal being low when B goes high Optical encoders In their many different forms are an
represents rotation in the opposite direction. important part of a large number of microcomputer-
To determine the position of the motor shaft, you controlled machines.
simply count off how many holes the motor has moved
from some "home" position. On the Rhino robot arm a
small mechanical switch on each axis is activated when
the arm Is in its starting. or home, position. When you CHECKlIST OF IMPORTANT TERMS AND
turn on the power, the motor controller/driver box CONCEPTS IN THIS CHAPTER
automatically moves the arm to this home position. To
move the arm to some new position, you calculate the If you do not remember any of the terms in the following
number of holes each motor must rotate to get the arm list. U3e the index to help you find them in the chapter
to that position. For each motor, you then send the for review.
controller a command which tells it which direction to
rotate that motor and how many holes to rotate it. The Simple input and output
controller will drive the motor the specified number of Strobed [/0
holes in the specified direction, If you then manually
rotate the encoder wheel or some heavy load moves the Single-handshake i/O
arm and rotates the encoder disk, the controller will
Doubk-handshake data transfer
detect the change in position of the disk and drive the
motor back to its specified position. This is an example 8255A initialization
of digital feedback control, which is easily done with a Mode 0. mode 1. mode 2
microcomputer. The Rhino controller uses an 8748 Mode definition control word
single-chip microcomputer to Interpret and cany out Set/reset control word
the commands you send it. Commands are sent to the
Computer numerical control (CNC) machines
controller In the serial ASCII form described at the start
of Chapter 13. Centronics parallel printer standard
Incidentally, you may wonder at this point Why the
designers of the Rhino arm did not use stepper motors 110 driver
such as those we described in a previous section. The Control block
answers are: Stepper motors are much more expensive Sentinel
than the simple dc motOrs used, and if a stepper motor Keyswitches—mechanical. capacitive, Hall effect
Is forced back a step by a sudden load change. there Is
no way to know about it and correct for it unless It Detect, debounce. and encode a keyboard
has an external encoder. Also, the dc motor-encoder Two-key lockout, two-key rollover
approach better demonstrates the method used In large
commercial robots. Code conversion using compare method
In the Rhino robot arm, each motor drives its section Code conversion using XLAT method
of the arm through a series of gears. Gearing the motor
down reduces the force that the motor has to exert and Error trapping

DIGITAL INTERFACING 285


LED Interfacing Field-effect display
f)Ir't drivr' Backplane drive
Software-multiplexed display
Relays
8279 hardware display controller
Mechanical
8279 display and keyboard operation Solid-state
Encoded and decoded scan Electromagnetic interference
Keyboard/display mode Set control word Zero-point switching
Clear control word RC snubber Circuit
Write-display control word
Four-phase stepper motor drive
LCD interfacing
Dynamic scattering display Shaft encoders—absolute and incremental

REVIEW QUESTIONS AND PROBIEMS


I. Why must data be sento a printer on a handshake 9. Modify the printer driver procedure in Figure 9-16
basis? so that it stops sending characters to the,printer
when it finds a sentinel character of 03H, instead
2. For the double-handshake data transfer in Figure
of using the counter approach.
9-Id.
a. Indicate which signal is asserted by the sender 10. Would the software method of generating the
and which signal is asserted by the receiver. STROBE signal to the printer in Figure 9-6 still
b. Describe the meaning of each of the signal work if you tried to run the program with an 8-
transitions. MHz 8086?
3. Why are the port lines of programmable port devices 11. Show the instructions you would use to read the
automatically put in the input mode when the Status byte from the 8255A in Question 5.
device is first powered up or reset?
12. Describe the three major tasks needed to get mean-
4. An 8255A has a system base address of FFF9H. ingful information from a matrtx keyboard.
What are the system addresses for the three ports
and the control register for this 8255A? 13. Describe how the compare method of code conver-
sion in Figure 9-20 works.
5. a. Show the mode set control word needed to
initialize an 8255A as follows: Port A—hand- 14. Why is error trapping necessary in real programs?
shake input: Port B—handshake output; Port Describe how the error trap in the program in
C—bits PC6 and PC7 as outputs. Figure 9-20 works.
b. Show the bit set/reset control word needed to IS. Assume that the rows of the circuit shown in Figure
initialize the port A interrupt request and the 9-44 are connected to ports EFF8H and the 74148
port B Interrupt request. is connected to port FFFAH of an SDK-86 board.
c. Show the assembly language instructions you The 74148 will output a low on its GS output if a
would use to send these control words to the low is applied to any of its inputs. The way the
8255A in problem 4. keyboard is wired, the A2, Al. and A0 outputs will
d. Show the additional instruction you need if you have a 3-bit binary code for the column in which a
want the handshake to be done on an interrupt low appears. Use the algorithm and discussion of
basis through the 1R3 input of the 8259A in Figure 9-20 to help you write a procedure which
Figure 8-14. detects a keypress. deb.ouiices the keypress, and
e. Show the instructions you would use to put a determines the row number and column number
high on port C, bit PC6 of this device. of the pressed key. The procedure should then
6. Describe the exchange of signals between the tape combine the row code, column code, shift bit, and
reader, 8255A, and 8086 in Figure 9-7 as a byte of control bit into a sirgle byte in the form: control.
data is transferred from the tape reader to the shift, row code, column code. The XLAT instruction
microprocessor. can then be used to convert this code byte to ASCIi
for return to the calling program. Hint: Use a DB
7. When connecting peripheral devices such as print. directive to make up the table of ASCII codes.
ers, terminals. etc.. to a computer, why is it very Why is the XLAT approach more efficient than
important to connect the logic ground and the the compare technique for this case?
chassis gour.d together oniy at the computer?
NOTE: For test purposes, the keyboard matrix
8. Describe the function and direction of the following can be simulated by building the diodes, resistors,
signals_in a Centronics parallel printer Interface. and 74148 on a proiotyping board and using a
a. STROBE jumper wire to produce a "keypress.'
b. ACKNLG
c. BUSY 16. a. Calculate the value of the current-limiting resis-
d. INIT tor needed in Series with each segment of a 7-

286 CHAPTER NINE


*5 V row. The process is repeated until all rows are done
and then started over.
0 0 0 0 0 0 0 0 The row patterns can be kept in a table in
OUTPUT
PORT memory. If you want to display a sequence of letters,
ROW 47 you can display the Contents of one table for a
6 -O )' 7'
pa p*
00 few seconds and then switch to another table
DI
I 0 II] U L K1 J containing the second letter. Using the rotate in-
struction, you can produce some scrolled displays.
02 V U I S P o Hint: The wiring required to build the LED matrix
0 I A
3 2 1 0 2 4.760 can be reduced by using an IC 5 by 7 dot-matrIx
03 - -P% LED display such as the Texas Instruments T1L305.
- 9 8 7 4.1 Efl Write the algorithm and program for an inter-
04
rupt procedure (called every 2 msf to refresh these
I BS IF DEl. N UL 4710
__ displays.
ESC TAB 47 60 19. You are assigned he job of fixing several SDK-86
- boards with display problems. For each of the
7 CS 47 60
- following problems, describe a possible cause of the
6 5 4 3 2 1 0 COLUMN problem and tell where you would look with an
Il 12 73 1 2 3 4 oscilloscope to check out your theory. Use the
2 3 4 5 - , -9 sv
INPUT circuit on sheet 7 of Figure 7-8 to help you.
74148
76 a. A segment never lights.
l • t El E
1 7 6 74 5 b. The leftmost digit of the data field never lights.
___-___ 'NC c All the displays show dim "eights."
+5 V
20. a. Show the command words and assembly lan-
D---________ -_________ guage instructions necessary to initialize an
4.7 CO 8279 at address 801-I and 821-I as follows: 16-
06 ---' ---. ________ SIIIFT character display, left entry, encoded-scan key-
07 CONTROL ir board, N-key rollover; 1-MHz input clock di-
vided to 100 kflz; blanking charcter FFH.
b. Show the 8279 instructions necessary to write
FIGURE 9-44 Interface circuitry for unencoded matrix 99H to the first location in the display RAM and
keyboard for problem 15. autoincrement the display RAM pointer.
c. Show the assembly language instructions nec-
essary to read the first byte from the 8279 F1FO
RAM.
segment display driven by a 7447 if you want d. Determine the 7-segment codes you would have
40 mA per segment. to send to the SDK-86 8279 to display the letters
b. Approximately how much current is being HELP on the data field display. Remember that
pulsed through each LED segment on the SDK- DO of the byte sent - BO and D7 of the byte
86 board? sent = A3.
17. a. Write the algorithm for a procedure which e. Show the sequence of instructions you can
refreshes the multiplexed LED displays shown send to the 8279 of the SDK-86 board to blank
in Figure 9-25. Assume that the procedure will the entire display.
be called evely 2 ms by an interrupt signal to 21. Write a procedure which polls the LSB of the 8279
lR4 of an 8259A. status register on the SDK-86 board until it finds
b. Write the assembly language instructions for a key pressed, then reads the keypressed code from
the display refresh procedure. Since this proce- the FIFO RAM to AL and returns.
dure Is called on an interrupt basis, all display 22. Why must the backplane and segment-line signals
parameters should be kept in named memory be pulsed for LCD displays?
locations, If you have time, you can add the
23, Draw a circuit you could attach to an 8255A port
circuitry shown in Figure 9-25 to your micro-
B pin to drive a 1-A solenoid valve from a + 12-V
computer so 'ou can test your program.
supply. You want a high on the port pin to turn on
IS. Figure 9-45. p. 288. shows a circuit for an 8 by 8 the solenoid:
matrix of LEDs that you can connect to a couple of
24. Why must reverse-biased diodes always be placed
ports on your microcomputer to produce some
interesting displays. The principle here is to output across inductive devices when you are driving them
a I to port B for each LED you want turned on in with a transistor?
the top row and then output a I to the DO bit of 25. a. Define the terms MOSFET and IGBT.
port A to turn on that row, Aftçr 2 ms you output b. What isa major advantage of these devices over
the pattern you want In the second row to port 13 bipolar Darlingtons when driving a high-power
and a I to bit I of port A to turn on the ',econd load with a microcomputer port line?

DIGITAL INT[RF ACING 287


•5V *5V

22??

FIGURE 9-45 8 by 8 LED matrix circuitry for problem 18.

26. a. What are the major disadvantages of mechani- code, used on many absolute-position shaft
cal relays? encoders?
b. How do solid-state relays solve these problems? b. If a Gray-code wheel has six tracks and each
track represents I binarybit. what is its angular
27. a. 1-low is electrical isolation between the control resolution?
input and the output circuitry achieved -In a
solid-state relay? 30. a. Look at the encoder disk on the Rhino arm in
b. Describe the function of the zero-crossing de- Figure 9-42. Do the waveforms in Figure 9-43
tector used in better-quality solid-state relays. represent clockwise or counterclockwise rota-
C. Why is a snubber circuit required across the tion of the motor shaft as seen from the gear
triac of a solid-state relay when you are driving end of the motor, which is what you care about?
inductive loads? b. Assume the A signal shown in Figure 9-43 Is
connected to bit DO and the B signal is con-
28. Write the algorithm and the program for an 8086 nected to bit DI of port FFF8H. Write a proce-
procedure to drive the stepper motor shown in dure which determines the direction of rotation
Figure 9-39. Assume the desired direction of rota- and passes a I back in AL for clockwise rotation
tion is passed to the procedure in AL (AL = 1 is and a 0 back In AL for counterclockwise
clockwise. AL = 0 is counterclockwise) and the rotation.
number of steps is passed to the procedure in CX.
c. DC motors, such as those on the Rhino arms.
Also assume full-step mode, as shown in Figure are rotated clockwise by passing a current
9-39b. Don't forget to delay 20 ms between step through them in one direction and rotated
commands! counterclockwise by passing a current through
29. a. Why is Gray code, rather than straight binary them in the opposite direction. Assume you

288 CHAPTER NiNE


have a motor controller that responds to a 2- • Write the algorithm and program for a
bit control word as follows: procedure to rotate a motor. The number of
holes is passed to the procedure in CX: the
direction of rotation is determined by the
00 = hold 01 = rotate clockwise value in AL. AL = 1 is clockwise; AL = 0 is
11 = hold 10 rotate counterclockwise counterclockwise.

DIGITAL INTERFACING 289


; ,. -:
.:
1i

Analog Interlacing and


Industrial Control

In order to control the machines in our electronics 5. Describe briefly the operation of flash. successive-
factory, medical instruments, or automobiles with mi- approximation, and ramp A/D converters.
crocomputers. we need to determine the values of vari- Draw circuits showing how A/D converters of vari-
6.
ables such as pressure, temperature, and flow. There ous types can be interfaced to a microcomputer.
are usually several steps in getting electrical signals
which represent the values of these variables and con- 7. Write programs to control A/D and D/A converters.
verting the electrical signals to digital forms the micro-
8. Describe how feedback is used to control variables
computer can work with. such as pressure. temperature. flow, motor speed.
The first step involves a sensor, which converts the
etc.
physical pressure. temperature. or other variable to a
proportional voltage or current. The electrical signals 9. Describe the operation of a 'time-slice" factory-
from most sensors are quite small, so they must next control system.
be amplified and perhaps filtered. ThIs Is usually done
with some type of operational-amplifier (op-amp) circuit. 10. Describe the tools arid techniques currently used
to develop a microcomputer-based product.
The final step is to convert the signal to digital form
with an analog-to .digital (A/D) converter. 11. Draw a block diagram of a digital filter and briefly
In this chapter we review some op-amp circuits com- describe its basic operation.
monly used in these steps, show the interface circuitry
for some common sensors, and discuss the operatIon
and interfacing of D/A converters. We also discuss the
REVIEW OF OPERATICNAL-AMPLIFIER
operation and Interfacing of A/D converters and show
how all of these pieces are put together in a microcomput-
CHARACTERISTICS AND CIRCUITS
er-based scale and a microcomputer based machine- Basic Operational-Amplifier Characteristics
control system. As part of these examples, we discuss
the tools and techniques used to develop microcomputer. Figure 101a i-':. e schematic symt-'ol Icr a' op
based products. Finally, we discuss how an A/D con- amp. Herc are the important points for you to remember
verter, a microcomputer, and a D/A converter can be about the basic op amp. First, the pins labeled +V
used to produce a digital filter. and - V represent the power-supply connections. The
voltages applied to these pins will usually be 1- 15 V and
- ISV. or + 12 V arid - 12 V. The op amp also has two
signal inputs. The Input labeled with a - sign is called
the inverting input, and the input labeled with a + sign
OBJECTIVES
is called the noninverting input. The + and - on
At the conclusion of this chapter, you should be able to: these inputs have nothing to do with the power supply
voltages. These signs indicate the phase relationship
I. Recognize several common op-amp circuits, de- between a signal applied to that input and the result
scribe their operation, and predict the voltages at that signal produces on the output. If, for example, the
key points in each. noninverting input is made more positive than the
2. Describe the operation and interfacing of several inverting input, the voltage on the output will move in
common sensors used to measure temperature. a positive direction. In other words, if a signal Is applied
pressure, flow, etc. to the noninverting input. the output signal will be in
phase with the input signal. If the Inverting input is
3. Describe the operation of a D/A converter and define made more positive than the noninverting input, the
D/A data-sheet parameters. such as resolution. output signal will be inverted, or 180 out of phase with
settling time, accuracy, and linearity. the input signal.
4. Draw ctrcuiis showing how to interface D/A convert- The ratio of the voltage out from an amplifier circuit
ers with any number of bits to a microcomputer. to the input voltage is called voltage gain. A. In symbols,

290

COMMON OP AMP COMPARATOR COMPARATOR WITH HYSTERESIS

OUTPUT. +V -1 V
OIJTPUT.+v-tV IF <V•,,
VI,. >__f .4,,IFV,,. >

* OUTPUT-V+1V
- OUTPUT-V*IV IFV,>V,
F '/,,. <V,.,.,. N,
-Vx
A 0 > 1OO.IO
V,,1,
(b)
NON INVERTING AMP INVERTING AMP ADDER (MIXER)
\I,. A N)
V1...
>-t VI
RI RI

Ni +V A? +V
vr rl (R2 A.. %'. - - OII
L______4 i, > , MEG n
IN PHASE
R1lIA2l)R Z,,. • Al -V
•-
0=180'
Id)
(I)
DIFFERENTIAL AMP INSTRUMENTATION AMP
V..
RI

Ri V-(V-v,t

Rt=R2
H V R3- RI

Va 1* N3, R2'%j NI
'/ N3 /'Hj

('I
A)
INTEGRATOR (RAMP GENERATOR) DI F FERENTIATOR
C
RI

V_>_
,. >—I
* -
v -v
R2 Hi L..JJ.. R2 '.Rl M.. 1J-1J
v0, VO.,

(/) ('I
2ND ORDER LOW PASS FILTER 2ND ORDER HIGH PASS FILTER

V1R3+:Vv: CIA3*V

1.00 H?
Ci - 2C2 -V -1.00
RI a? _______ C1C2
A3..lK2 R2-2RI I
R3 I Kil
1k) I/I

FIGURE 10-1 Overview of commonly used op-amdrcuits. (a) Common op


amp. (b) Comparator. Cc) Comparator with hysteresis. Cd) Noninverting amp.
Ce) Inverting amp. (I) Adder (mixer). (g) Differential amp. (h) Instrumentation
amp. (I) Integrator (ramp generator). C) ) Differentiator. (k) Second-order low-
pass filter. (I) Second-order high-pass fitter.

- 39
ANAI.00 INTERFACING AND INDUSTRIAL CN1 Rot 291
= V/V1N. The Av for an op amp is typically 100.000 voltage changes at a different input voltage when the
or more. (The number is variable with temperature and input is gntng in the positive direction than it does
from device to device.) Another useful way of saying this when the input voltage is going in the negative direction.
is that an -OP amp amplifIes the difference in voltage If you have a thermostatically controlled furnace in your
between these two inputs by 100.000 or more. Now let's house, you have seen hysteresis in action. The furnace,
see how much the output changes for a given input for example. may turn on when the room temperature
signal, and see how an op amp Is used as a comparator. drops to 65°F and then not turn off until the temperature
reaches 68° F. Hysteresis Is the difference between the
two temperatures. Without this hysteresis. the furnace
Op-Amp Circuits and Applications
would be turning on and off rapidly lithe room tempera-
OP AMPS AS COMPARATORS ture were near 68°F. Another situation where hysteresis
We said previously that an op amp amplifies the differ- saves the day is the case where you have a slowly
ence in voltage between its inputs by 100.000 or more. changing signal with noise on it. Hysteresis prevents the
noise from Causing the comparator output to oscillate as
Suppose that you power an op amp wIth +15 V and the input signal gets close to the reference voltage.
-15 V. tie the inverting input of the op amp to ground. To determine the amount of hysteresis In a circuit
and apply a signal of +0.01 V dc to the noninverting such as that in Figure I0-lc. assume V = 0 V and
input. The op amp will attempt to ampli1r this signal by = 13 V.A simple voltage-divider calculation will tell
100,000 and produce the result on its output. An input you that the noninverting input is at about 13 mV. The
signal of 0.01 V times a gain of 100,000 predicts an voltage on the inverting input of the amplifier wifi have
output voltage of 100 V. The maximum positive voltage to go more positive than this before the comparator will
the op-amp output can go to, however, is a volt or two changestates. Likewise. if you assume V is -13 V.
less than the positIve supply voltage, so this is as far as the noninverting input will be at about - 13 mV. so the
it goes. A common way of expressing this is to say the voltage on the Inverting input of the amplifier will have
op-amp output "goes into saturation" at about + 13 V. to go below this to change the state of the output. The
Now suppose that you apply . a signal of -0.01 V to hysteresis of this comparator is 26 mV.
the noninverting input. The output will now try to go
to - 100 V as fast as it can. The output, however, goes NONINVERTING AMPLIFIER OP-AMP CIRCUIT
into saturation at about - 13 V. so it stops there.
In this circut the op amp effectively compares the When operating in open-loop mode (no feedback to the
input voltage with the voltage on the inverting input Inverting input), an op amp has a very high, but
and, gives a high or low output. depending on the result unpredictable, gain. This is acceptable for use as a
of the comparison. If the input is more than a few comparator, but not for use as a predictable amplifier.
rnicrovolts above the reference voltage on the inverting Figure 10-Id shows one way negative feedback is added
input, the output will be high (+ 13 V). lithe input to an o amp to produce an amplifier with stable,
voltage is a few microvoIt more negative than the predi'tahle gain. First of all, notice that the input signal
reference voltage, the output will be low H 13 'IL An in this circuit is applied to the noninverting input, so
op amp used in this way is called a comparator. Figure the output will be in phase with the input. Second. note
10-lb shows how a comparator is usually labeled. The that a fraction of the output signal is fed back to the
reference voltage applied to the inverting input does not inverting Input. Now, here's hc .w this works.
have to be ground (0 VI. An input voltage can be To start. assume that V is 0 V. V is 0 V. and the
compared to any voltage within the input range specified voltage on the inverting Input is 0. Now, suppose that
for the particular op amp. you apply a + 0.01-V dc signal to the noninverting input.
As you will see throughout this chapter, comparators Since theO. 1-V difference between the two inputs will
have many applications. We might, for example, connect be amplifIed by 100.000, the output will head toward
a comparator to a temperature sensor on the boiler + 100 V as fast as it can. However, as the output goes
in our electron4m, factory. When the voltage from the positive, some of the output voltage will be fed back to
temperature sensor goes above the voltage on the refer- the inverting input through the resistor divider. This
ence input of the comparator, the output of the compara- feedback to the inverting Input will decrease the differ-
tor will change state and send an interrupt signal to ence in voltage between the two inputs. To make a long
the microprocessor controlling the boiler. Commonly story short, the circuit quickly reaches a predictable
available comparators such as the LM3 19 have TFL- balance point where the voltage on the inverting input.
compatible outputs which can be connected directly to V, is very, very close to the voltage on the noninverting
microcomputer ports or interrupt inputs. input. V,5 . Fora 1 .0-Vdc output, this equilibrium voltage
Figure 10- Ic shows another commonly used compara- difference might be about 10 V. If you assume that the
tor circuit. Note in this circuit that the reference signal voltagcs on the two inputs arc equal. then predicting
is applied to the noninverting input, and the input the output voltage for a given input voltage is 'simply
voltage Is applied to the inverting input. This Connection a voltage-divider problem. V 0 = V (Ri + R2VR1. if
simply inverts the output state from those in the previ- R2 = 99kClandRI = lkfl. then V 0 = V 5 x 100. For
ous circuit. Note also in Figure 10-Ic the positive- a 0.01-V input signal, the output voltage will be 100 V.
feedback resistors from the output to the noninverting The voltage gain of a circuit with feedback is called its
input. This feedback gives the comparator a characteris- closed-loop gain. The closed-loop gain. for this cir-
tic called hysteresis. Hysteresis means that the output cuit is equal to the simple resistor ratio, (Rl + R2VRI.

292 CHAPTER TEN


To see another advantage of feeding some of the output dc gain of 100.000 or store. At hIgher frequencies, the
signal back to the inverting input, let's see what, happens gain decreases until, at some frequency, the open-loop
t
when the load connected to the outpu of the op amp
changes and draws more current from the output. The
gain drops to 1. Figure 1 0-2a shows an open-loop voltage
gain versus frequency graph for a common op amp such
output voltage wilt temporarily drop because of the as a 741 The frequency at which the gain is 1 Is referred
increased load. Part of this voltage drop will he fed back to on data sheets as the unity-gain bandwidth or the
to the inverting input, increasing the difference in gain-bandwidth product. A common value for this is I
voltage between the two inputs. The increased difference MHz. The bandwidth of an amplifier circuit with negative
will cause the op amp to drive its output harder to feedback times the low-frequency closed-loop gain will
correct for the increased load. The feedback then causes be equal to this value. For example. if an op amp with
the op amp to at least partially compensate for the a gain-bandwidth product of 1 MHz t used to build an
increased load on its output. amplifier circuIt with a closed-loop gain of 100, the
Feedback which causes an amplifier to oppose a bandwidth of the circuit, f. will be about I MHz/10Oor
change on its output is called negative feedback, Be- 10 k}1z. as shown in Figure I0-2b.
cause of the negative feedback, the op amp will work The point here is that the gain-bandwidth product of
day and night to keep its output 8tabiluzed and its two the op amp limits the maximum frequency that an
inputs at nearly the same voltage! This is probably the amplifier circuit can amplify.
moat important point you need to know to analyze or
troubleshoot an Op-amp circuit with negative feedback. OP-AMP ADDER CIRCUIT
Draw a box around this point In your mind so you don't Figure 10-if shows a commonly used variation of the
forget it, inverting amplifier described in the previous section.
The noninverting circuit we have Just discussed Is This circuit adds together or mixes two or more input
used mostly as a buffer because it has a very high input' signals. Here's how it works.
impedance, Z,. This means that it will not, load dow-i, Remember from the previous discisslou that in an
a sensor or some other device you onnect to Its input. inverting circuit, the op amp holds the inverting i9put
If it uses a bipolar-transistor input op amp, the circuit at 0 V or virtual ground. The current through each ci
in Figure 10-Id will have an input impedance greater the input resistors will be the same as if it were connected
than 100 Mfl. If a FET input op amp such as the
'about 1ot2
National LF356 is used, the input impedance will be
ft
INVERTING AMPLIFIER OP-AMP CIRCUIT
Figure lO-le shows a somewhat more versatile amplifier 10.0001
SLOPE • -6 dO/OCTAVE OR
dO/DECADE
circuit using negative feedback. Note that in this circuit.
the noninverting input is tied to ground with a resistor.
z
i3O00 E-
and the signal you want to amplify is applied to the 100 I-
inverting Input through a resistor. Since the signal is UNITY GAIN
applied to the inverting input, the output signal will be 'OF-II /rRE,ENCv
180° out of phase with the input signal. For this circuit, 1 11111 I
resistor RI suppltes the negative feedback which keeps 1 10 100 I 10 100
HZ KHZ FREQUEI.4CY
the two inputs at nearly the same voltage. Since the MHZ
noninverting input is tied to ground, the op amp will
sink or source whatever current is needed to hold the
inverting input also at zero volts. Because the op amp
fi
holds the inverting input at zero volts, this node is
100,000
referred to as a virtual ground.
The voltage gain of this circuit is also determined by
the ratio of two resistors. The A 1 for this circuit at low
io - OPEN LOOP

frequencies is equal to -RL'Rl. You can derive this for 1,000-


yourself by just thinking of the two resistors as a voltage 0 I SLOPE°
1 / -20 dR/DECADE
divider with V, 5 at one end. 0 V in the middle, and V, 70.7 ']
"
on the other end, If V 1,, Is positive, then V must be lot-
negative because current cannot flow from positive to
ground to positive again. The minus sign in the gain it I I - I
I 10 100 1 10 100
expression is another way of indicating that the output Hz KHZ MHZ
is inverted from the input. The input impedance Z,, of BANDWIDTH
this circuit is approximately Ri because the amplifier it)
end of this resistor is held at 0 V by the op amp.
One additional characteristic of op-amp circuits that FIGURE 10-2 (a) Open-loop gain versus frequency
we need to refresh in your mind before going on to other response of 741 op amp. (b) Gain versus frequency
op-amp circuits is gain-bandwidth product. As we response of 741 op-amp circuit with closed-loop gain of
indicated previously, an op amp may have an open-loop 100.

ANALOG INTERFACING AND INDUSTRIAL CONTROl. . 293


to ground. Input voltage V produces a current through constant current V,,,/R1. Basic physics tells you that the
RI to this point, and input voltage V 2 causes a current voltage across a capacitor being charged by a constant
through R2 to this point. The two currents add together current is a linear ramp. Note that because of the
at the virtual ground. In this circuit the virtual ground inverting amplifier connection, a positive input voltage
is often called the summing point. The op amp pulls the will cause the output to ramp negative. Also note that
sum of the two currents through resistor RI to hold the some provision must be made to prevent the amplifier
inverting input at 0 V. The left end of Rf is at 0 V. so output from ramping into saturation.
the output voltage is the voltage across RI. This is equal The circuit is called an Integrator because it produces
to the sum of the currents times the value of Rf. or an output voltage proportional to the integral, or "sum."
V/Rl + V2/R2 x RI. A circuit such as this is used to of the current produced by an input voltage over a period
'mix" audio signals and to sum blnary .weighted cur- of time. The waveforms in Figure 10-li show the circuit
rents in a D/A converter. Although the Circuit in Figure response for a pulse-input signal.
10-if shows only two inputs, an adder can have any
number of inputs. AN OP-AMP DIFFERENTIATOR CIRCUIT
Figure 10-li shows an op-amp circuit which produces
SIMPLE DIFFERENTIAL-INPUT AMPLIFIER CIRCUIT an output signal proportional to the rate of change of
As we show later, many sensors have two output signal the input signal. With the input voltage to this circuit
lines with a dc voltage of several volts on each signal at 0 or some other steady dc voltage, the output will be
line. The dc voltage present on both signal leads is at 0. If a new voltage is applied to the input, the voltage
referred to as a common-mode voltage. The actual signal across the capacitor cannot change instantly, so the
you need to amplify from these sensors is a difference inverting input will be pulled away from 0 V. This will
in voltage of a few millivolts between the two signal lines. cause the op amp to drive its output in a direction to
If you try to use a standard inverting or noninverting charge the capacitor and pull the Inverting input back
amplifier Circuit to do this, the large dc voltage will be to zero. The waveforms in Figure 10-1,1 show the circuit
amplified along with the small difference voltage you response for a pulse-input signal. The time required for
need to amplify. Figure 10-19 shows a simple circuit the output to return to zero is determined by the time
which, for the most part, solves thi problem without constant of RI and C.
ising coupling capacitors to block the dc. The analysis
of this circuit is beyond the space we have here, but OP-AMP ACTIVE FILTERS
basically the resistors on the noninverting input hold In many control applications, we need to filter Out
this input at a voltage near the common-mode dc voltage. unwanted low-frequency or high-frequency noise from
The amplifier holds the inverting input at the same the signals read in from sensors. This could be done
voltage. If the resistors are matched carefully, the result with simple RC filters, but active filters using op amps
is that only the difference in voltage between V 2 and V1 give much better control over filter characteristics. There
will be amplified. The output signal will consist of only are many different filter configurations using op amps.
the amplified difference in voltage between the input The main points we want to refresh here are the mean-
signals. We say that the common-mode signal has been ings of the terms low-pass filter, high-pass filter, and
rejected. bandpass filter and how you identify the type when you
find one in a circuit you are analyzing.
AN INSTRUMENTATION AMPLIFIER CIRCUIT A low-pass filter amplifies or passes through low
frequencies, but at some frequency determined by circuit
Figure l0-ih shows an op .amp circuit used in applica-
values, the output of the filter starts to decrease. The
tions that need a greater rejection of the common-mode
frequency at which the output is down to 0.707 of the
signal than is provided by the simple differential circuit
in Figure 10 . 1g. The first two op amps in this circuit low-frequency value is called the critical frequency or
buffer the differential signals and give some amplifica-
breakpoint. Figure iO-3a shows a graph of gain versus
frequency for a low-pass filter with the critical frequency.
tion. The output op amp removes the common-mode
voltage and provides further amplification. Another way Ic- labeled. Note that above the critical frequency the
gain drops off rapidly. For a first-order filter such as a
of describing the function of the output op amp is to
single R and C, the gain decreases by a factor of 10 for
say that it converts the signal from a differential signal to
each increase of 10 times infrequency (-20 dB/decade).
a single-ended signal. Instrumentation amplifier Circuits
For a second-order filter, the gain decreases by a factor
such as this are available in single packages.
of 100 for each ficrease of 10 times in frequency.
Figure 10-1k shows a common op-amp circuit for a
AN OP-AMP INTEGRATOR CIRCUIT
second-order low-pass filter. The way you recognize this
Figure 10-li shows art op-amp circuit that can be used as a low-pass filter is to look for a dc path from the input
to produce linear voltage ramps. A dc voltage applied to to the noninverting input of the amplifier. If the dc path
the input of this circuit will cause a constant Current of is present. as it is in Figure 10-1k. you know that the
V5/R ito flow into the virtual-ground point. This current amplifier can amplify dc and low frequencies. Therefore.
flows onto one plate of the capacitor. In ordet to hold it is a low-pass filter with a response such as that shown
the inverting input at ground, the op-amp output must in Figure I0-3a.
pull the same current from the other plate of the capaci- For contrast, look at the circuit for the second-order
tor. The capacitor then is getting charged by the high-pass filter in Figure 10-1k. Note that in this circuit,

294 CHAPTER TEN


down to 0.5 as it would be if we cascaded two simple
1000
RC circuits.
10,0001—

100
N OP AMP
OPEN LOOP
For the high-pass filter, the gain for the flat section of
the response curve is also 1. Assuming that the two
capacitors are equal and the value of R2 is twice the
value of Ri. the critical frequency is determined by the
10 formula shown next to Figure 10-lI. Again. R3 Is for
0 damping.
A low-pass filter can be put in series with a high-pass
0.1 ORDER ifiter to produce a bandpass filter which lets through a
LOW PASS
.01 F I LT ER desired range of frequencies. There are also many differ-
ent single-amplifier circuits which will pass or reject a
band of frequencies.
.0001 I Now that we have refreshed your memory of basic op-
1 10 100 1 10 100 1
HZ KHZ MHZ amp Circuits, we will next discuss some of the different
types of sensors you can use to produce electrical signals
ic
proportional to the values of temperatures. pressures.
(a) position, etc.

100.000
SENSORS AND TRANSDUCERS
10.000
OP AMP It would take a book many times the size of this one to
1,000 LOOP describe the operation and applications of all the differ-
100 ent types of available sensors and transducers. What we
10 want to do here is introduce you to a few of these nd
0 show how they can be used to get data for microcomput-
er-based machines in, for example, our electronics
0.1- factory.
.01 /"1-..2NDORDER
.001-
/ I HIGHPASSFILTER
Light Sensors
I
000• I I One of the simplest light sensors is a light-dependent
1 10 100 I 10 100 1
HZ KHZ MHZ resiStor such as the Clairex CL905 shown in Figure
lO-4a. A glass window allows light to fall on a zigzag
fc

(b)
FIGURE 10-3 Cain versus frequency response for
second-order low-pass and high-pass filters. (a) Low-
pass. (b) High-pass.

(a)
the dc component of an input signal cannot reach the
noninverting input, because of the two capacitors In
series with that input. Therefore, this circuit will not
amplify dc and low-frequency signals. Figure 1O-3b
shows the graph of gain versus frequency for a high-
pass filter such as this. Note that the gain-bandwidth 100 K (At LAY
product of the op amp limits the high-frequency re-
sponse of the circuit.
For the iow-pass circuit in Figure 10-1k, the gain for
the flat part of the response curve is 1. or unity, because
__J_______
the output is fed back directly to the inverting input. At P HO TO A E SISTO A
the critical frequency, f,. the gain will be 0.707. and
above this frequency the gain will drop off. The critical
frequency for the cIrcuit is determined by the equation
next to the circuit. The equation assumes that RI and (b)
R2 are equal and that the value of Cl is twice the value
of C2. R3 is simply a damping resistor. The positive FIGURE 10-4 (a) Cadmium sulfide photocell. (Clawex
feedback supplied by C I is the reason the gain is only E'ectronics) (b) Light-controller relay Circuit using a
down to 0.707 at the critical frequency, rather than photocell.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 295


patteiri of cadniiu&u ulfid or cadmium sclenidc whose cell. Common solar cells are simply large, viy havlIy
resistance depends on the amount of light present. The doped silicon PN Junctions. Light shining on the solar
resistance of the CL905 varies from about 15 MIl when cell causes a reverse current to flow, just as In the
in the dark to about 15 kfl when In a bright light. photodiode. Because of the large area and the hea,'y
Photoresistors such as this do not have a very fast doping in the solar cell, however, the current produceu
response time and are not stable with temperature, but is milliamperes rather than microamperes. The cell
they are Inexpensive, durabie. and sensitive. For these functions as a light-powered battery. Solar Cells can be
reasons, they are usually used in applications where the connected in a series-parallel array to produce a solar
light measurement need not be precise. The devices power supply.
placed on top of streetlights to turn them on when Light meters in cameras, photographic enlargers, and
It gets dark, for example, contain a photoresistor. a our printed-circuit-board-making machine use solar
transistor driver, and a mechanical relay, as shown in cells. The current from the solar cell is a linear function
Figure 10-4b. As it gets dark, the resistance of the
of the amount of light railing on the cell. A circuIt such
photoresistor goes up. This Increases the voltage on the as the one In Figure 10-5 can be'used to convert the
base of the transistor until, at some point, it turns on. output cur-rent to a proportional voltage. Because of the
This turns on the ti-ansistor driving the relay, which In larger output Current, the value of R1 is decreased to a
turn switches on the lamp.
much smaller value, depending on the output current
Another device used to sense the amount of light of the cell. The noninvertlng Input of the amplifier is
present is a photodiode. If light is allowed to fall on the connected to ground because reverse biasing iS not
junction of a specially constructed silicon diode, the needed with solar cells. The frequency response to light
reverse leakage current of the diode increases linearly (spectral response) of solar cells has been tailored to
as the amount of light falling on it Increases. A circuit match the output of the sun. Therefore, they are ideal
such as that shown In Figure 10-5 can be used to convert in photographic applications where we want a signal
this small leakage current to a proportional voltage. Note proportional to the total light from the sun.
that in this circuit a negative reference voltage is applied
to the noninvertlng input of the amplifier. The op amp
will then poduce this same voltage on its inverting
input, reverse-biasing the photodiode. The op amp will
Temperature Sensors
pull the photodiode leakage Current through Rf to pro- Again, there are many types of temperature sensors.
duce a proportional voltage on the output of the ampli- The four types we discuss in some detail here are
fier. For a typical photodiode such as the HP 5082-4203 semicotiductor devices, thermocouples, RTDs, and
shown, the reverse leakage current varies from near 0 thermistors.
pA to about 100 pA, so with the l00-kfl Rf. an Output
voltage of about 0 to 10 V will be produced. The circuit SEMICONDUCTOR TEMPERATURE SENSORS
will work without any reverse bias on the diode, but
with the reverse bias, the diode responds faster to The two main types of semiconductor temperature sen-
changes In light. An LM356 FET input amplifier is used sors are temperature-sensitive voltage sources and tem-
here because it does not require an Input bias current. perature-sensitive current sources. An example of the
A photodiode circuit such as this might be used to first type Is the National LM35, which we show the
determine the amount of smoke being emitted from a circuit connections for in FIgure t0-6a. •The voltage
smokestack, To do this, a gallium arsenide infrared output from this circuit increases by 10 mY for each
LED is put on one side of the smokestack, and the degree Celsius that its temperature is increased. If the
photodetector cireit is put on the other. Since smoke output is connected to a negative reference voltage. V5.
absorbs light, the aount of light arriving at the photo- as shown, the sensor will give a meaningful output for
detector is a measurç of the amount of smoke present. a temperature range of —55 to + 150° C. The output Is
An infrared LED is uskd here because the photodiode is adjusted to 0 V for 0° C. The output voltage can be
most sensitive to Iigl wavelengths in the infrared amplified to give the voltage range you need for a
region. particular application. In a later section of this chapter.
Still another useful light-sensitive device is a solar we show another circuit using the LM35 temperature
sensor. The accuracy of this device Is about 1°C.
Another common semiconductor temperature sensor
Is a temperature-dependent current source, such as the
RI 100 t(il Analog Devices AD590. The ADS9O produces a current
of I pAJ°K. Figure I0-6b shows a circuit which converts
this current to a proportional voltage. In this Circuit
th'e current from the sensor. I. is passed through an
approximately I -ku resistor to ground. This produces a
PHOTODIODE voltage which changes by ImVPK. The AD580 in the
HP5082-4203
circuit is a precision voltage reference used to produce
2V12v a referericevoltageof 273.2 mV With thisvoItageapplied
to the inverting input of the amplifier, the amplifier
FIGURE 10-5 Photodiode circuit lo measure light
output will be at zero volts for 0° C. The advantage of a
intensity.
current-source sensor is that voltage drops in long
296 CHAPTER T[N

OFFSET
vs REFERENCE

MEASURED TEMP AD58OLQ


P215K
OTO 10OC Ir TRIM 1000C
4-X) V R2
9.09 K 4.Ay%Aq_1

r±1 our +1500 ItSV AT 1500C


+250 oW AT 250C
—550 roV AT —550C
I'I
P1
2000
TRIM

RG
P5

I 1KO
R3
Lt v
REMOTE
TEMPERATURE-
TO-CURRENT
R- TRANSDUCER,
1 '.A/K 1 KO 01% INSTRUMENTATION
LOW TCR AMPLIFIER,
A0590 IC IS METERING GAIN OF 10.
AVAILABLE IN RESISTOR, 0.00 V TO 1.00 FS
PROBE AS AC2626J lroVlpA lrnV/K ID ntV/0C

I) (b)

FIGURE 10-6 Semiconductor temperature-sensor circuits. (a) LM35


temperature-dependent voltage source. (b) AD590 temperature-dependent
current source. (Analog Devices Incorporated) -

connecting wires do not have any effect on the output thermocouples is changing. The problem is that it is
value. If the gain and offset are carefully adjusted, the Impossible to tell which thermocouple caused a change
accuracy of the circuit in Figure l0-6b is ± 10 C using in output voltage. One cure for this is to put the reference
an AD59OK part. junction in an ice bath or a small oven to hold it at a
constant temperature. This solution is us'ually inconve-
THERMOCOUPLES nient, so instead a circuit such as that in Figure 10-7
is used to compensate electronically for changes in the
Whenever two different metals are put in contact, a small
temperature of the reference junction.
voltage is produced between them. The voltage developed
As we discussed In a previous section, the AD590
depends on the type of metals used and the temperature.
shown here produces a current proportional to its
Depending on the metals, the developed voltage in-
temperature. The AD590 Is attached to the reference
creases between 7 and 75 p.V for each degree Celsius
thermocouple so that they are both at the same tempera-
increase in temperature. Different combinations of met-
ture. The current frorp the AD590, when passed through
als are useful for measuring different temperature
the resistor network, produces a voltage which compen-
ranges. A thermocouple junction made of iron and
constantan, commonly called a type J thermocouple.
has a useful temperature range of about - 184 to + 7600
.
sates for changes in the reference thermocouple with
temperature . The signal to the amplifier then is proper-
C. A junction of platinum and an alloy of platinum and
13 percent rhodium has a useful range of 0 to about 7.5V
16000 C. Thermocouples can be made small, rugged,
and stable; however, they have three major problems
which must be overcome.
REPEAEE,CE
JUNCTION
15C < T4<35'C,,
I
,_1!1 0

The first of these is the fact that the output is very OUTPUT
AMPLIFIER
small and must be amplified a great deal to bring it up
MEASURING
into range where it can, for example, drive an A/D JUNCTION
converter.
Second. as shown in Figure 10-7. a reference junction
ii___
made of the same metals must be connected in series 523flI25V
with thejunction being used to make the measurement, I.+P -25V I 866Ki)
Note that the reference junction is connected in the 1TE j 50M1i OVT
reverse direction from the measuring junction. This is I I VALUE I
done so that the output connecting wires are both I I 52311 I
I I 4120 I
constantan. The thermocouples formed by connecting £ I 61412 I NOMiNAL
T 402 I VALUE
these wires to the copper wires going to the amplifier I S. I 5760 91350
will then cancel out. T.he input voltage to the amplifier
will be the difference between the voltages across the FIGURE 10-7 Circuit showing amplification and cold-
two thermocouples. II we simply amplify this voltage. function compensation for thermocouple. (Analog
however, there is a problem if the temperature of both Devices Incorporated)

ANALOG INTERFACING AND INDUSTRIAL CONTROL 297


tional only to changes in the sensor thermocouple. the resistance of the RTD. The resistance of an RTD
Canceling out the effects of ambient temperature varia- increases with an increase in temperature.
tions on the reference Junction is referred to as cold- Thermistors consist of semiconductor material whose
junction compensation. The table in Figure 10-7 shows resistance decreases nonlinearly with temperatjre. De-
the values of R which will provide cold-junction compen- vices with 25° C resistance of tens of ohms to millions
sation for common types of thermocouples. An Instru- of ohms are available for different applications. Thermis-
mentation amplifier such as that In Figure lO-lh is tors are relatively inexpensive, have very fast response
usually used for this application. times, and are useful in applications where precise
The third problem with thermocouples is that their measurement is not required. A circuit similar to that
output voltages do not change linearly with temperature. in Figure 10-8 can be used to produce a voltage propor-
This can be corrected with analog circuitry which tional to the resistance of the thermistor.
changes the gain of an amplifier according to the value
of the signal However, when a thermocouple is used
with a microcomputer-based instrument, the correction
can be easily done using a lookup table in ROM. An Force and Pressure Transducers
A/D Converter converts the voltage from the thermocou- To convert force or pressure (force/area) to a proportional
pie to a digital value. The digital value is then used as electrical signal, the most common methods use strain
a pointer to a ROM location which contains the correct gages or linear variable differential transformers
temperature for that reading. (LVDTs). Both of these methods Involve moving some-
thing. This why we refer to them as transducers rather
RTDS AND THERMISTORS than as sensors. Heres how strain gages work.
Resistance temperature detectors (RTD5) and thermal
sensitive resistors (thermistois) are two other commonly STRAIN GAGES AND LOAD CELLS
used types of temperature sensors. Both of these types A strain gage Is a small resistor whose value changes
are essentially resistors which change value with a when its length is changed. It may be made of thin wire.
change in temperature. RTDs consist of a wire or a thin thin foil, or semiconductor material. Figure 10-9a shows
film of platinum or a nickel wire. The response of a simple setup for measuring force or weight with Strain
RTDs is nonlinear, but they have excellent stability gages. One end of a piece of spring steel is attached to
and repeatability. Therefore, they are often used in a fixed surface, A strain gage is glued on the top of the
applications >vhere very precise temperature measure- flexible bar. The force or weight to be measured is
ment Is needed. RTDs are useful for measures in the applied to the unattached end of the bar. As the applied
range of —250 to +850° C. A circuit such as that In force bends the bar, the strain gage is stretched. Increas-
Figure 10-8 can be used to convert the change in ing its resistance. Since the amount that the bar is bent
resistance of the RTD to a proportional voltage. 0p amp is directly proportional to the aDplted force, the change
Al in this circuit produces a precise reference voltage in resistance will be proportional to the applied force, If
of —6.25 V. This voltage produces a precise current at a current Is passed through the strain gage, then
the inverting input of A2. °p amp A2 pulls this current the change in voltage across the strain gage will be
through the RTD to produce a voltage proportional to proportional to the applied force.

PLATINUM
RTD
loon to 2000

25 K -625 V SPAN
*15 V 500 *15V
...' 2200 -

A2
4.7 KO 1.8 V
FOR 0 TO
266° C
1K
REF. -1.8 V
OFFSET
1.5 KiZ

FIGURE 10-8 100 . 11 RTD connected to perform temperature measurements in


the range 0°C to 266°C. (Analog Devices Incorporated)

298 CHAPTER TEN


Unfortunately, the resistance of the strain-gage ele- beam structure, as shown in Figure iO-9a. the result
ment also changes with temperature. To compensate for is called a food cell and Is used to measure weight.
this problem, two strain-gage elements mounted at right FIgure 10-10 shows a 10-lb load cell that might be
angles, as shown in Figure IO-9b. are often used. Both used in a microprocessor-controUed dlicatessen scale or
of the elements will change resistance with temperature, postal scale, Larger versionscan be used to weigh barrels
but only element A will change resistance appreciably being filled or even trLcks.
with anplied force. When these two elements are con- If a strain-gage bridge is mounted on a movable
nected in a balanced-bridge configuration, as shown in diaphragm in a threaded housing, the output of the
Figure lO:9c. any change in the resistance of the ele- bridge will be proportional to the pressure applied to the
ments due to temperature will have no effect on the diaphragm. If a vacuum is present on one side of the
differential output of the bridge. However, as force is diaphragm, then the value read out will be a measure
applied, the resistance of the element under strain will of the absolute pressure, If one side of the diaphragm is
change and produce a small differential output voltage. open, then the output will be a measure of the pressure
The full-scale differential output voltage is typically 2 or relative to atmospheric pressure. If the two sides of the
3 mV for each volt of excitation voltage applied to the diaphragm are connected to two different pressure
top of the bridge. For example, if 10 V is applied to the sources, then the output will be a measure of the differen-
top of the bridge, the full-lead output voltage will be 20 tial pressure between the two sides. Figure 10-Il shows
or 30 mV. This small signal can be amplified with a a Sensyrn LXI 8O4GBZ pressure transducer which meas-
differential amplifier or an instrumentation amplifier. ures pressures in the range of 0 to 15 lb/in. A transducer
Strain-gage bridges are used in many different forms such as this might be used to measure blood pressure
to measure many different types of force and pressure. In a microcomputer-based medical instrument.
If the strain-gage bridge is connected to a bendable
LINEAR VARIABLE DIFFERENTIAL TRANSFORMERS
An LVDT is another type of transducer often used to
STRAIN GAGES SPRING STEEL STRIP
measure force, pressure, or position. Figure 10-12 shows
the basic structureof an LVE)T. It consists of three coils
of Wire wound on the same form and a movable Iron
'LJ core. An ac excitation signal of perhaps 20 kHz is applied
to the primaly. The secondaries are conneted such that
the voltage, induced in one opposes the voltage induced
WEIGHT in the other, If the core is centered, then the induced
voltages are equal arid cancel each other, so there is no
Ia) net output voltage. If the coil is moved off center,
coupling to one secondary coil will be stronger, so that
STRAIN GAGES SPRING STEEL STRIP the coil will produce a greater output voltage. The result
will he a net output voltage. The phase relationship
oeL..... ui' output signal and the input signal is an
indication of which direction the core moved from the
center position. The amplitude of the output signal is
linearly proportional to how far the core moves from the
center position.

IbI

FIGURE 10-9 Strain gage' used to measure force.


(a) Side view. fbi lop view )expanded). FIGURE 10-10 Photograph of load-cell transducer used
IC) Circuit connections. to measure weight. ITransducers Incorporated I

- 40 . ANALOG INTERFACING AND INDUSTRIAL CONTROL 299


or gas. An optical encoder can be attached to the shalt
of the paddle wheel to produce digital information as to
how fast the paddle wheel is turning.
A second common meth&d of measuring flow Is with
a differential pressure transducer, as shown in Figure
10-13b. A wire mesh or screen is put in the pipe to
create some resistance. Flow through this resistance
produces a difference in pressure between the two sides
of the screen. The pressure transducer gives an output
proportional to the difference in pressure between the
two sides of the resistance. In the same way that the
voltage across an electrical resistor is proportional to
the flow of current through the resistor, the output of
the pressure transducer is proportional to the flow of a
liquid or gas through the pipe.

Other Sensors
As we mentioned previously, the number of different
types of sensors Is very large. In addition to the types
we have discussed, there are sensors to measure pH,
FIGURE 10-11 LX18O4GBL pressure
concentration of various gases, thickness of materials,
transducer. (Sensym, Incorporated)
presence of an object (proximity), and just about any-
thing else you might want to measure. Often you can
use commonly available transducers in creative ways
• PRIMARY SECONDARIES to solve a particular application problem you have.
1+ Suppose, for example, that you need to accurately deter-
mine the level of a liquid in a large tank. To do this, you
AC - could install a pressure transducer at the bottom of the
EXCITATION tank. The pressure in a liquid is proportional to the
SIGNAL hed of the liquid in the tank, so you can easily convert
20KHZ
a pressure reading to the desired liquid height. ']he
point here Is to check out what is available and then be
1 creative.
MOVEABLE IRON CORE

FIGURE 10-12 Linear variable differential transformer


4- to 20-mA Current Loops
(LVDT) structure. In the preceding discussions, we showed how op amps
can be used to convert output signals to voltages in a
range thai can be applied to the input of an AID
An LVDT can be used directly in this form to measure
displacement or position. If you add'a spring so that a
force is required to move the core, then the voltage cu'
of the LVDT will be proportional to the force applied tc FLO" -
the core. In this form, the LVDT can be used in a load
cell for an electronic scale. Likewise, if a spring is added
and the core of the LVDT is attached to a diaphragm in
a threaded housing. the output from the LVDT will be cat
proportional to the pressure exerted on the diaphragm.
We do not have the space here to show the ac-interface
OIFFELENTIAL
circuitry required for an LVDT. PRESSURE
TRAr' SDUCER

Flow Sensors
If we are going to control the flow rate of some material FLOW-.
in our electronics factory, we need o be able to measure
it. Depending on the material, flow rate, and tempera- RESISTANCE
ture, we use different methods. 0)
Qn. method used is to put a paddle whcel in the flow.
aown in Figure lO l3a. The rate at which the paddle FIGURE 10-13 Flow sensors. (a) Paddle wheel,
iei turns Is proportional to tJ' rate of flow of a liquid b DI tferen hal pres,u re.

CHAPTE R Tt'J

converter. In many industrial applications where the order to pull this current through the feedback resistor,
sensor Is a long distance from the A/D converter, how- the op amp must put a voltage of 0.05 mA x 10 ku or
ever, the signals from the sensors or transducers are 0.5 Von its output. If you also close switch Dl. it will
converted to currents instead of voltages. Sending a send another 0.1 mA into the summing point. In order
signal as a current has the advantages that the signal to pull the sum of the currents through the feedback
amplitude Is not affected by resistance, induced-voltage resistor, the op amp has to output a voltage of 0.15
noise, or voltage drops in a long connecting line. A mA X 10 kfl or 1.5 V.
common range of currents used to represent analog The point here is that the binary-weighted resistors
signals in industrial environments Is 4 to 20 mA. A produce binary-weighted currents which are summed
current of 4 mA represents a zero output, and a Current by the op amp to produce a proportional output voltage.
of 20 mA represents the full-scale value. The reason the The binary word applied to the switches produces a
current range is offset from zero is so that a current of proportional output voltage. Technically the output volt-
zero is left to represent an open circuit. At the receiving age is "digital" because it can only have certain fixed
end of the line, a resistor or a simple op-amp Circuit is values. Just as the display on a digital voltmeter can.
used to Convert the current to a proportional voltage However, the output simulates an analog signal, so we
which can be applied to the input of the A/D converter. refer to it as analog. Switch D3 in Figure 10-14 repre-
sentS the most significant bit because closIng it produces
the largest current. Note that since V l,.EF is negative, the
output will go positive as switches are closed.
0/A CONVERTER OPERATION, As you see here, the heart of a D/A converter is a
INTERFACING, AND APPI.ICATIONS set of binary-weighted current sources which can be
In the previous sections of this chapter we have dis- switched on or off according to a binary word applied to
cussed how we use sensors to get electrical signals its inputs. Since these current sources are usually inside
proportional to pressure, temperature. etc. and how we an IC. we don't need to discuss the different ways the
use op amps to amplify and filter these electrical signals. binary-weighted currents can be produced. The op-amp
The next logical step would be to show you how to use circuit in Figure 10-14 converts the sum of the currents
an A/D converter to get these signals into digital form to a proportional voltage.
that a microcomputer can work with. However, since
D/A CHARACTERISTICS AND SPECIFICATIONS
D/A converters are simpler and since several types of
A/D converters have D/As as part of their circuitry, we Figure 10-15 shows the circuit for an inexpensive IC
will discuss DIAs first. D/A converter with an op-amp circuit as a current-to-

D/A Converter Operation and Specifications V,,, 2.0 V dc


P14 P15 1.0kg
OPERATION P0 5.0 kit
a
The purpose of a digital-to-analog converter is to convert 41
P14 Vi,,
a binary word to a proportional current or voltage. To MSB A1O---"
see how this is done, let's look at the simple 4-input A2o---
11151 .A,//1
adder circuit in Figure i014. A3o—
MC1508L8I P15
Since the noninverting input of the op amp is A4 MC14O8L I
grounded. the op amp will work day and night to hold SERIES III
A5
the inverting input also at 0 V. Remember that the 110
A6 0—
inverting input in this circuit is referred to as the A7
summing point. When one of the switches is closed, a II? 2)
LSB AO-
current will flow from 5 V (VREr) through that resistor to (6)
the summing point. The op amp will pull the current on 131
through the feedback resistor to produce a proportional MCi 741SG
OR EOUIV.
output voltage. If you close switch DO. for example, a
current of 0.05 mA will flow into the summing point. In 15 pF
v,
ThorIicI

v 5 V
lOkO v,, fA1A2 +A4++M+A7^
V0 (A0) 1 2 4 8 16 32 64 128 256

1 k 0 r-- ADJUST Vs,,, P14 OR P0 SO THAT V0 WITH ALL DIGITAL


INPUTS AT HIGH LEVEL IS EQUAL TO 9961 V
5Ok06

I { + +
02 R3 25k0 I 6
1., V f
255
-b y -9961V
03 °2kf
o—,AA
R1
L -
FIGURE 10-15 Molorola MC1408 S-bit D/A with current-
FiGURE 10-14 Simple 4-bit DIA converter. to-voltage converter.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 301


voltage converter, We will use this Circuit for our discus- occur to you at thIs point is. What good IS It to have a
sion of D/A characteristics. 10-bit converter if the linearity Is only equivalent to that
The first characteristic of a D/A converter to considet of an 8- orO bit converter2 The answer to this question
is resolution. This is determined by the number of bits is that for many applications, the resolution given by a
in the input binary word. A converter with S binary 10-bit converter is needed for small output signals.
inputs, such as the one in Figure 10-15, has 2 or 256 but it doesn't matter if the output value is somewhat
possible output levels, so its resolution is I part in 256. nonlinear for large signals. The price you pay for a U/A
As another example, a 12-bit converter has a resolution converter is proportional not only to its resolution, but
of I part in 22 or 4096. Resolution is sometimes also to its linearity specification.
expressed as a percentage. The resolution of an 8-bit Still another U/A specification to look for is settling
converter expressed as a percentage is 11/256) x 100 time. When you change the binary word applied to the
percent or about 0.39 percent. input of a converter, the output will change to the
The next D/A characteristic to determine is thefull- appropriate new value. The output, however, may over-
scale output voltage. For the converter in Figure 10-15, shoot the Correct value and 'ring" for a while before
the current for all the switches is supplied by V,.,5r finally settling down to the correct value. The tlme'the
through R14. The current output from pin 4 of the U/A output takes to get within ± LSB of the final value is
is pulled through R0 to produce the output voltage. The called settling time. As an example, the National
formula for the output voltage is shown under the circuit DACIO2O 10-bit converter has a typical settling time o
in Figure 10-15. In the equation the term Al, for 500 ns for a full-scale change on the output. This
example, represents the condition of the switch for that specification is important because if a converter is
bit. If a switch is closed, allowing a Current to flow, put operated at too high a frequency, it may not have time
a 1 in that bit. If a switch Is open, put a 0 in that bit. to settle to one value before It is switched to the next.
As we also show in Figure 10-15, if all the switches are
closed, the output will be 10 V x (255/256) or 9.961 V.
D/A Applications and Interfacing
Even though the output voltage can never actually get to Microcomputers
to 10 V. this is referred to as a JO-V output converter,
The maximum output voltage of a converter will always U/A converters have many applications besides those
have a value I least significant bit less than the named where theyare used with a microcomputer, In a compact-
value. As another example of this, suppose that you disk audio player, for example. a 14- or 16-bit U/A
have a 12-bit, 10-V converter. The value of 1 LSB will converter is used to convert the binary data read off the
be (10 V)/4096 or 2.44 mV. The highest voltage out of disk by a laser to an analog audio signal. Most speech-
this converter when it is properly adjusted will then be synthesizer ICs contain a U/A converter to convert stored
(10.0000 - 0.0024) V or 9.9976 V. binary data for words into analog audio signals. Here.
Several different binary codes, such as straight binary, however, we are primarily interested in the use of a
BCD. and offset binary, are commonly us&1 as inputs U/A converter with a microcomputer,
to U/A converters, We will show examples of these codes The inputs of the U/A circuit (Al through A8) in
In a later discussion of A/D converters. Figure 10-15 can be connected directly to a microcom-
The accuracy specification for a U/A converter Is a puter output port. As part of a program, you can produce
comparison between the actual output and the expected any desired voltage on the output of the U/A, Here are
output. It Is specified as a percentage of.the.fuII-scale some ideas as to what you might use this circuit for.
output voltage or current. If a converter has a full-scale As a first example, suppose that you want to build a
output of 10 V and ±0.2 percent accuracy, then the microcomputer-controlled tester which determines the
maximum error for any output will be 0.002 x 10.00 V. effect of power supply voltage on the output voltage of
or 20 mV. Ideally the maximum error for a U/A converter some integrated-circuit amplifiers. If you Connect the
should be no more than ±1 the value of the LSB. output of the U/A converter to the reference input of a
Another important specification for a U/A converter is programmable power supply or simply add the high-
linearity. Linearity isa measure of how much the output current buffer circuit shown in Figure 10-16 to the
ramp deviates from.a straight line as the converter Is output of the U/A, you have a power supply which you
stepped from no switches on to all switches on. Ideally, can vary under program control. To determine the
the devtatlon of the output from a straight line as the output voltage of the IC under test as you vary its supply
converter is stepped from no switches on to all switches voltage, connect the input of an A/D converter to the IC
on. Ideally, the deviation of the output from a straight output, and connect the output of the A'U converter to
line should be no greater than ±) the value of the an input port of your microcomputer. You can then read
LSB to maintain overall accuracy. However, many U/A in the value of the output voltage on the IC,
converters are marketed which have linearity errors Another application you might use a D/A and a power
greater than that. National Semiconductor, for example, buffer for is to vary the voltage supplied to a small
markets the DACIO2O. DACIO2I, DACIO22 series of resistive heater under program control. Also, the speed
IO'bii-resoiution converters. The linearity specification of small dc motOrs is proportional to the amount of
for the DAC 1020 is 0.05 percent, which is appropriate current passed through them, so you Could Connect a
for a 10-bit Converter. The DACIO2I has a linearity small dc motor to the output of the power buffer and
specification of 0.10 percent. and the DAC 102.2 has a control the speed of the motor with the value you output
specification of 0.20 percent. The c1uestion that may to the D1A. Note that without feedback control, the speed

302 CHAPTER TEN


I TO V DEVICE JUSTIFIED OAC12c€, OACl2OB, DAC12IO


CONVERTER TIP11O UNDER RIGHT LEFT
TEST DElI 0815 -1D 01—iD
D/A
rV -1 D 01-1D 0—I
oH o aki
D 8-BIT al—ID
INPUT 01— I
DLATCH O 1 i D at—'I
—'--1 18-BIT o
RF
V0U.r I
I our DATA BUS o 0 o
°H
ai—..l,,ro
O a o °l-j CURRENT
D :HD SWITCHES
12-BIT
LE DAC
PORT A/D
D/A REGISTER
CURRENT 0 D a
OUTPUT OBO D84 4-BIT
o INPUT D a
o LATCH 0 0
0

FIGURE 10-16 High-power buffer for 0/A output.

Vcc °1 BYTE 1/
BYTE 2
of the motor will vaxy if the load changes. Later in the SIGNAL
FROM
chapter we show you how to add feedback control to ADDRESS
DECODER
maintain constant motor speed under changing loads.
So far we have talked about using an 8-bit 0/A with SYSTEM WR2
a microprocessor. Interfacing an 8-bit converter Involves STROBE -=. L
simply connecting the inputs of the converter to an
output port or, for some 0/As, simply connecting the II
inputs to the buses as you would a port device. Now,
suppose that for some application you need 12 bits of FULL-SCALE ADJUST
resolution, so YOU need to interface a 12-bit converter.
If you are working with a system which has an 8-bit
data bus, your first thought might be to connect the
lower 8 inputs of the 12-bit converter to one output port
and the upper four inputs to another port. You could OAC12. LF35 Voor
send the lower S bits with one write operation and the .
upper 4 bits with another write operation. However, the
time between the two writes introduces a potential
problem in this approach. A DJ UST M E NT I
Suppose, for example, that you want to change the
output of a 12-bit converter from 0000 1111 1111 to VorHI,, XRI=-2FORO<D.C4095
0001 0000 0000. When you write the lower 8 bits, the
IbI
outputwfllgofrom0000 liii 1111 to000000000000.
When you write the upper 4 bits, the output will go back
FIGURE 10-17 (a) National DAC12O8 12-bit 0/A input
up to the desired 0001 0000 0000. The point here is
block diagram showing internal latches. (b) Analog
that for the time between the two writes the output will
Circuit connections.
go to an unwanted value. In many systems this could
be disastrous. The cure for this problem Is to put latches
on the input lines. The latches can be loaded separately
and then strobed together to pass all 12 bits to the 0/A an SDK-86 board, you can simply connect the DAC 1208
converter at the same time. data inputs to the lower 12 data bus lines, connect the
Many currently available 0/A converters contain built- CS input to an address decoder output, connect the
in latches to make this easier. Figure lO-17a shows a WR1 input to the system WR line and tie the WR2 and
block diagram of the National DAC 1230- and DAC 1208- XPER inputs to the ground. The BYTE 1/BYTE input is
type 12-bit Converters. Note the Internal latches and the tied high. You then write words to the converter just as
register. The DAC 1230 serIes of parts has the upper 4 lilt were a 16-bi' port. The timing parameters for the
input bits connected to the lower 4 bits so that the 12 DAC 1208 are acceptable for an 8086 operating with a
bits can be written with two write operations from clock frequency of 5 MHz or less. For higher 8086 clock
an 8-bit port or data bus such as that of the 8088 frequencies, you would have to add a one-shot or other
microprocessor. The DAC 1208 series of parts has the circuitry that inserts a WAIT state each time you write
upper 4 data inputs available separately so they can be to the 0/A. Here are a few notes about the analog
connected directly to the bus in a system which has a connections for these devices.
16-bit data bus, as shown in Figure l0-l7a. If, for These 0/A converters require a precision voltage refer-
example. you want to connect a DAC 1208 converter to ence. The circuit in Figure l0-l7b uses a - 10.000-V

ANAI.00 INTERFACING AND INDUSTRIAL CONTROL 303


reference. The DIA converters have a current output. so +4 V
an op amp is used to convert the D/A output current to
a proportional voltage. A FET input amplifier is ts.d
here because the input bias current of a bipolar input
amp mtgh affect the accuracy of the output. The
DAC 1208 and DAC 1230 have built-In feedback resistors
which match the temperature characteristics of the Dl
internal current-divider resistors, so all you have to add
externally is a 50-fl resistor for 'tweaking" purposes. BINARY CODE
With a - 10.000-V reference as shown, the output OUTPUT
voltage will be equal to (the digital input word!
4096) >< I + 10.000 Vi. Note that the D/A has both a Do
digital ground and an analog ground. To avoid getting
digital noise In the analog portions cf the circuit, these
two should be connected together Only at the power
supply.

AID CONVERTER SPECIFICATIONS,


TYPES, AND INTERFACING
FIGURE 10-18 Paraflel comparator A/D converter,
AID Specifications
The function of an AID converter is to produce a digital
word which represents the magnitude of some analog code, but it can be converted to any desired code with
voltage or current. The specifications for an A/D con- some simple logic. The major disadvantage of a hash
verter are very similar to those for a D/A converter. The A/D is the number of comparators needed to produce a
resolution of an A/D converter refers to the number of result with a reasonable amount of resolution. The 2-
bits in the output binary word. An 8-bit converter, for bit converter in Figure 10-18 requires three compara-
example, has a resolution of 1 part in 256. Accuracy and tors. To produce a converter with N bits of resolution,
linearity specifications have the same meanings for an you need i2 5 - I I comparators. For an 8-bit conversion,
A/D converter as they do for a D/A converter. Another then, you need 255 comparators, and for a 10-bit Hash-
important specification for an A/D converter is its conver- converter, you need 1023 comparators. Single-package
sion time. This is simply the time it takes the converter Hash converters are available from TRW for applications
to produce a valid output binary code for an applied in which the high speed is required, but they are
input voltage. When we refer to a converter as high' relatively expensive. Flash Converters which can do an
speed, we mean that it has a short conversion time. 8-bit conversion in under 10 ns are currently available.
There are many different ways to do an A/D conversion.
but we have spe here to review only three commonly DUALSIOPE AID CONVERTERS
used methods, which represent a wide variety of conver-
sion times. Figure lO-19a shows a functional block diagram of a
dual-slope AID converter. This type of converter is often
used as the heart of a digital voltmeter because it can
AID Converter Types give a large number of bits 01' resolution at a low cost,
l-lere's how the converter ii. Figure 10-19 works.
PARAI.LEL COMPAR,ATQR AID CONVERTER
To start, the control circu,tt-y rescts all the counters
Figure 10-18 shows a circuit for a 2-bit A/D converter to zero and connects the input of the integrator to the
using parallel comparators. A voltage divider sets refer- input voltage to be converted. If you assume the input
ence voltages on the inverting inputs of each of the voltage is positive, then this will cause the output of the
comparators. The voltage at the top of the divider chain integrator to ramp negative, as shown In Figure lO-19b.
represents the full-scale value for the converter. The As soon as the output of the integrator goes a few
voltage to be converted is applied to the noninverting microvolts below ground. the comparator output will go
inputs of all the comparators in parallel. If the input high. The comparator output being high enables the
voltage on a comparator is greater than the reference AND gate and lets the I-MHz Jock Into the Counter
voltage on the inverting input, the output of the compa. chain, After some fixed number of counts. typically
rator will go high. The outputs of the comparators then 1000. the control circuitry switches the input of the
give us a digital representation of the voltage level of the integrator to a negative reference voltage and resets all
input signal. With an input voltage of2.6 V. for example, the counters to zero, With a negative input voltage, the
the outputs of comparators Al and A2 will be high. integrator output will ramp positive, as shown in the
The major advantage of a parallel. orflash. AID con- right-hand side of Figure 10-1 g b. When the integrator
verter is its speed of conversion, which is simply the output crosses 0 V. the comparalor output will drop low
propagation delay time of the comparators. The output and shut off the clock signal to the counters. The
code from the comparators Is not a standard binary number of Counts required for the integrator output to

304 CHAPTER TiN



1-MFO CLOCK The main dIsadvantage of slope-type converters is
their slow speed. A 4k-digit unit may take 300 ms to do
ANALOG INTEGRATOR
v,, a conversion.
ri COMPARATOR

10 kit SUCCESSIVE-APPROXIMATION ND CONVERTERS


Figure 10-20. p. 306, shows a circuit for an 8-bit
SWITCH successtve-approximatton converter which uses readily
CONTROL available parts. The heart of this converter is a succes-
sive-approximation register (SARI such as the MC 14549,
RESET I BINARYORBCOCOUNTERS which functions as follows.
On the fIrst clock pulse at the start of a conversion
-. r'-i LATCHES
= -1 V cycle, the SAR outputs a high on its most-significant bit
DECODER/DRIVERS to the MC 1408 D/A converter. The D/A converter and
the amplifier convert this to a voltage and apply it to one
CONTROL _I L' I_I I_I input of a comparator. If this voltage is higher than the
CIRCUITS i_I LI !_I LI input voltage on the other input of the comparator, the
comparator output will go low and tell the SAR to turn
off that bit because it is too large. If the voltage from the
D/A converter is less than the input voltage, then the
to comparator output will be high, which tells the SAR to
FIXED TIME keep that bit on. When the next clock pulse occurs, the
1000 COUNTS
I t2 SAR will turn on the next most significant bit to the
TIME
1)/A converter, Based on the answer this produces from
the comparator, the SAR will keep or reset this bit. The
LAAGE V SAR proceeds In this way on down to the least significant
bit, adding each bit to the total in turn and using the
SMALL V signal from the comparator to decide whether to keep
V 1: X t2 that bit in the result, Only nine clock pulses are needed
}LOPEsJ._ AC to do the actual conversion here. When the conversion
V= is complete, the binary result is on the parallel outputs
of the SAR, and the SAR sends out an end-of-conversion
- V11 e; X t2
AC AC (EOC) signal to indicate this. In the circuit in Figure
vo.ts t2=-- Xii
10-20, the EOC signal is used to strobe the binary
result into some latches, where it can be read by a
microcomputer. If the EOC signal is connected to the
start-conversion (SC) input as shown, then the converter
FIGURE 10-19 Dual-slope A/D conVerter.- (a) Circuit.
will do continuous conversions, Note in the circuit in
(b) Integrator output waveform.
Figure 10-20 that the noninverting input of the op amp
on the 1408 D/A converter is connected to — 5 V instead
get back to zero ts directly proportionai to the input of to ground. This shifts the analog input range to —5
voltage. For the circuit shown in Figure 10-19a, an V to +5 V instead of 0 V to + 10 V so that sine waves
input signal of +2 V. for example, produces a count of -and other ac signals can be input directly to the converter
2000. Because the resistor and the capacitor on the to be digitized.
integrator are used for both the input voltage integrate The National ADC 1280 isa single-chip 12-bit succes-
and the reference integrate, small variations in their sive-approximation converter which does a conversion
value with temperature do not have any effect on the in about 22 p.s. Datel and Analog Devices have several
accuracy of the conversion. 12-bit converters with conversion times of about I p.s.
Complete iope-type AID converters are readily avail- Several commonly available successive-approximation
able In singI C packages. One example Is the Intersil A/D Converters have analog multipiexers on their inputs.
CL7 136, which contains all the circuitry for a 3k-digit The National A11C0816. for example, has a 16-Input
A/D converter and all'the Interface circuitry needed to multiplexer in front of the A/D converter. This allows
drive a 3)-digit LCD. Another example is the Intersil the one converter to digitize any one of 16 input signals.
1CL7135, which contains all the circuitry for a 4).diglt The input channel to be digitized is determined by a 4-
A/D converter and has a multiplexed BCD output. Note bit address applied to the address inputs of the device.
that, because of the usual use of this type of converter. An A/D converter with a multiplexer on Its inputs is
we often express its resolution in terms of a number of often called a data acquisition system, or DAS. Later in
digits. The full-scale reading for a 3 . digit converter is this chapter we show an application of a DAS in a factory
1999, so the resolution corresponds to about I part in Control system.
2000. A two-chip set, the Intersil 1CL8068 and ICL7 104 Before w go on to discuss ND interlacing, we need
16. contains all the circuitry for a slope-type 16-bit to make a few comments about common A/D output
binary output AID converter. codes.

ANAI.OG INTERFACING ANI) INf)USTIIAL (1ONTOt 305


CLOCK
INPUT

1060 5OpF I +5V


+5V
+15 V
? 22k0'" (10) 9) (16) 81 SERIAL
MR SC OUTPUT
12I
±5 V MA MC14549 END OF CONVERSION
00 -5 V
1/2 MS8IIIIIU
181 1M319N

-15 V

14)
74LS374
1 DATA
OUTPUTS

10

(SI 11I (B) I iOlt2l


ITO,
,f
+ 1EV
MC 1408

3) 114)1 (15)) 1)1


NC

.,1
-iSV -5V
12113)1

+5V -iSV
OpF

-
2.5k

Vfiff F

FIGURE 10-20 Successive-apprOxmatiOfl NO converter circuit.

UNIPOLAR OI1.IABY CODES


A/D OUTPUT CODES NVERTEO
10
COMPLEMENTARY INVERTEO COM PC 6 B 0 N I A B N
VOLTS BINARY
For convenience indifferent applications, A/D converters VALUE
FULL 181)41
BINARy BINARY
BINARY
ICE) 118)
are available with several different, somewhat confusing. SCALE ICE)

output codes. The best way to make sense out of these +FS-1 LSB 9.9609 1111 fl)
tOYS 6.I) 10IXJO 0111 1111
different codes is to see them all together with represen- .SYS -1 LOB 4.9609 0711 III) 0900000
tative values, as shown in Figure 10-21. The values 4) LSB 0.039) )00001 TIll 17)0
TIlT Ill 00O)0 1111 1711
shown here are for an 8-bit converter, but you can ZERO 0.0)390 0(030000

extend them to any number of bits, -1 LOB -0,039) 000(10001 1)11 1110
_'/, FS + I LOB -49609 0(17 1111 100000OS
For an A/D converteE with only a positive input range -'SF0 -5.0000 )CO00 0111 11)1
-FS,t LOB -99609 (Ill ill)
(urotpolar). a straight binary code or inverted binary j
code is usually used. If the output of an A/D converter
UNIPOLAR BINARY CODED DECIMAL CODES
is going to drive a display, then it is convenient to have
COMPLEMENTARY INVERTED INVERTED
the output coded 1n BCD. For applications where the 70 BINARY BINARY COMPLEMENTARY
BINARY
VOLTS COOED BINARY CODED
VALUE COOED COOED
input range of the converter has both a negative and a PULL DECIMAL
DECIMAL OECIU,'IL DECIMAL
SCALE BCO)
positive range (bipolar), we usually use offset-binary CBCD) IIBCOI )ICBCDI

coding. As you can see in Figure 10-21, the values of 4FS-. I LOB 9,9 10011001 07100110
''SF5 5,0 OIOIOOCO 70701111
00000000 to 11111111 are simply shifted downward so +1 LSB - 0.1 0000) 1111 1110
that 00000000 represents the most negative input value ZERO 00 00000009 (111 III 0000 1111 1)11
and 10000000 represents an input value of zero. This -I ISS -01 I1 tIll 1110
coding scheme has the advantage that the 2's comple- -ISFS -5.0 0l0l 10101111
-FS +1 LOB --99 1097 7001 07100770
ment representation can be produced by simply in-
verting the most significant bit. Some bipolar converters
BIPOLAR BINAR y CODES
output the digital value directly In 2's complement form. COMPLEMENTARY'
IOVOLI'S OFFSET TWOS
OFFSET
VALUE FULL SCALE BINARY COMPLEMENT
BINARY
RANGE IDE)
(COOl
lId
Interfacing Different Types of A/D +FS 50000'
Converters to Microcomputers .1-S-I LOB 49609 III) 1111 00000 DIII Ill)
000OI
+1 CSB 00391 0)100091 0(11 1110

INTERFACING TO PARALIEI-COMPARATOR ZERO O3 I0000XID OIl) 7)7

k/D CONVERTERS -T LOB -0039) 011) 1111 10005)09 1111


-FS'T LSB -4,9609 0I III 1110 T0(0000I
In any application where a parallel comparator converter -FE -5.0000 CR0 1171 TIlT 1(030009

is used, the converter is most likelygoing to be producing


digital output values much faster than a microcomputer FIGURE 10-21 Common AID output codes.

306 CHAPTER TEN


could possibly read them In. Therefore, separate cir- the microcomputer for the data transfer. The first of
cuitry is used to bypass the microprocessor and load a these is a START CO4VERT signal which you output
set of samples from the converter directly into a series of from the microcompter to the A/D to tell It to do a
memory locations. The microprocessor can later perform conversion for you. The second signal is an EOC signal
the desired operation on the samples. Bypassing the which the A/I) converter outputs to indicate that the
microprocessor In this way is called direct memory conversion is complete and that the word on the outputs
access, or DMA. The basic principle of DMA is that an is valid. Here are the program steps you use to get a
external controller IC tells the microprocessor to float data sample from this type of converter.
its buses. When the microprocessor does this, the DMA First, you pulse the START CONVERT input for a time
controller takes control of the buses and allows data required by the particular converter. Then you detect
to be transferred directly from the A/D converter to the EOC signal going low on a polled or interrupt basis.
successive memory locations. We discuss DMA in detail You then read In the digitized value from the parallel
in the next chapter. outputs of the converter. In a later section of this chapter
we show a detailed example of this for the National
INTERFACING TO SIOPE-TYPE A/D CONVERTERS ADCOSO8 converter.
Most of the commonly available slope-type Converters
were designed to drive 7-segment displays In. for exam- A MICROCOMPUTER-BASED SCALE
ple, a digital voltmeter. Therefore, they usually output
data in a multiplexed BCD or 7-segment form. Figure So far in this book we have shown you how a basic
10-23 shows how you can connect the multiplexed BCD microcomputer functions and how to interface a wide
outputs of an inexpensive 3-dig1t slope converter, the variety of devices to the basic microcomputer. Now it's
MC 14433. to a microprocessor port. In the section of tine to show you how some of these pitces are put
the chapter where Figure 10-23 is located, we use thIs together to make a microcomputer-based instrument.
converter as part of a microcomputer-based scale. The l'he first instrument we have chosen is a "smart" scale
BCD data is output from the converter on lines 90 such as you might see at the checkout stand in your
through 93. A logic high is output on one of the digit local grocery store.
strobe lines. DSI through DS4. to indicate when the
BCD code for the corresponding digit is on the Q outputs.
The MCI 4433 converter shown in Figure 10-23 outputs Overview of Smart-Scale Operation
the BCD code for the most significant digit and then Figure 10-22. p. 308, shows a block diagram of our
outputs a high on the DS1 pin. After a period of time, smart scale. A load cell converts the applied weight of. for
it outputs the BCI) code for the next most significant example, a bunch of carrots to a proportional electrical
digit and outputs a high on the DS2 pin. After all 4 signal. This small signal is amplified and converted to
digits have been put out, the cycle repeats. a digital value which can be read in by the microproces-
To read In the data from this converter, the principle sor and sent to the attached display. The user then
is simply to poll the bit corresponding to a strobe line enters the price per pound with the keyboard, and this
until you find it high, read in the data for that digit, price per pound is shown on the display. When the
and put the data in a reserved memory location for user presses the compute key on the keyboard, the
future reference. After you have read the BCD code (or microprocessor multiplies the weight times the price
one digit. you poll the bit which corresponde -id"ftie per pound and displays the computed price. After hold.
strobe line for the next digit untflyou.Ond-thtgh, read ing the price display long enough for the user to read
the code for that digit, and put it In memory. Repeat it. the scale goes back to reading in the weight and
the process until yOO have the data for all the digits. displaying it. To save the user fron having to type the
The A/D converter in Figure 10-23 is connected to do computed price into the cash regIster, an output from
continuous conversions, so you can call the procedure the scale could be connected directly into the cash
to read in the value from the A/D converter at any time. register circuitry. Also, a speech synthesizer could be
Frequency counters: digital voltmeters, and other test added to verbally tell the customer the weight, price per
instruments often have multiplexed BCD outputs avail- pound. and total price.
able on their back panel. With the connections and Smart scales such as this have many applications
procedure we have just described, you can use these other than weighing carrots. A modified version of this
instruments to input data to your microcomputer. scale is used in company mail rooms to weigh packages
and calculate the postage required to send them to
INTERFACING A SUCCESSIVE-APPROXIMATION different postal zones. The output of the scale Is usually
A/D CONVERTER connected to a postage meter, which then automatically
Successive-approximation A/D converters usually have prints out the required postage sticker. Another applica-
outputs for each bit. The code output on these ilnes is tion of smart scales is to count coins in a bank or
usually straight binary or offset binary. You can simply gambling casino. For this application the user simply
connect the parallel outputs of the converter to the enters the type of coin being weighed: A conversion
required number of lnpu port pins and read in the factor in the program computes the total number olcoins
converter output under program control. In addition to and the total doilar amount. Still another application of
the data lines, there are two other successive-approxima- a scale such as this is in packaging items for sale
lion A/D converter signal lines you need to interface to Suppose, for example, that we are manufacturing wood-
- 41 ANALOG INTtRFACING AND INDUSTRIAL CONTROl. 307
FIGURE 10-22 Block diagram of microcomputer-based smart scale.

s-ews and that we want to package 100 of them per the weight after it is read into the microprocessor. The
box. We can pass the boxes over the load cell on a 0.1 -ixF capacitor between pins 15 and 16 of the amplifier
,weyor belt and fill them from a chute until the we4ght. reduces the bandwidth of the amplifier to about 7.5 Hz.
P . 1 therefore the Count, reaches some entered value. This removes 60 Hz and any high-frequency noise that
'1 . ,c point here is that the combination of intelligence might have been induced in the signal lines.
some simple interface circuitry gies you an Instru- The MC14433 A/D converter used here is an Inexpen-
r-ent with as many uses as your imagination can come sive dual-slope device intended for use In 3k-digit digital
p with. voltmeters. etc. Because the load cell output changes
slowly, a fzs& converter isn't needed here. The voltage
across an LM329 6.9-V precision reference diode is
vart-Scale Input Circt" amplified by iC4 to produce the 10.00-V excitation
re lO10 shows a picl;: 1' 1e rras, :.... ;, l.c. vclage for the load cell and a 2.000-V reference for the
-f .ei C46-1 #-ION load JD. With a 2.000-V reference voltage, the full-scale Input
ce built this scale. 'V.ei a p. :e o oig: for tie A/D Is 2.000 V. Conversion rate and
top of the load c-eli to ,.-. -o Irma fn., muipi'lng frequency for the converter are determined
.Thisloadcellhases a- by i internal oscillator and Ru. An Rh of 300 kfl
X,O. or 0.01 lb over the & . oge for 1;ch a elock [requency of 66 kFlz. a multiplex frequency
designed. 1 0. kh-lz. and about four conversions per second.
)s shown In Figure 10-2.3, the lo i cnsls's c/ Ac-uIat) of the converter is ±0.05 percent and ± 1
350-fl resistors connected In hr/dge 'fiiuratiou. count, which is comparable to the accuracy of the load
;-t.blc lO.00v excitation vtage i . spt tc, the top cell. in ,ther words, the last digit of toe displayed weight
ie bridge. With no load on the ceb. the cutpus frcn may be off by 1 or 2 counts. As we described in a previous
: bridge are at aut th same .altage. 5 V. When a scctio. the Output from this converter is in multiplexed
v'i is applitd to thc bridge. - msstance of one of the '-iCD form.
-ar resiatora will bc chanc: Tht produces a small
entIal output voltage t :tfl tIe bricige. The maxi- An Mgorthm for the Smart Scale
m differential output voltage for thts 10-lb load cell Figure 1024 shows the flowchart for our smart scale.
it/V per volt of excitation, so with 10.00 V excitatIon Note that, as indicated by the double-ended boxes In the
s shown, the maximum differential-output voltage is flowchart, most major parts of the program are written
0 mV. as procedures. This is an example of the structured.
To ampl1li this small differential signal, we use a modular programming approach we have stressed
National LM363 tpsti-umentation amplifier. This device throughout the book. Here's how it all works.
contains all the circuitry shown for the instrumentation The output of the A/D is in multiplexed BCD form.
unpllfier In Figure 10-lh. The closed-loop gain of the The Converter outputs the BCD code for a digit on its
:rnplifier is programmable with Jumpers on pins 2, 3, Q0—Q3 lines and outputs the strobe for that digit on
'd 4 for fixed values of 5, 100, and 500. We have the corresponding digit strobe line. DSI—DS4. To read
;3rpered it for a gain of 100 so that the 20-mV maximum the data for a digit, that digit strobe is polled until it
I,iial from the load cell will give a maximum voltage of goes high; then the BCD code for that digit is read in.
200 V to the A'D converter input. A precision voltage After the four BCD values are read in from the converter.
divider on the output of the amplifier divides this signal a display procedure is called to display these values on
in half so that a weight of 10.00 lb produces an output the address field displays of the SDK-86. The letters "Lb'
voltage of 1.000 V. This scaling simplifies the display of are displayed in the data field displays.

308 CHAPTER TEN


+12 V + iSV
START

LM329'' 21LM30, k_

_j,jv INITIALIZE
LOADCELL 1+15 V
BALANC I
6.4 K _DJUST
1% 1% KO
I GET WEIGHT I
FROMAJO
' -- CONVERT
PRICE/LB
TO BINARY
j35Ofl 350r) ': DUMB II DISPLAY II
SCALE
3N,6i3
MODULE
IIII WEIGHT AND LBIIIi CONVERT
14 WEIGHT
TO BINARY

350 350)') I 12 IOKO
0.1% 7N0
I 2i-J 2
MULTIPLY
WEIGHT X
N iV PRICE/LB
WHITE I 0.1%
DISPLAY 'SP.
FOR
SELLING PRICE CONVERT
________ J6 TOTAL PRICE
10 (UI (24) +5V - TO BCD
(1) 8255
.4:-J- ___?
2) 48 —PA3
Q3)23) DISPLAY KEY ROUND OFF
470 K)) [ (3) Q2 22) - 44 - PA2 PRESSED 'OTAL PRICE T(
NEAREST CENT
_A,A./y_.__ (4) 01(21) 40 - PAl
_______ 00(20) - 36 —PAO
(5)
Cl 0.1 pF READ DISPLAY
0S1 (19) - 50 - PA4
GET KEYBOARD TOTAL PRICE
-}------- (6) DS2 (18) - 46 - PA5 PRICE/LB
________
(7) MODULE
0S3 (17) - 42 - PA6
2 \1 0i HF ,,
— 7r-- ' •' - NO KEY WAIT
PRESSED 3 SECONDS

7NO

YES
FIGURE 10-23 Circuit diagram for load-cell interface
circuitry and AID converter for smart scale, FIGURE 10-24 Flowchart for smart-scale program.

Next, a check is made to see if any keys have been equivalents and then multiplied the binary numbers.
pressed by the user. If a key has been pressed, the letters Another procedure converts the binary result of the
"SP," which represent selling price, are displayed in the multiplication to RCD. The BCD result Is rounded to
address field. Keycodes are read from the 8279 as entered the nearest cent and displyed in the data field. The
and displayed on the data field display. Keys can be letters Pr" are displayed in the address field to indicate
pressed until the desired price per pound shows on that this is the total price. After a few seconds the
the display. When a nonnumeric key is pressed, it is program goes back to reading and displaying weight
assumed that the entered price per pound is correct, over and over, until a key is pressed.
and the program goes on to compute the total price.
Computing the price involves multiplying the weight
in BCD form times the price per pound in BCD form. It
The Microprocessor-Based Scale Program
is not easy to do a BCD x BCD multiply directly, so we Figure 10-25. p. 310-15, shows the complete program
took an alternate route to get there. We converted both for our microprocessor-based scale. It is important for
the weight and the price per pound to their binary you not to be overwhelmed by a multipage program such

ANALOG INTERFACING AND INDUSTRIAL CONTROL 309


;8086 PROGRAM F10-25.ASM
2 ;A8STRACI : Program for t scale
3 ;PORTS Uses SDK-86 port PIA (FFF9H) for inp.it
4 ;PR0CEDURES READ KEY, DISPLAY IT, PACK, EXPAND, CONVERT2BIII, BIWCVT
5
6 0000 DATA SEGMENT WORD PUBLIC
7 0000 04(00) WEIGHT BUFFER 08 4 DUP(0) Space for unpacked BCD weight
8 0004 04 * (00> SELL_PRICE 08 4 DLIP(0) Space for unpacked price/pound
9 0008 04 * (00)
PRICE_TOTAL 08 4 DUP(0) Space for total price to display
10 000C 0000 BINARY_WEIGHT OW 0 Space for converted weight
11 000E 08 10 14 ¶4 LB 08 0814, 1014, 1614, 1414 b, L, blank, blank
12 0012 12 11 14 14 S_P 08 ¶214, 1114, 1414, 1414 P. S. blank, blank
13 0016 13 12 14 14 PR 08 1314, 1214, ¶414, 1414 r, P. blank, blank
14
15 1 1 2 3 4 5 6 7
16 QOIA 3F 06 5B 4F 666070 * SEVEN_SEG 08 3F14, 0614,5814, 4FH, 6614,6014, 7014,0714
17 07
18 8 9 A b C d E F
19 0022 if 6F 77 7C 39 5E 79 08 7F11, 6tH, 7714, 7C14, 3914, 5EN, 7914, 7114
20 71
21 I S P r blank H
22 002A 38 60 7'S 50 00 76 08 3814, 6014, 7314, 5014, 0014, 7614
23 0030 DATA ENDS
26
25 0000 STACK_SEG SEGMENT

26 0000 28(0000) OW 40 DUP(0)
27 STACK TOP LABEL WORD
28 0050 STACK_SEG ENDS
29
30 0000 CE SEGMENT WORD PUBLIC
31 ASSUME CS:CtE, DS:DATA, SS:STACK_SEG
32 ;Initialize data & stack seent registers
33 0000 88 0000s START NOV AX, DATA
34 0003 BE 08 NOV OS, AX
35 0005 88 0000s NOV AX, STACK_SEC
36 0008 BE DO NOV SS, AX
37 000A BC 0050r NOV SP, OFFSET STACK_TOP
38 ;8279 initialized at power-up of SDK-86 for 8 character display,
39 Left entry encoded scan, 2-key lockout.
40 0000 BA FFEA NOV DX, OFFEAN Point at 8279 control address
41 0010 80 00 NOV AL, 0014 Control word for above conditions
42 0012 EE ESIT DX, AL Send control word
43 0013 80 38 NOV AL, 001110008 Clock word for divide by 24
44 0015 EE JT OX, AL
45 0016 BO CO NOV AL, 110000008 Clear display character is all 0's
46 0018 EE c*JT DX, AL
47 ;Dur scale start
48 0019 89 0004 ROWT: NOV CX, 0414 Zero out weight buffer
69 OO1C 68 0000r NOV BX, OFFSET WEIGHT_BUFFER
50 OO1F C6 07 00 NEXT1: NOV BYTE PTR(BXI, 0014
51 0022 43 INC 8X
52 0023 E2 FA L00P NEXT1
53 0025 89 0004 NOV CX, 0414 Zero out price/pound buffer
54 0028 88 0004r NOV BX, OFFSET SELL_PRICE
55 0028 Co 07 00 NEXT2: NOV BYTE PTR(BX], 0014
56 002E 43 INC BX
57 002F E2 FA 1DP NEXT2
58 ;Get weight from A/D converter and display.
59 0031 88 0003r NOV BX,OFFSET WEIGIITBUFFER.3; MSD Position in weight buffer
60 0034 BA FFF9 NOV DX, OFEF9H Point at A/I) port
61 0037 EC OS1: IN AL, DX ; Read byte from A/D
62 0038 24 10 AND AL, 1014 Check for NSD strobe high
63 003A 74 FB JZ DS1 Loop till high
64 003C EC IN AL, DX Read NSD data from A/D
65 0030 24 OF AND AL, OFH Mask strobe bits
66 003F 3C 04 CNP AL, 0414 See if MSD in bit 3 is a one
67 0041 74 06 JE LOAD1 ; Yes, go toad 0114 in buffer
68 0043 C6 07 14 NOV BYTE PTR(BX], 1414 No, load code for blank
69 0046 ES 04 90 JNP WXTCHR
70 0049 CO 07 01 LOAD1: NOV BYTE PTR(8X1. 0114
71 OO4C 48 NXTCHR: DEC aX Point to next buffer location
72 0060 DS2: IN AL, OX Poll for digit 2 strobe

FIGURE 10-25 Assembly language program for smart scale. (Cont,nued on pages 311-75.)

310 CHAPTER TEN


73 004€ 24 20 AND AL, 20,4
74 0050 74 FB JZ DS2
75 0052 Ec IN AL, DX ; Read digit 2 from AID
76 0053 24 OF AND AL, 0FH ; Mask strobe bits
77 0055 88 07 NOV (8X), AL ; Digit 2 BCD to buffer
78 0057 48 DEC BX ; Point at next buffer location
79 0058 EC DS3: IN AL, DX ; Poll for digit 3 from A/D
80 0059 24 40 *110 AL, 4011
81 0058 74 FB JZ DS3
82 005D EC IN AL, DX ; Read digit 3 from A/D
83 005E 24 OF AND AL, OFH ; Mask strobe bits
84 0060 88 07 NOV (BX],AL ; Digit 3 to buffer
85 0062 48 DEC RX ; Point to next buffer location
86 0063 EC DS4: IN AL, DX ; Poll for digit 4 USC)
87 0064 24 80 AND AL, 8011
88 0066 74 FB J2 DS4
89 0068 EC IN AL, DX ; Read digit 4 from A/D
90 0069 24 OF AND AL, 0TH ; Mask strobe bits
91 0068 88 07 NOV (8)1), AL ; Digit 4 8CC to buffer
92 ;Oisplay weight on address field of SDK-86
93 0060 88 0000r NOV BX, OFFSET WEIGHT BUFFER ; Point at stored weight
94 0070 BO 01 NOV AL, 0114 ; Specifies address field
95 0072 94 01 NOV AN, O1H ; Specifies decimal point
96 0074 E8 OOCF CALL DISPLAY_IT
97 0077 88 000Er NOV 8)4, OFFSET LB Point at Lb string
98 007A 80 00 NOV AL, 00 ; Specifies data field
99007C 8400 NOV AM, 00 ; Specifies no decimal point
100 COlE E8 OOCS CALL DISPLAY_IT
101 ;Check if key has been pressed
102 0081 BA FFEA NOV DX, OFFEAII Point at 8279 status address
103 0084 EC IN AL, DX Read 8279 FIFO status
104 0085 24 01 AND AL, O1H ; See it FIFO has keycode
105 0087 75 02 JNZ GETKEY ; Yes, go read it
106 0089 ER 8E JMP ROUT 140, go get weight and display
107 0088 80 40 GETKEY: NOV AL, 010000008 Control word for read FIFO
108 0080 EE JT DX, AL ; Send to 8279
109 008€ BA FFE8 NOV DX, OFFE8H ; Point at 8279 data address
110 0091 EC IN AL, DX ; Read code from FIFO
111 0092 3C 09 CMP AL, 09H ; Check if legal keycode (n.mer)
112 0094 76 02 JBE OK Go on if below or equal 9
113 0096 €8 81 JNP RDWT ; Else ignore, read weight again
114 ;Read in and display price/pound
115 0098 B8 0004r OK: NOV 8)4, OFFSET SELL_PRICE Point at price per pound buffer
116 0098 88 07 NOV (8)41, AL ; Keycode to buffer
117 0090 80 00 NOV AL, 00 ; Specify data field for display
118 009F 94 01 NOV AM, 01 ; Specify decimal point
119 00*1 E8 00A2 CALL DISPLAY IT
120 00A4 88 0012r NOV BX, OFFSET SP ; Point at SP string
121 00*7 80 01 NOV AL, 01 ; Specify address field
122 00A9 94 00 NOV All, 00 ; Specify no decimal point
123 COAB €8 0098 CALL DISPLAY_IT
124 COAt €8 0083 NXTKEY: CALL READ_KEY Wait for next keypress
¶25 0081 3C 09 ClIP AL, 0911 ; See if more price or cooinand
126 0083 77 iF JA C()IPUTE ; Go coeute total price
127 0085 88 0004r NOV 8)4, OFFSET SELL_PRICE ; Point at price per pound buffer
128 0088 8* 4F 02 NOV CL, (8)4+2) ; Shift contents of buffer one
129 0088 88 4F 03 NOV (8)1+3), CL ; position left and insert new
130 008€ 8* 4F 01 NOV CL, (8)1+1) ; keycode
131 OOC1 88 4F 02 NOV (BX2] , CL
132 00C4 8* OF NOV CL, (8)4)
133 0006 88 4F 01 NOV [BX11, CL
134 00C9 88 07 NOV (8)41 , AL
135 OOCB 80 00 NOV AL, 00 ; Specify data field
136 OOCD 84 01 NOV All, 01 Specify decimajpoint
137 0OCF (8 0074 CALL DISPLAY_IT
138 0002 ER DA JMP NXTKEY ; Keep reading and shifting keys
139 until conimand key pressed
140 ;Coirpute total price
141 0004 98 000Cr CNIPUTE: NOV BX,OFFSET WEIGHT_BUFFER; Point at weight buffer for pack
142 0007 80 7F 03 14 CNP BYTE PTR[Bx+3], 1/.11 ; See if MSD of weight 0
143 0008 75 04 JIlt NOTZER
144 0000 CO 47 03 00 NOV BYTE PTR(BX+3], 00 Yes, load 0 in place of blank code
145 00(1 (8 0098 NOTZER: CALL PACK ; Pack BCO weight into word
FIGURE 10-25 (Continued)

ANALOG INTERFACING AND INDUSTRIAL CONTROL 311


146 00E4 ES 0008 CALL COIIVERT2BIN Convert to 16 bit binary in AX


147 00E7 A3 000Cr NOV BINARY_WEIGHT, AX and save
148 OOEA 88 0004r MDV BX, OFFSET SELL_PRICE Point at price per pound for pack
149 OOED E8 008F CALL PACK Pack 8C0 price into AX for convert
150 OOFO ES 00CC CALL CON VERT2BIN ; Convert price to 16-bit binary n Ax
151 00F3 Fl 26 000Cr IJL BINARY_WEIGHT Price per pound in AX * binary weight
152 total price result in DX:AX
153 00F7 88 08 NOV BX, Ax Prepare for convert to BCD
154 00F9 ES 0104 CALL BINCVT ; Packed BCD price result in DX:BX
155 ;Round off price to nearest cent and display
156 OOFC 80 FB 49 ClIP BL, 49)1 Carry set if BL .49H
157 00FF BO 00 MDV AL, 00 Clear AL, keep carry
158 0101 12 Cl ADC Al, 8)1 Add any carry to next di9it
159 0103 27 DAA Keep in BCO format
160 0104 BA D8 NOV BL, AL Save Lower two digits of price
16T 0106 80 00 NOV AL, 00 Clear AL, save carry
162 0108 12 C2 ADC Al, DL Propagate carry to upper digits
163 O1OA 27 DAA Keep in BCD form
164 0108 BA ED NOV AM, AL Position upper digits for EXPAND
165 0100 BA C3 NOV Al, BL Position lower digits for EXPAND
166 OlaF 88 0008r NOV BX, OFFSET PRICE_TOTAL Point at buffer for expanded BCD
161 0112 ES 0084 CALL EXPANO Unpack BCD for DISPLAY_IT procedure
168 0115 80 00 NOV AL, 00 Display total priceon data field
169 0117 84 01 NOV AM, 01 with decimal point
170 0119 E8 002A CALL DISPLAY_IT
171 O11C 88 0016r NOV BX, OFFSET PR Point at price/lb String
172 OIIF 80 01 NOV AL, 01 Display in address field
173 0121 B4 00 NOV AM, 00 without decimal point
174 0123 E8 8020 CALL DISPLAY_IT
175 ;Delay a few seconds
176 0126 89 FFFF NOV CX,OFFFFII ; Delay a few seconds
177 0129 88 000* CNTON1: NOV BX, 000A14
178 012C 48 CNTDN2: DEC BX
179 0120 75 FD JNZ CNTDN2
180 012F E2 F8 LOOP CNTOM1
181 ;Go reed next weight
182 0131 E9 FEE5 JMP ROUT JUT back to dolt scale
183
184 PROCEDURES USED IN SMART SCALE PROGRAM
185
186 PROCEDURE READ_KEY
187 ;ABSTRACI :Reads the SDK-86 keyboard - polls the Status register of the
188 8279 on the SDK-86 board untiit finds a key pressed. It then
189 reads the keypressed code fr the FIFO RAN to AL and exits
190 ;REGISTERS: Destroys AL - returns with character read in AL
191
192 0134 READ_KEY PROC NEAR
193 0134 52 PUSH DX
194 0135 BA FfEA MOV DX, OFFEAH Point at 8279 control address
195 0138 EC NO_KEY: IN AL, DX Get FIFO Status
196 0139 24 01 AND AL, 00000001B Mask all but LSB, high if key in FIFO
197 0138 74 FB J2 NO_KEY Loop until a key is pressed
198 0130 BO 40 NOV Al, 010000008 Control word for read FIFO
199 013F EE JT DX, AL Send control word
200 0140 BA FFE8 NOV DX, OFFE8H Point at 8279 data address
201 0143 EC IN AL, DX Read character in FIFO ram
202 0144 5* POP DX
203 0145 C3 RET
204 0146 READ_KEY ENDP
205
206 ; PROCEDURE DISPLAY IT
207 ;ABSTRACT: Displays chiracters on the SDK-86 display. The data is sent to
208 ;INPUT : ALQ for data field
209 AL1 for address field
210 AH0 for no decimal point
211 AH=1 for decimaL point between second & third digit
212 8X offset of buffer containing 7-seq codes of the four
213 characters to be displayed
214 0146 DISPLAY IT PROC NEAR
215 0146 9C PUSHF Save flags and registers
216 0147 50 PUSH Ax
217 0148 53 PUSH BX
218 0149 51 PUSH CX

FIGURE 10-25 (Continued)

312 CHAPTER TEN


219 014* PUSH DX
220 0146 PUSH SI
221 0140 FFEA NOV DX, OFFEAH Point at 8279 controL address
222 014F 00 CMP AL, 0011 See if •data field required
223 0151 05 JZ DATFLD Yes, load control word for data field
224 0153 94 NOV AL, 9411 No, Load address-field control word
225 0155 03 90 .JMP SEND Go send control word
226 0158 90 DATFLO: NOV AL, 90H Load control word for data field
227 015* SEND: JT DX, AL Send control word to 8279
228 0158 04 NOV CL, 04H Counter for nurber of characters
229 0150 F3 NOV SI, BX Free 8)1 for use with XLAT
230 015F OOlAr NOV BX, OFFSET SEVEN_SEG Pointer to seven-segment codes
231 0162 FFE8 NOV DX, OFFE8H Point at 8279 dispLay RAM
232 0165 04 AGAIN: NOV AL, (SI] Get character to be dispLayed
233 0167 XLATB TransLate to 7-seg code
231. 0168 F9 02 CNP CL, 02H See if digit that gets decimaL point
235 0168 07 JNE MORE No, go send digit
236 0160 FC 01 CMP AH, 0111 Yes, see if decimal point specified
237 0170 02 JIlt MORE No, go send character
238 0172 80 OR AL,80H Yes, OR in decimal point
239 0174 MORE: .JT DX, AL Send 7-seg code to 8279 display RAM
240 0175 INC SI Point to next character
241 0176 ED LOCP AGAIN until all four characters sent
242 0178 POP SI
243 0179 POP OX Restore alL registers and flags
244 017* POP CX
245 0178 POP BX
246 017C POP AX
247 0170 POPF
248 017E RET
249 017F DISPLAY_IT ENDP
250
251 PROCEDURE PACK
252 ;ABSTRACT: Converts four unpacked BCD digits pointed to by BX to
253 four packed 8CD digits in AX
254 ;OESTROYS: AX -
255
256 017f PACK PROC NEAR
257 017F 9C PUSH F Save flags and registers
258 0180 53 PUSH BX
259 0181 51 PUSH CX
260 0182 8* 07 NOV AL, (8X) First BCD digit to AL
261 0184 81 04 NOV CL, 0411 Counter for rotate
262 0186 02 47 01 ROL BYTE PTR(BX1), CL Position second BCD digit
263 0189 02 47 01 ADO AL, (BX1] First 2 digits in AL
264 018C BA 67 02 NOV AN, (BX+2] Third digit to AN
265 01SF D2 47 03 ROL BYTE PTR[BX+3], CL Position fourth digit
266 0192 02 67 03 ADD AN, (BX+3] Second two digits now in AN
267 0195 58 POP BX
268 0196 59 POP CX
269 0197 90 POP F
270 0198 C3 RET
271 0199 PACK ENDP
272
273 PROCEDURE EXPAND
274 ;ABSTRACT: Expands a packed BCD nuther in AX to 4 unpacked BCD
275 digits in a buffer pointed to by 8)1
276
277 0199 EXPAND PROC NEAR
278 0199 9C PUSH F
279 019* 50 PUSH AX
280 0198 53 PUSH BX
281 019C 51 PUSH CX
282 0190 88 07 NOV (BX],AL Move first 2 BCD digits to buffer

283 019F 80 27 OF AND BYTE PRIBX],OFH Mask off upper digit
284 01*2 81 04 NOV CL, 04H Counter for rotates

285 01*4 02 C8 ROR AL, CL Position digit 2 in low nibble
286 01*6 24 OF AND AL, OFH Mask uppor nibble
287 O1AB 88 47 01 NOV [BX*1), AL Digit 2 buffer
288 OTAB 88 67 02 MOV [BX+2] , AN Second 2 BCD digits to buffer

289 O1AE 80 67 02 OF AND BYTE PTR[BX+2] ,OFH Mask off upper digit
290 0182 02 CC ROR AU, CL Position digit 1 in Low nibble
291 0164 60 E4 OF AND All, OFH Mask upper nibble

FIGURE 10-25 (Continued)

ANALOG INTERFACING AND INDUSTRIAL CONTROL 313


292 0187 88 67 03 NOV (BX*31, AH Digit 4 to buffer
293 O1BA 59 POP CX
294 0188 58 PUP lix
295 O1BC 58 POP AX
296 0180 90 POPF
297 O1BE C3 RET
298 OlaF EXPAND EIdOP
299
300 PROCEDURE CONVERT2BI.N
301 ;ABSTRACT: Converts a 4 digit BCD nu,er in AX register into its binary
302 (HEX) equivalent. It returns the result in the AX register
303 ;DESTROYS: AX register
304
305 = 03E8 THJ EQU 3E8H 1000 3E8H
306 O1BF CONVERT2BIN PROC NEAR
307 O1BF 9C PUSHF Save fLags and registers
308 OTCO 53 PUSH BX
309 OWl 52 PUSH DX
310 01C2 51 PUSH CX
311 01C3 57 PUSH DI
312 01C4 88 08 NOV BX, AX Copy nuer into BX
313 0106 8A C4 NOV AL, All Place for upper 2 digits

314 01C8 8A F8 MDV RH, BL Place for Lower 2 digits
315 ;Split up nuthers so that we have one digit in each register
316 O1CA 81 04 NOV CL, 04 NibbLe count for rotate
317 01CC 02 CC ROR AN, CL Digit 1 in correct place
318 O10E 02 CF ROR 8H, CL Digit 3 in correct place
319 0100 25 OFOF AND AX, OFOFH
320 0103 81 E3 OFOF AND 8X, OFOFH Mask upper nibbles of each digit
321 ;Copy AX into CX so that can use AX for nultiplication
322 0107 88 C8 NOV CX. AX
323 0109 88 0000 NOV AX, 0000H
324 ;Now nsLtipLy each nurer by its place value
325 O1DC 8A CS NOV AL, CH MuLtiply byte in AL * word
326 O1DE BF 03E8 NOV DI, THJ No imediate aultiplication
327 O1E1 FT E7 MILL DI Digit I * 1000
328 ;Result in DX and AX. Because BCD digit not >9 result in AX only
329 ;Zero DX and add BL because that digit needs no aultiptication for
330 ;place value. Then add the result in AX for digit 4
331 01E3 BA 0000
NOV DX, 0000H
332 01E6 02 D3 ADD DL, BL Add digit 1
333 01E8 03 DO ADD DX, AX Add digit 4
334 ;Continue with nuLtiplications
335 O1EA 88 0064 NOV AX, 006411 Byte * byte result in AX
336 O1ED F6 El MUL CL ; Digit 2 * 100
337 O1EF 03 DO ADD DX, AX Add digit 3

338 O1F1 88 090A MOV AX, 000AH Byte * byte result in AX
339 01F4 F6 E7 NUL RH
340 01F6 03 00 ADD DX, AX dd d,yt
341 01F8 88 C2 NOV AX, DX Put result in correct place
342 O1FA SF POP DI
343 0DB 59 POP CX

344 O1FC 5A POP DX Restore registers
345 O1FD SB POP BX
346 O1FE 90 POPF
347 01FF C3 RET
348 0200 CONVET2BIN ENDP
349
350 PROCEDURE BINCVT
351 ;ABSTRACT: Converts a 24-bit binary njaber in DL and BX to a packed
352 BCD equivalent in DX:BX
353 ;INPUTS: DL, BX - 24 BIT BINARY NUMBER
354 ;JTPUTS: OX, BX - PACKED BCO RESULT
355 ;CALLS: CNVT1
356 ;OESTROS DX and 8X
357
358 0200 BINCVT PROC NEAR
359 0200 9C PUSHF ; Save registers sod flags
360 0201 50 PUSH AX
361 0202 51 PUSH CX
362 0203 86 19 NOV OH, 19H Bit counter for 24 bits
363 0205 E8 0018 CALL CNVT1 Produce 2 LS BCD digits in CH

364 0208 8A CD NOV CL CH : Save in CL

FIGURE 10-25 (Continued)

314 CHAPTERTEN


365 020A B6 19 OH, 19W Bit co,Jter for 24 BITS
366 020c EB 0014 CALL CNVT1 Produce next 2 BCD digits in CII
367 020F 51 PUSH CX Save tower 4 BcD digits on stack
368 0210 B6 19 NOV OH, 19W Bit Co,ter for 4 bits
369 0212 ER 000E CALL CNVT1 Produce next 2 8cO digits in CII
370 0215 BAco -v CL, CH Position in CL
371 0217 B6 19 NOV OH, 19H Set bit counter for 24 bits
372 0219 E8 0007 CALL CNVT1 Produce last 2 BCD digits in CH
373 021C 88 Dl NOV 0X,CX Position 4 MS BCD DIGITS for return
374 021E SB Pop BX Four LS BCD digits back from stack
375 021F 59 Pop CX for return
376 0220 58 Pop AX
377 0221 90 POPF
378 0222 C3 RET
379 0223 BINCVT EPIDP
380
381 PROCEDURE CNVT1
382 0223 CNVT1 PROC WEAR
383 0223 32 CO XOR AL, AL Clear AL and carry as workspace
38.4 0225 8A E8 NOV CH, AL Clear CII
385 0227 32 CO CNVT2: NOR AL, AL Clear AL and CARRY
386 0229 FE CE DEC DII Decrement bit counter
387 022B 75 01 JWZ CONTINUE Do all bits
388 0220 C3 RET Done if OH down to zero
389 022E Dl 03 CONTIWUE:RCI BX, 1 BX left one bit, MSB to carry
390 0230 Do 02 RCL DL, 1 HSB from BX to 158 of DL, NSB of DI. to carry
391 0232 8A C5 NOV AL, CH Hove BCO digit being built to AL
392 0234 12 CO ADC AL, AL. Dote AL and add carry from DL shift
393 0236 27 DAA Keep result in BCD form
394 0237 8A E8 NOV CII, AL Put back in CII for next time through
395 0239 73 EC INC CNVT2 No carry from DAA, continue
396 023B 83 03 00 ADC BX, 0000W If carry, propagate to BIt and DL
397 023E 80 D2 00 ADC DL, DOW for future terms
398 0241 ER E4 JNP CWVT2 Cant i flue conversion
399 0243 CNVT1 ENDP
400 0243 CE ENDS
401 END
FIGURE 10-25 (Continued)

as this, If you use the 5-minute rule and work your way field or address field and a 1 or a 0 in AH to specify a
through this program one module at a time, you should decimal point in the middle of the display or no decimal
pick up some more useful programming techniques and point. You then load BX with the offset of the memory
procedures you can use in your programs. buffer containing the unpacked codes for the digits to
Three 4-byte buffers set up at the start of the program be displayed. A program loop in the display procedure
are used to Store the unpacked BCD values of the weight. uses the XLAT instruction and the SEVEN_SEG table
the price per pound. and the computed total price. to convert these codes to the required 7-segment values
These buffers will be used to pass values to the display and send the values to the 8279 display RAM. For
procedure. The SEVEN_SEG table in the data segment displaying the weight, BX is simply loaded with the
contains the 7-segment codes for BCD digits, hex digits. offset of WEIGHT_BUFFER. AL is loaded with 01 to
and some letters we use to indicate which value is being display the weight in the address field, and All is loaded
displayed. in the display procedure you will see how with 01 to insert a decimal point at the appropriate
these codes are accessed. place.
After Initializing everything, the program polls the To display the letters Lb in the data field. BX is loaded
digit strobe for the most significant digit from the AID with the offset of the string named LB. and the display
converter. Since this A/D converter isa 3)-digit unit, the procedure is callçd. Again, the XLAT instruction loop
MSD can be only a 0 or a I. The value for this digit is converts the code4 from the LB string to the required 7-
sent in the third bit, (bit 2) of the 4-bit digit read in. If segment codes and sends them out of the 8279 display
this bit isa 1. then Otis loaded into the buffer location. RAM. The codes in the string named LB represent the
If the bit is a 0. then the value which will access the 7- offsets from the start of the SEVEN_SEC table for the
segment code for a blank (141-1) is loaded into the buffer desired 7-segment codes. For example, the 7-segment
location. Each of the other digit strobes is then polled code for a P is at offset 12H in the SEVEN_SEG table.
in turn, and the values for those digits are read in. When Therefore, if you want to display a P. you put l2H in the
all the BCL) digits for the weight are in the WEIGHT_ appropriate location in the character string in memory.
BUFFER, the display procedure Is called to show the The XLAT Instruction will then use the value l2H to
weight on the address field. access the 7-segment code for P in the SEVEN_SEC.
To use the display procedure we wrote for this pro- table.
gram. you first load a 0 or a 1 intO AL to specify data After displaying the weight. the program reads the

- 42 ANALOC INT(RFACINC AND INDtJSIRIAI CONTROL 315


8279 status register to see. If the operator has pressed


a number key to start entering a price per pound. Ii no
key has been pressed or if a nonnumeric key has been
pressed, the program simply goes back and reads the
weight again. if a number keyhas been pressed, the CLEAR AL AND CARRY
weIght is removedfrom the addis field and the letters AS WORKSPACE
SP (selling price) are displayed in the address field. The
entered number is put in the SELL..PRICE buffer and
displayed on the rightmost digit of the data field. The
program then poiis the 8279 status register until another
keypress is detected, lithe pressed key is a numeric key,
then the code(s) for the previously entered number(s)
will be shifted one location in the buffer to make room DECREMENT BIT
COUNTER
for the new number. The new number is then put in
the first location in the buffer so that it will be displayed
in the rightmost digit of the display. In other words.
previously entered numbers are continuously shifted to BIT
the left as new numbers are entered. If a mistake is COUNTER
= 5 ? ________
made, the operator can simply enter a 0 followed by the
correct price per pound. NO __
When a nonnumeric key is pressed, this is the signal
that the displayed price per pound is correct and that [SHIFT BX LEFT BIT
MSB TO CARRY
the total price should now be computed. Before the SHIFT DL LEFT 1 BIT
weight and the price per pound can be multiplied. CARRY TO LSB
however, they must each be put in packed BCD form MSB To CARRY
and converted to binary.
The PACK procedure converts four unpacked BCE) 2. DIGIT BEING BUILT
digits in a memory buffer pointed to by BX to a 4.dtgit AND ADD CARRY
packed result in AX. This procedure is simply some FROM DL SHIFT
masking and moving of nibbles. Once the weight and
ptice per pound are packed in BCI) fomi. the CON DECIMAL ADJUST TO
VERT2BIN procedure is used to convert ach to Its KEEP IN BCD FORMAT
binary equivalent. The algorithm for this procedur. is
explained in detail in Chapter 5.
Unlike earlier processors, which reulred a messy
NO
procedure for multiplication, a single 8086 MUL insiruc. INAL>99!
tion does the 16 x 16 binary multiply to produce the CARRY 1?
binary equivalent of the total price. The procedure
BINCVT is used to convert the binary total price to the YES
packed BCD form needed for the DISPLAY..,,IT procedure. ADD OVERFLOW
Here's how the BINCVT procedure works. CARRY TO BX & DL
FOR NEXT BCD
In a binary number, each bit position represents a BYTE CALCULATION
power of 2. An 8-bit binary number, for example, can
be represented as:
FIGURE 10-26 Flowchart for CNVT1 subpjocedure.
b7x21+b6x26+b5x25+t,<24
+b3x23 +b2x22 +bj x2+b0
of CNVFI. The main principle he toshift the 24Ebit
This can be shuffled around and expressed as number left one bit position so thai the MSB goes into
the carry flip. flop and then add hi bit lo twice the
Binary number previous result. We use the DAA instrucUpirto keep the
((U((2b7 + b6l 2 + bS) 2 + b4) 2 result of the addition in BCE) format. If th€DAA produces
+ b3)2 + b2)2 + bl)2 + bO a carry. we add this carry back into the shifted 24-bit
number in DL and BX so that it will be propagated into
where b7 through bO are the values of the binary bits. higher BCE) digits. After each run ofCNVTI (24 runs of
If we start with a binary number and do each operation CNVT2), DL and BX will be left with a binary number
in the nested parentheses in BCD with the aid of the Which Is equal to the original binary number minus the
DAA instruction, the result will be the BCE) number value of the two BCE) digits produced. You can adapt
equivalent to the original binary number. this procedure to work with a different number of bits
The procedure in Figure 10-25 produces two BCE) by simply calling CN'V'rI more or fewer times and by
digits of the result at a time by calling the subprocedure adjusting the count loaded into DH to be I more than
CNVF 1. Figure 10-26 shows a flowchart for the operation the number of binary bits in the number to be converted.
316 CHAPTER TEN
The count has to be 1 greater because of the position of
the decrement In the loop. The temperature-controller
procedure in FIgure 10-35 shows another example of
this conversion.
The least significant two digits of the BCD value for
the total price returned by BINCVT in BL represent
tenths and hundredths of a cent. If the value of these
two BCD digits is greater than 49H. then the carry
DC
produced by the compare instruction and the next two MoTor
higher BCD digits in BH are added to AL. This must be
done In AL. because the DAA instruction, used to keep
the result in BCI) format, only works on an operand in
AL. Any carry from these two BCD digits is propagated
on to the upper two digits of the result in DL. After thi.
rounding off, the packed BCD for the total price is left
in AX.
In order for the display procedure to be able to display FIGURE 10-27 Circuit for controlling speed of dc motor
this price, it must be converted to unpacked BCD form using feedback from tachometer,
and put in four successive memory locations. Another
"mask and move nibblc" procedure called EXPAND does
this. The DISPLAY.JT procedure is then called to display possible for any change in the variable caused by. for
the total price on the data field. The DISPLAY..JT proce- example. increased load on a motor. A simple example
dure Is called again to display the letters Pr in the will show the traditional approach to control of a process
address field. variable and explain some of the terms used in control
Finally, after delaying a few seconds to give the opera- systems.
tor time to read the price, execution returns to the The circuit in Figure 10-27 shows an analog app
"dumb-scale" portion of the program and starts over. to controlling the speed of a dc motor. Atttched to the
A question that may occur to you when reading a long shaft of the motor is a dc generator. or tachometer.
program such as this is, How do you decide which parts which puts out a voltage proportional to the speed of
of the program to keep in the mainline and which parts the motor. The output voltage is typically a few volts per
to write as procedures? There is no universal agreement 1000 rpm. A fraction of the output voltage from the
on the answer to this question, The general guidelines tachometer is -fed back to the inverting input of the
we follow are to write a program section as a procedure power amplifier driving the motor. A positive voltage is
if It is going to be used more than once in the program. applied to the noninverting input of the amplifier as a
it is reusable (could be used in other programs). It is so et point. When the power is turned on, the motor
lengthy (more than 1 page) that it clutters up the accelerates until the voltage fed back from the tachome-
conceptual flow of the main program. or it is an essen- ter to the inverting input of the amplifier is nearly equal
tially independent section. The disadvantage of using to the set-point voltage.
too many procedures is the time and overhead required If the load on the motor is increased, the motor will
for each procedure call. As you write more programs, initially slow down, and the voltage output from the
you will arrive at a balance that feels comfortable to you. tachometer will decrease. This will increase the differ-
The following section shows you another long program ence In voltage between the inputs of the amplifier and
example which was written in a highly modular manner cause it to drive more current to the motor. The increased
so that it can easily be expanded. This example should current will increase the speed of the motor to nearly
lurther help you see when and how to use proedures. the speed it had before the increased load was added. A
similar reaction takes place if the load on the motor Is
decreased.
Using negative feedback to control a system such as
A MICROCOMPUTER-BASED INDUSTRIAL this is often called servo control. A control loop of
PROCESS-CONTROL SYSTEM this type keeps the motor speed quite constant for
Overview of Industrial Process Control applications where the load on the motor does not
change much. Some hard-disk drive motors and high-
One area in which microprocessors and microcomputers quality phonograph turntables use this method of speed
have had a major impact is industrial process control. control.
Process control involves first measuring system variables For applications in which the load and/or the set point
such as motor speed. temperature. the flow of reactants, changes drastically, there are several potential problems.
the level of a liquid in a tank, the thickness of a material. The first of these is overshoot when you change the set
etc. The output of the controller then adjusts the value point. Figure 10-28a, p. 318. shows an example of this.
of each variable until it is equal to a predetermined value in this case the variable—motor speed. for example—
called a set point. The system controller must maintain overshoots the new set point and bounces up and down
each variable as close as possible to its set-point value. for a while. The time it takes the bounclruZ to settle
and it must compensate as quickly and accurately as within a specified error range or error band is cilied the

ANALOG INTERFACING AND INDUSTRIAL CONTROL 317


PEAK gain of the amplifier to produce the additional drive for
ERROR
ERROR the motor. For stability reasons, the gain
NEW ii } BAND
SETPOINT systems cannot be too high. Therefore, even if you adjust
the speed of a motor, for example. to be exactly at a
given speed for one load, when you change the load there
OLD will always be some residual error between the set point
SETPOINT and the actual output.
To help solve these problems, circuits with more
complex feedback are used. Figure 10-29 shows a circuit
which represents the different types of feedback com-
RESIDUAL ERROR monly used. First note in this Circuit that the output
power amplifier is an adderwlth four Inputs. The current
- 4ERROA supplied to the summing point of the adder by the set-
NEW - BAND
SEIPOINT point input produces the basic output drive current.
The other three inputs do not supply any current unless
there is a difference between the set point and the
OLD feedback voltage from the tachometer. Amplifier I is
SE TPOIN I another adder whose function is to compare the set-
point voltage with the feedback voltage from the tachom-
(b) eter. Let's assume the two input resistors, RI and R2.
are equal. Since the set-point voltage is negative and the
RESIDUAL ERROR voltage from the tachometer is positive, there will be no
net current through the feedback resistor of the amplifier
SETPOINT If the two voltages are equal in magnitude. In other
MOTOR SPEED
words, if the speed of the motor is at its set-point value,
the output of amplifier 1 will be zero, and amplIfiers 2,
3. and 4 will contribute no current to the summing
junction of the power amp.
INCREASEO LOAD Now, suppose that you add more load on the motor.
Id slowing it down. The tachometer voltage Is no longer
equal to the set-point voltage, so amplifier I now has
FIGURE 10-28 Overshoot and undershoot of system some output. This error signal on the output produces
when set point or load is changed. (a) Overshoot. three types of feedback to the summing junction of the
(b) Undershoot, (c) load change. power amp.
Amplifier I produces simple dc feedback proportional
to the difference between the set point and the tachome-
settling time. This type of response Is referred to as ter output. This Is exactly the same effect as the voltage
underdamped and Is sim'lar to the response that a car divider on (he tachometer output in Figure 10-27.
with bad shock absorbers will make when it hits a Proportional feed back, as this is called, will correct for
bump. The ringing can be prevented by adding damping most of the effect of the increased load, but, as we
to the system. However, If too much damping Is added, discussed before, there will always be some residual
the response to a change in set point may look like that error.
'hown in Figure l0-28b. This type response is referred The cure for residual error is to use some integral
to a.s .i overdamped response. The difficulty with this feedback, Amplifier 3 in Figure 10-29 provides this type
type response is that it takes a long time for the variable of feedback. Remember from a previous discussion that
to reach the new set point. For best performance, the this circuit produces a ramp on Its output whenever a
damping must be custom designed for a particular voltage is applied to its input. For the example here, the
system. integrator will ramp up or ramp down as long as there
Another problem in any process control system is is any error signal present on its input. By ramping up
residual error. Figure lO-28c shows the response a and down Just a tiny bit about the set point, the
control system such as the motor speed controller in integrator can eliminate most of the residual error. Too
Figure 10-27 will have when more load is added on the much integral feedback, however, will cause the output
motor. The motor initially slows down, so the voltage to oscillate up and down. Also, feedback only slowly
of the tachometer decreases. As we said before, this affects the output because the error signal must be
leases the voltage difference between thc amplifier present for some time before the integrator has much
inputs and causes tl'e amplifier output to increase. output.
Increased amplifier output increases the speed of the To improve the response time of the system. amplifier
motor and thereby the output from the tachometer. 4 in Figure lO-29suppllesa third type of feedback called
When the system reaches equilibrium, however, there derivative feedback. Derivative feedback is a signal
is some noticeable difference between the set point and proportional to the rate of change of the error signal. If
the voltage led back from the tachometer. It is this the load on the system is suddenly changed. the deriv3-
difference or residual error which is amplified by the tive amplifier circuit will give a quick shot of Ieedbak

318 CI-IAPTERT[N
MOTOR

FIGURE 10-29 Circuit showing proportional, integral, and derivative feedback


control.

to tly to correct the error. When the error signal is first to changes in load or set point. Process control 1oops
applied to the dltTerentiator circuit, the capacitor In that use all three types of feedback are called proportional
series with the input is not charged, so it acts like a integral derivative or PID control loops. Because process
short circuit. This Initially lets a large current flow, so variables change much more slowly than the microsec-
the amplifier has a sizable output. As the capacitor ond operation of a microcomputer, a microcomputer
charges, the current decreases, so the feedback from the with some simple input and output circuitry can perform
differentiator decreases. The differentiator essentially all the functions of the analog circuitry in Figure 10-29
gives the amplifier a quick pulse of feedback to help for several PID loops.
correct for the increased load. Too much derivative Figure 10-30 shows a block diagram of .a microcom-
feedback can cause the system to overshoot and oscillate. puter-based process-control system. Data acquisition
The point here Is that by using a combination of some systems convert the analog signals from various sensors
or all of these types of feedback, a given feedback- to digital values that can be read in and processed by
Controlled system can be adjusted for optimum response the microcomputer. A keyboard and display in the

DISPLAY
PRESSURE SENSORS I—I RELAYS I

TEMPERATURE SENSORS

FLOW METER
I-
0
2 MICRO-
COMPUTER
A-

a.
z I-
Io
0
LOAD CELLS

LIQUID-LEVEL SENSORS DAS

RN METERS KEYBOARD
CONTAO'L
SIGNALS
NI TODAS

FIGURE 10-30 Block diagram of microcomputer-based process control system.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 319


kyhoard or a clock "tick" from the timer. The keyboard
strobe signal and the clock signal are each connected to
interrupt inputs.
When the microcomputer receives an interrupt from
the timer, it goes to a procedure which determines
whether it is time to service the next control loop. The
Interrupt procedure does this by counting interrupts In
the same way as the real-time clock we described In

_J.
I
Chapter 8 does. If you program the timer to produce a
pulse every I ms, and you want the controller to Service
another loop every 20 ms, for example. you can simply
have the interrupt procedure count 20 interrupts before
going on to update the next loop. Once 20 interrupts
have been counted down, the program falls into a
decision structure which determines which loop is to
be updated next. Every 20 ms a new loop is updated. so
with eight loops, each loop gets updated every 160 ms.
This system is an example of a time-slice system, because
each loop gets a 20-ms "slice" of time every 160 ms.

r An important point here is that the microcomputer


services each loop at regular intervals instead of simply
updating all eight loops, one loop right after another.
This is done so that the timing for each loop is independ-
ent of the timing for the other 1oops. Therefore, a change
in the internal timing for one loop will not affect the
timing in the other 1oops.
Each PID loop is controlled by an independent proce-
dure. For our example system here, we have space to
show the implementation of only one loop, the control
of the temperature of a tank of liquid in. perhaps, our
FIGURE 10-31 Photograph of Texas Instruments' printed-circuit .board-making machine. You could write
programmable controller. other similar control-loop procedures to control pH. flow,
light exposure timing, motor speed. etc.
Figure lO-32c shows the flowchart forour temperature-
system allow the user to enter set-point values, to read controller PID loop. Note that we use lower-level proce-
the current values of process variables, and to issue dures to implement most steps in thebasic PID procedure.
commands. Relays. D/A converters, solenoid valves, and These low-level operations are written as procedures so
other actuators are used to control process variables that they can be used in other PID loops. Also, using
under program direction. A programmable timer In the procedures here maintains the top-down program struc-
system determines the rate at which control loops are ture we have been trying to get you to use In your pro-
serviced. grams. Work your way through Figure 10-32 until you
Microcomputer-based process-control systems range clearly see the program levels. After we look at the hard-
from a small programmable controller such as the one ware of the system, we will dig into the details of the actual
shown in Figure 10-31. which might be used to control program.
a machine on a factory floor, to a large minicomputer
used to control an entire fractionating coh:imn In an oil
refinery. To show you how these microcomputer-based Hardware for Control Systems
control systems work. here's an example system you can and Temperature Controller -
build and experiment with. To build the hardware for this project. we started by add-
ingan 8254 programmable timer and an 8259A priority
interrupt controller to an SDK-86 board, as shown in
AN 8086-BASED Figure 8-14. The timer is initialized to produce l.kHz
PROCESS-CONTROL SYSTEM clock ticks. The 8259A provides interrupt inputs for the
Program Overview clock-tick interrupts and for keyboard interrupts. We
built the actual temperature sensing and detecting cir-
Figure 10-32 shows in flowchart form one way in which cuitry on a separate prototyping board and connected it
the program for a microcomputer-based control system to some ports on the SDK-86 with a ribbon cable. Figure
with eight PlO loops can be structured. After power is 10-33. p. 322. shows this analog interface circuitry.
turned on, a mainline or executive program initializes The temperature-sensing element in the circuit is an
ports. Initializes the timer, and Initializes process vari- LM35 precision Celsius temperature sensor. The voltage
ables to some starting values. The executive program between the output pin and the ground pin of this device
then sits in a loop waiting for a user command from the will be 0 V at 0 C and will increase by 10 mV for

320 CHAPTER TEN


START ) MAINLINE OR ICK INTERRUPT LOOP 0
- - BACKGROUND
PROGRAM

INITIALIZE ON TIME
PORTS COUNTED

INITIALIZE TURN HEATER


TIMER OFF

INITIALIZE OFF TINE


PROCESS COUNTED
VARIABLES

GET NEW
UNMASK AND TEMPERATUR
ENABLE READING
INTERRUPTS

CONVERT TO
BCD FOR
DISPLAY
LOOK FOR
USER
COMMAND
KEY PRESSED DISPLAY

FIND T

YES

SERVICE çAro
USER
COMMAND

-J COMPUTE
HEATER
DUTY CYCLE
I.'

SET DUTY
CYCLE FOR ON

TURN HEATER
ON

SET DUTY
CYCLE FOR
OFF

AETI
TOINTR .)
II

FIGURE 10-32 Flowchart for microcomputer-based process control system.


(a) Mainline or executive. (b) Loop selector. (ci Temperatue-controI loop.

ANALOG INTERFACING AND INDUSTRIAE CONTROL 321


+5V +5V
*5 V
t +15v -
HEATING PIN NUMBERS FOR
10k
CONNECTOR iS OF
SOK-86
PORT 2C
28 P2CS
-15V 26 P2C4
[ -15V '=•
6 P2C3
1K
l0k 4 P2C2
TEMPERATURE SENSOR
2 P2C1
STATE 24 P2CG
74C14 RELAY 12OVAC
+5V
1k 0.1,F 4 PORT 28
+5 V ADCOSO8
°- B P267
OUTPUT END OF
ENABLE CONVERSION - NC- 12 P266
START
INPUT 0 - CONVERSION 22 - 20 P265
27 INPUT I ALE - 16 P264
18 23
O.J1pF OSCILLATOR INPUT 2 ADC - NC- 14 P263
DAS 24
INPUT 3 A08 - - 16 P262
INPUT 4 ADA - 22 P281
+15 V INPUTS DATA 7 - 10 P260
INPUT 6 DATA 6
[_5 INPUT7 OATA5 I! PORT 2A
CLOCK DATA 4 18 36 P2A7
V OATA3 40 P2A6
_Li1i *REF DATA 2 P2A5
LM329 16 -REF DATA 1 P2A4
JII GND DATAO 17 46 P2A3
42 P2A2
38 P2A1
10k 10sF
SOLID 34 P2AO
TANTALUM
REFERENCE
FOR A/D

FIGURE 10-33 Temperature-sensing and heater-control circuitry for


microcomputer-based controfler.

each increase of 10 C above that. The 30O-kf resistor zener is buffered by an LM308 amplifier to produce a
connecting the output of the LM35 to - ISV allows the Vcc and a V REF 015.12 V for the A/D converter. With this
output to go negative for tmperatures below 0° C. (If reference voltage, the A/D converter will have 256 steps
you are operating with ± 12-V supplies, use a 240- of 20 mV each. Since the temperature sensor si$nal is
kft resistor.) This makes the circuit able to measure amplified by 2. each degree Celsius of temperature
temperatures over the range of —55 to + 150° C. For change will produce an output change of 20 my . or one
our application here, we use only the positive part of the step on the AID converter. This gives us a resolution of
output range, but we thought you might find this circuit 1°C, which is about equal to the typical accuracy of the
useful for some of your other projects. An LM308 buffers sensor. The advantage of using V 5 as the Vcc for the
and amplifies the signal from the sensor by 2 so that aevice is that this voltage will not have the switching
the signal uses a greater part of the input range of the noise that the digital V line has. The control inputs and
A/D converter. This improves the noise immunity and dataoutputsoftheA/Dconverterareslmplyconnectedto
resolution. SDK-86 ports as shown.
The ADCO8O8 A/D converter used here is an 8-input Figure 10-34 shows the timing waveforms and param-
data acquisition system. You tell the device which Input eters for the ADCO8O8, Note the sequence in which
signal you want digitized with a 3-bit address you send control signals must be sent to the device. The 3-bit
to the ADC, ADB. and ADA inputs. This 8-input device address of the desired input channel Is first sent to the
was chosen so that other control loops could be added multiplexer inputs. After at least 50 ns. the ALE input
later. Some Schmitt-trigger inverters In a 74C14 are is sent high. After another 2.5s. the START CONVER-
connected as an oscillator to produce a 300-kl-lz clock SION input is sent high and then low. Then the ALE
for the DAS. The voltage drop across an LM329 low-drift input is brought low again. When the END OF CONVER-

322 CHAPTER TEN


CLOCK

FIGURE 10-34 Timing waveforms for the ADCO8O8 data acquisition system.

SION signal from the A/D Converter is found to be high. pin from the relay, and holds the relay in the off position
the 8-bit data value which represents the temperature when the power is first turned on. Port pins, remember.
can be read in. are in a floating state after a reset, so some method
To control the power delivered to the heater, we used must be used to hold external circuitry In a known state
a 25-A. 0-V turn-on, solid-state relay, such as the Potter until the port is Initialized and the desired value is
Brumfield unit described in Chapter 9. WIth this relay output to the port. Now that you know how the hardware
we can control a 120- or 240-V ac-powered hot plate or is connected, we can explain the operation of the control-
immersion heater. To control the amount of heat put ler program.
out by the heater, we vary the duty cycle of pulses sent
(o the relay.
For very low power .applicat ions, a D/A converter and The Controller System Program
a power amplifier could be used to drive the heater.
However. In high-power applications this is not very THE MAINLINE OR EXECUTIVE SECTION
practical because the power amplifier may dissipate as Figure 10-35. pp. 324-29, shows the assembly language
much or more power than the load. For example, an program for our controller system. Refer to the 1lowchart
amplifier intended to control a 5000-W heater over its in Figure 10-32 as you work your way through this
lull range must be able to dissipate more than 5000W. program. The mainline or executive part of the program
The D/A-converter apprpach has the added disadvantage starts by initializing port FFFAI-I for output, the 8259A
that it cannot directly hse (he available ac line voltage. to receive interrupt inputs from the timer and the
l'hc driver transistor on the Input of the solid-state keyboard, and tht 8254 to produce a I -kHz square wave
rela y supplies the drive for the relay, isolates the port on its counter 0 output. In Chapter 8 we described all

- 43 ANALOG INTERFACING AND INDUSTRIAL CONTROL 323


;8086 I4AINLINE PROGRAM F1O-35a.ASM - UI.E 1


2 ;ABSTRACT; Program for controller system. Services eight process
3 control Loops on a rotating basis. Pri,ylain written to run on an
4 Intel SOK-86 board. Timing for the control Loops is generatedon
S an interrupt basis by an o4i'board 8254 timer. ControL-Loop 0 in
6 the program controls the teeçereture of a water bath.
7 ;PORTS: Uses port P28 (FFFAH) as output
8 bits 7 r heater, bits 6.3 not connected, bit 5 start conversion
9 bit 4 = ALE, bits 2,1,0 channeL address
10 Uses port P2A (FFF8H) as data input
11 Uses port P2C (FFFCH) as end-of-conversion input fron, A/D
12 ;PROCEOIJRES: Uses CLOCK_TICK - interrupt service procedure
13 KEYBOARD - interrupt service procedure (enty)
14
15 0000 1111_PROC SEGMENT WORD PUBLIC
16 EXIRN CLOCK_TICK:FAR, KEYBOARD:FAR
17 0000 INT_PROC ENDS
18
19 PUBLIC CtJNTER, TIMENI, TIMELO, L00PNUM, CLIRTEMP, SETPOINT
20
21 0000 AINT TABLE SEGMENT WORD PUBLIC
22 0000 02*(0000) TYPE 64 DW 2 DUP(0) ;Reserve space for clock-tick proc addr IRO
23 0004 O2*(0000) TYPE_65 OW 2 DUP(0) ;Not used irs this program - IR1
24 0008 02*(0000) TYPE_66 OW 2 DUP(0) ;Reserve space for keyboard proc addr -- 1R2
25 000c Mill_TABLE ENDS
26
27 0000 DATA SEGMENT WORD PUBLIC
28 0000 00 CJN1ER 08 00 ;Counter for nuther of interrupts
29 0001 01 TIMEI4I 08. 01 ;Heater reLay - time on
30 0002 01 TII4EIO 08 01 ;Heater relay - time off
31 0003 00. LOGPNI$I 08 00 ;Tee storage for Loop counter
32 0004 00 CURTEMP 08 00 Current te.Tçerature
33 0005 3C SETPOINT 08 60 ;Setpoint tefrperature
34 0006 DATA ENDS
35
36 0000 STACK SEG SEGMENT ;No STACK directive because using EXE2BIN
37 0000 78( 0000) OW 40 OUP(0) ;so car, then do,n1oad code to SOK-&,
38 TOP STACK LABEL WORD
39 0050 STACK_SEG ENDS
49
41 UUUU C001 SEGMENT WORD PUBLIC
42 ASSUME CSC00E, DS:AINT_TA8IE, SS:STACKSEG
43 ;Ir,itialize stack segment. star-k pointer, and data segment registers
44 0000 88 0000s . NOV AX, STACK_SEG
45 0003 8€ DO NOV SS, AX
46 0005 DC OO5Or NOV SP, 0FSET TOP_STACK
47 0008 B8 0000s NOV AX, AuNT_TABLE
48 0008 8€ 08 NOV OS, AX
49 ;Define the addresses for the interrupt service procedures
50 0000 C? 06 0002r 0000s NOV TYPE_64+2, SEG CLOCK_TICK ;Put in clock-tick proc addr
51 0013 Cl 06 0000r 0000e NOV TYPE_64, OFFSET CLOCK_TICK
52 0019 C? 06 000Ar 0000s NOV TYPE_66.2, SEC KEYBOARD ;Put in keyboard Proc addr
53 OOIF C7 06 000Br 0000c NOV TYPE_66, OFFSET KEYBOARD
54 . ;Initiatize data segment register
55 . ASSUME DS:DATA
56 0025 88 0000s NOV AX, DATA
57 0028 8€ 08 . NOV OS. AX
58 ;Initiatize port P28 (EFFA) as output - mode 0, P2A & P2C as inputs - mode 0
59. 002A BA FFFE NOV DX, OFFFEN ;Point DX at port control addr
60 0020 80 99 NOV AL, 100110018 ;Mode control word for above conditions
61 002F if csJT OX, Al ;Send control word
62 ;Initialize 8259A, edge triggered, single, I.CW4
63 0030 80 13 . NOV AL, 000100.118
640032 BA U_00 NOV DX, OFFOOM ;Point at 8259A control
650035 EE JT OX, AL . ;Send ICW1
66 0036 80 40 NOV AL, 010000008 ;Type 64 is first 8259A type (IRO)
67 0038 BA FF02 NOV DX, OFFO2H ;Point at 1CW2 address
68 0038 EE . CSJT DX, Al ;and send ICW2
69 003C 80 01 . NOV . Al, 000000018 ; 1CW4, 8086 rode
70 003E EE csi DX, Al ;Send 1CW4
71 003F BO FE . NOV AL, 111111108 ;OCW1 to ursr,ask 1R0 only leave 1R2 masked
72 9041 EE 001 CX, AL ;because not used & tend OCU1
FIGURE 10-35 8086 assembly language program for process control system (continued on pp. 325-29).
(a, pp. 324-5 Module 1—mainline. (b, pp. 325-61 Module 2—interrupt-service procedures.
(C, pp:326.-7) Module 3—loop service procedures. (d. pp. 327-29 Module 4—utility procedures.

324 CHAPTER TEN


73 ;lnitialize 8254 counter 0 for 1-kHz .utput, LSB then MSB, square wave, 8CD
74 0042 BC 37 NOV AL, OO11O11IB
75 0044 BA FF07 NOV DX, OFFO7H ;Point 8254 controL addr
76 0047 EE JT DX. AL ;Send counter 0 comand word
77 0048 80 58 NOV AL, 58H ;Load LSB of count
78 004* BA FF01 NOV DX, OFFO1N ;Point at counter 0 data addr
79 0040 EE JT DX. AL ;Send LSB of count
80 DO4E 80 24 NOV AL, 24H ;Load MSB of count
81 0050 EE JT . DX, AL ;Send MSB of count
82 ;Irutialize variables
83 0051 C6 06 000Sr 3C NOV SETPO!NT, 3CH ;Initialze fina teas, at 60
84 0056 C6 06 0000r 14 NOV CIXINTER, 14H ;Intiatize time counter
85 005B C6 06 0003r 00 NOV L0OPNI, OOH ;Start at first toop
86 0060 C6 06 000lr 01 NOV TIMEHI, O1H
87 0065 C6 06 0002r Cl NOV TIMELO, O1H
88006* C6.060004r00 NOV CURTEMP, OOH
89 ;Enabte interrupt input of 8086
90006F FB STI
91 0070 EB FE I4ERE:JMP HERE Wait for interrupt, if required,
92 0072 90 MOP ; can put more instructions here
93 0073 CE ENDS
94 END

;8O86 MODULE 2 PROCEDURES: F10-35B.ASM


2 ;ABSTRACT Module 2 contains the interrupt service subroçjtines for Module 1.
3
4 PUBLIC CLOCK_TICK, KEYBOARD
S
6 0000 DATA SEGMENT WORD PUBLIC ;TetL asseetler where to find
7 0000 00000000se LOOP_ADDR_TABLE DO LODPO ;Loop addresses used in this module
8 0004 00000000se DO LOOP1
9 0008 00000000se DO LOOP2
10 000C 00000000se DO L00P3
11 0010 00000000se DO LOOP4
12 0014 00000000se DO LOOP5
13 0018 000000005e DO LOOP6
14 OO1C 00000000se DO LODP7
.15 EXTRN C'XJNTER:BYTE, LODPNUM:B1'TE
16 0020 DATA ENDS
17
1-8 ;teLL asset,tter where to find procedures used in this module
19 0000 CODE SEGMENT WORD PUBLIC
20 E)(TRN LODP0:FAR, 100P1:FAR, LOOP2:FAR, L00P3:FAR
21 EXYRN 100P4:FAR, LOOPS:FAR, 100P6:FAR, LODP7;FAR
22 0000 CODE ENDS
23
24 0000 INT_PROC SEGMENT WORD PUBLIC ;Sgment for interrupt service procedures
25 ASSUME CS:IWT_PROC, DS:DATA
26
27 ;8086 INTERRUPT PROCEDURE CALLED CLOCK_TICK
28 ;A8STRACT: Services process control loops. Calls 1 of 8 process
29 control Loops on a rotating basis.
30 ;PORTS USED: None
31 ;PROCEDURES: Calls LODPO.LODP1,LOOP2,LODP3,100P4,LOOP5,LOOP6,100P7
32 ;REGISTERS : Saves all
33
34 0000 CLOCK_TICK PROC FAR
35 0000 50 PUSH AX ;Save registers
36 0001 53 PUSH 8*
37 0002 52 PUSH DX
38 0003 1€ PUSH OS ;Save OS of interrupted program
39 0004 F8 511 ;Enabte higher interrupts if any
40 0005 80 20 NOV AL, 001000008 ;0CW2 for nonspecific EOI
41 0007 8* FF00 NOV DX, OFFOOH ;Load address for 0CW2
42 .000* EE JT DX, AL
43 0008 88 0000s NOV AX, DATA ;Load OS needed here
44 000E 8€ 08 NOV OS, AX
65 0010 FE Of 0000e DEC CJNTER ;Decrement interrupt counter
46 0014 75 20 JNZ EXIT2 ;Not zero yet, go wait
47 0016 C6 06 0000e 14 NOV CJM1ER, 20 ;If zero, reset tick counter to 20
48 0018 87 00 NOV 814, 00 ;Load 8* with fluTter of loop to

FIGURE 10-3 (Continued)


ANALOG INTERFACING AND INDUSTRIAL CONTROL 325


49 OO1D 8A IE 0000e NOV BL. IOOPNtJ q ;service and service that Loop
50 0021 FF 9F 0000r
CALL DWORD P18 LOOP ADOR TABLE (BXJ
51 0025 80 06 0000e 04 ADO LN(1, 04 ;Point at next . p address
52 002A 80 3E 0000e 20 CMP LNL84, 20H ;Was this the Last loop?
53 002F 75 05 .JWE EXIIZ ;Ilo, exit
54 0031 C6 06 0000e 00 NOV LOOPNIJ, 00 ;Yes, get back to first loop
55 0036 iF EXIT2:POP OS ;Restore registers
56 0037 5A Pop DX
57 0038 58 Pop 8)1
58 0039 58 POP AX
59 003A CF IRET
60 0038 CLOCK_Il CX ENDP
61
62 ;DUNMY INTERRUPT PROCEDURE TO SERVICE KEYBOARD
63 003B KEYBOARD PROC FAR
64 ;Keyboard procedure intruct ions
65 0038 BO 20 NOV AL, 001000008 ;OCW2 for non-specific (CI
66 0030 BA FF00 NOV OX, OFFOOH ;Load address for OCW2
67 0040 EE .JT DX, AL ;arid send OCW2 for end of interrupt
68 0041 CF IRET
69 0042 KEYBOARD ENOP
70
71 0042 INT_PROC ENDS
72. END

(b)
;8086 MOOULE 3 PROCEDURES: F10-35C.ASM
2 ;ABSTRACT: Module 3 contains the procedures to service each Loop
3
4 0000 DATA SEGMENT WORD PUBLIC
5 EXTRN TIMEHI :BYTE, TIMELO :BYIE ;1norted into this
6 EXTRN CURTENP:BYTE, SETPOINT:BYTE ;modu(e from the mainline
7 0000 DATA ENDS
8
9 PUBLIC LOOPO, LOOP1, L2, LOOP3, 100P4, LOOP5, LOOP6. 100P7
10
11 0000 COOE SEGMENT WORD PUBLIC
12 EXTRN DISPLAY IT HEAR These procedures can be
13 EXIRN A_D_READ : HEAR found in MOOULE 4 which
14 EXIRN BIPICVT
: HEAR will be linked this module

15 0000 COOt ENDS and MC)ULES 1 and 2
16
17 0000 COOE SEGMENT WORD PUBLIC
18 ASSUME CSCOOE. DS:DATA
1.9
20 ;8086 PROCEDURE - LOOPO
21 ;ABSTRACT This procedure services the teirerature controller
22 ;REGISTERS: Destroys none
23 :PORTS: Uses bit 7 of P2B (FFFAH) as output port control heater.
24 ;PROCEDURES: Uses DISPLAY_IT, A_D_READ, BINCVT from Module 4
25
26 0000 LOOPO PROC FAR

PUSH
27 0000 9C F ;Save registers

28 0001 50 PUSH AX
P29USH
0002 53 8)1

30 0003 51 PUSH CX
31 0004 52 PUSH DX

D32 0005
ECFE CE 0000e TIME HI ;Decrement time for heater on
33 0009 75 50 JNZ EXIT ;Return to interrupt procedure
34 0008 C6 06 OQOOe 01 NOV TIMEHL, 01 ;Reset time high to fall through value
35 0010 BA FFFA NOV DX, OFFFAH ;Point at output port P28 &
36 0013 80 80 NOV AL, 80H ;turn off heater
3? 0015 EE JT DX, AL
38 0016 FE OE 0000e
DEC TIMELO ;Decrement time for heater off

39 OO1A 75 3F JNZ EXIT ;Return to interrupt procedure
40 OO1C B3 00
NOV BL, 00 ;Load charnel address (0)
41 DOlE E8 0000e
CALL A 0 READ ;Do A/D conversion

42 0021 A2 0000e NOV CURTEMP, AL Save current teff,erature
43 0024 (8 0000e CALL BINCVT ;Convert to BCD

44 0027 8A C8 NOV CL, AL ;Put result in CX to display
45 0029 85 00 NOV CH, 00

46 0028 BO CO NOV AL, 00 tee in data field of SOK-86

FIGURE 10-35 (Continued)

326 CHAPTER TEN


47 0020 ES 0000e c*t DISPLAY_IT
48 0030 *0 0000e NOV AL, SETPOINT ;Get setpoint teeçerature
49 0033 2* 06 0000e SUB AL, CURTEMP ;Get teeçerature & stract from setpoint
50 0037 76 18 IDE DONE ;Ileater off if above or equal setpoint
51 0039 8* 00 NOV DL, AL ;Save tefTperature difference
52 003B 88 0064 NOV AX, 006411 ;Comçute new TIMELO
53 003E F6 F2 DIV DL 0064/error, quotient is value
54 0040 *2 0000e NOV TIMELO, AL for new time Low
55 0043 C6 06 0000e 04 NOV TINEHI, 04 ;Set time high for 4 Loops
56 0048 BO 00 NOV AL, 00
57 OO4A BA FFFA • NOV DX. OFFFAH ;Point at output port
58 0040 EE 0-Jr DX,AL :Turn on heater
59 004E EB 08 •90 JNP EXIT
60 0051 C6 06 0000e 01 DONE: NOV 'IIMEHI, 0111 ;FaLL through value for time high
61 0056 C6 06 0000e 7F NOV TINELO, 7FH ;Long off value for time Low
62 OOSB 5* EXIT: POP DX ;Loop serviced - return to
63 005C 59 POP CX interrupt service procedure
64 0050 5B POP BX
65 005E 58 POP AX
66 005F 90 POPE
67 0060 CB RET
68 0061 LOOPO ENDP
69
70 ;DUIIHY PROCEDURES FOR OTHER LOOPS INSERTED HERE
71 0061 LOOP1 PROC FAR
72 Instructions for this Loop
73 0061 CS RET
74 0062 LOOPI ENOP
75
76 0062 LOOP2 PROC FAR
Ti Instructions for this Loop
78 0062 CB RET
79 0063 L2 EWDP
80
81 0063 LOOP3 PROC FAR
82 ;Instructiols for this loop

83 0063 CB RET II
84 0064 100P3 ENOP
85
86 0064 LWP4 PROC FAR
87 ;Instructions for this Loop
88 0064 GB RET
89 0065 LOOP4 ENDP
90
91 0065 LOOPS PROC FAR
92 ;Instructions for this loop
93 0065 GB RET
940066 LOOP5 ENDP
95
96 0066 LOOP6 PROC FAR
97 ;Instructions for this Loop
98 0066 CB RET
99 0067 LOOP6 ENDP
100
101 006? LtYJP7 PROC FAR
102 ;Instructions for this Loop
103 0067 CS RET
104 0068 LOOP? ENDP
105
106 0068 CE ENDS
107 END

IC)

;8086 I4LJLE 4 PROCEDURES: F10-350.ASM


2 ;ABSTRACT : Module 4 contains the service procedures needed by the ioop modules
3
4 PUBLIC DISPLAY IT, ADREAD, BIIICVT Make prdcedures availabLe to other modules
5
6 0000 DATA SEGMENT WORD PUBLIC
7 0 1 2 3 4 5 6 7
8 0000 3F 06 55 4F 66 60 70 + SEVEN_SEC OB 3FH, 06H, SBH, 4FH, 6611, 6011, 7DH, 07H
9 07

FIGURE 10-35 (Continued)


ANALOG INTERFACING AND INDUSTRIAL CONTROL 327
10 8 9 * b C d F
11 0008 77 6F 77 7C 39 SE 79. 08 7FH, 6FH, 77K, 7C11, 39K, 5tH, 79K, 71K
12 71
13 0010 DATA ENDS
14 0000 C00E SEGMENT lD PUBLIC
15 ASSL14E CS:C00E, DS:DATA
16
17 ;8O86 PROCEDURE DISPLAY_IT
18 ;ABSTRACT: Displays a 4-digit hex or BCD nuer on tEDs of the SDK-86
19 ;INPUTS; Data in CX, control in AL.
20 Al. 00K data displayed in data-field of LED5
21 AL 0011, data displayed in address field of tEDs.
22 ;PORTS: Uses none
23 ;PRQCEDURES:Use g none
24 ;REGISTERS: Saves alt registers and flags
25
26 0000 DISPLAY_IT PROC NEAR
27 0000 PIJSHF ;Save flags
28 0001 1E PUSH DS ;Save calLer's registers
29 0002 50 PUSH AX
30 0003 53 PUSH BX
31 0004 51 PUSH CX
32 0005 52 PUSH DX
33 0006 88 0000s NOV BX, DATA ;Initialize DS as needed for procedure
34 0009 8€ 08 NOV os, ax
35 0008 BA FFEA NOV DX, OFFEAK ;Point at 8279 controL address
36 000E 3C 00 ClIP AL. 00K ;See if data field required
37 0010 74 0$ JZ OATFLD ;Yes, load control word for data field
38 0012 00 94 NOV AL, 9411 ;No, Load address-field control word
39 0014 EB 03 90 JMP SEND ;Send control word
40 0017 80 90 DATFLD:H0V AL, 90K ;Load contro' word for data field
61 0019 SEND: 001 DX, AL ;Send control word to 8279
42 001* SB ODOUr NOV OX, OFFSET SEVEN_SEG ;Pointer to seven-segment codes
43 0010 BA FFE8 NOV DX, OFFEBH ;Point at 8279 display RAN
44 0020 BA Cl NOV AL, CL ;Get low byte to be displayed
45 0022 24 OF AND- AL, OFH ;Mask upper nibble
46 0024 07 XLAT8 ;Transtate Lower nibble to 7-seg code
47 0025 001 DX, Al ;Send to 8279 display RAM
48 0026 BA Cl NOV AL, CL ;Get low byte again
49 0028 81 04 NOV CL, 04 ;Load rotate count
50 002* 02 CO ROt AL, CL ;Nove upper nibble into Low position
51 002C 24 OF AND AL, 0tH ;Mask upper nibble
52 002E 07 XLATB ;TransLate 2nd nibble to 7-seg code
53 002F EE 001 DX, AL ;Send to 8279 display RAN
54 0030 BA C5 NOV . AL, Cli ;Get high byte to translate
55 0032 240F AND AL, OFH ;Mask upper nibble
56 0034 07 XLAT8 ;Iranslate to 7-seg code
57 0035 EE 001 DX, AL ;Send to 8279 display RAM
58 0036 BA C5 NOV AL, Cli ;Get high byte to fix upper nibble
59 0038 02 CO ROL AL, CL ;Nove upper nibble into tow position
60 003* 24 OF AND AL, OFH ;Mask upper nibble
61 003C 07 XLATB ;Translate to 7-seg code
62 0030 EE 001 DX, AL ;T-seg code to 8279 display RAM
63 003E 5A POP DX ;Restore alL registers and flags
64 003F 59. POP CX
65 0040 58 POP OX
66 0041 58 POP AX
67 0042 iF POP DS
68 0043 90 POPF
69 0044 C3 RET
70 0045 DISPLAY IT ENOP
71
72 ;8086 PROCEDURE AD READ
73 ;ABsIRAcJ: Controls A/D converter
74 ;PORTS: Uses Port P2A for input from A/D
75 p ort P28, bit 7 = heater, bit 5 start conversion
76 bit 4 = ALE bits 2,1,0 channel address
T7 Port P2C bit 0 = end of conversion
78 ;INPUTS: Charv,el address for AID in BL
79 ;00TPUTS: AID data in AL
80 ;REGISIERS: DESTROYS AL & 81
81
82 0045 A_O_READ PROC NEAR

FIGURE 10-35 (Continued)

328 CHAPTER TEN


830045 9C PU S H F
840046 52 PUSH DX
85 0047 80 80 NOV AL, 8011 ;Cootroi for heater off
86 0049 0* C3 OR AL, BL ;C.ine with charnel address
87 004B 0* FFFA NOV DX, OFFFAH ;Point at P28, output port
88 004E EE OJI DX, AL ;send
89 004F BO 90 NOV AL, 9011 ;Send ALE, keep heater on
90 0051 0* C3 OR AL, BL ;Keep chamet address on
91 0053 EE 001 OX, AL
92 0054 00 BO NOV Al, 08014 ;Send Start of conversion
93 0056 OA C3 OR AL, BL ;Keep charnel address on
94 0058 EE DX, AL
95 0059 80 80 NOV AL, 8014 ;Turn off ALE and Start
.96 0058 0* C3 OR AL, BL ;Keep channel address
97 0050 EE DX, AL
98 005E 0* FFFC NOV DX, OFFFCH ;Point at port P2C
99 0061 EC EOCL: IN AL, DX ;Wait for end of cdnversion
100 0062 00 08 8CR AL, 01 to go low
101 0064 72 FB JC EOCL
102 0066 EC EOCH: IN AL, DX ;Wait for end of conversion
103 0067 DO 08 8CR AL, 01 to go high
104 0069 73 FB JNC EOCII
105 0068 BA FFF8 NOV DX, OFFF8H ;POint at port P2*
1060066. EC IN AL, DX ;Read data from AID
107 006F 5* POP DX
108 0070 99 POPF
109 0071 C3 RET
110 0012 A D READ ENDP
111
112 ;8086 PROCEDURE BINCVr
113 ;ABSTRACI: ConvertS 8-bit binary n&jther in AL to packed BCD equivalent in AL
114 ;INPUTS: AL - 8-bit binary ruTer
115 ;00TPUTS: AL - packed BED result
116
117 0072 BINCVI PROC NEAR
118 0072 9C 'PUSH F ;Save registers and fLags
119 0073 51 PUSH CX
120 0074 B4 09 NOV *11,09K ;Bit counter for 8 bits
121 0076 BA C8 NOV CL, Al ;Save binary in CL
122 0078 85 00 NOV CII, 00 ;Ctear CII for use as buffer
123 007A 32 Co CNVT2: XOR AL, AL ;Ctear AL and carry
124 007C FE CC DEC AN ;Decrenent bit counter
125 007E 75 03 JNZ GO_ON ;Do alt bits
126 0080 EB OC 90 JMP HIE ;Done if *11 down to zero
127 0083 DO 01 GO_ON: RCL CL,1 ;HSB from CL to carry
128 0085 8AC5 NOV AL, CII ;Hove BCD digit being built to AL
129 0087 12 CO AOC AL, Al ;Doubte Al and add carry from CL shift
130 0089 27 OAA ;Keep result in BCD form
131 008* 8* E8 NOV CII, AL ;Pit back in CH for next time through
132 008C EB EC ,iNP CNVI2 ;Continue Conversion
133 008E BA CS HIE: NOV AL, CII ;BCD in AL for return
1340090 59 POP CX ;Restore registers
135 0091 90 poet
136 0092 C3 RET
137 0093 BINCVT ENDP
138
139 0093 C00E ENDS
140 END
Id)
FIGURE 10-35 (Continued)

these operations in detail, SO we won't dwell on them which allow the user to change set points, stop a process.
here. Also In the mainline we initialize some process or examine the value of process variables at any lime.
variables. We will explain these initializations later when Due to severe space limitations, we can't show here the
they will have more meaning. implementation of the keyboard interrupt procedure.
After enabling the 8086 INTR input with an STI but we will show you how the timer interrupt procedure
instruction, the program then enters a loop and watts and the example PID loop procedure work.
for an interrupt from the user via the keyboard, or
an interrupt from the timer. The keyboard-interrupt THE CLOCK.TICK IN1TERRPT HANDLER
procedure would normally contain a command recog- As we said before, the 8254 is programmed to send a
nizer and subprocedures to implement commands pulse to an interrupt input of the 8259A every millisec-

ANALOG INTERFACING AND INDUSTRIAL CONTROL 3?Q


ond When a clock Interrupt occurs, execution goes TIMELO. At start-up the maihitne program initializes
to the CLOCK_TICK procedure. At the start of this TIMEHI and TIMELO to tJlH, so that the first time the
procedure, we simply decrement an interrupt "tick LOOPO procedure is called both of these are decremented
counter" kept In a memory location called COUNTER. to 0. and execution falls through to the A/D conversion
In the Initialization, this counter was set to 20 decimal procedure. This is done to get a temperature value which
or 14H. If the counter is not down to 0. execution is can be compared with the set-point value. The difference
simply returned to the wait loop in the mainline. If the between the set-point value and the actual temperature
tick counter Is now down to 0, the clock-tick Counter is will be used to set the value of TIMEHI and TIMELO for
reset to 20. and one of the loop procedures is called to the next time the LOOPO procedure is called:
service the next loop. It is important that this clock- The part of the program which controls the AID
tick procedure be reentrant because if one of the loop Converter is writlen as a separate procedure so that it
procedures takes more than the time between clock ticks can be used in other PID loops. The A/D Converter has
II ms), the CLOCK_TICK procedure will be reentered eight input channels, so as part of the interadion with
before its first use is completed. The procedure is made the A/D converter, we have to tell it which channel to
reentrant by pushing all registers used in the procedure digitize. The number of the A/D channel that we want
and by immediately resetting the clock-tick counter to to digitize is passed to the A/D Conversion procedure in
20. If a loop procedure takes longer than 1 ms and the the AL register. The procedure then sends out this
clock_tick procedure is called again, the tick counter channel number to the A/D converter and generates the
will be decremented by 1 and execution returned to the control waveforms shown in Figure 10-34. Since the
interrupted loop procedure. timing for these waveforms is in the range of microsec-
Selecting one of the loop procedures Is an example onds, we chose to generate the waveforms with program
of the CASE or nested IF-THEN-ELSE programming instructions rather than use an 8255A in handshake
structure described in Chapter 3. To implement this mode. The binary value for the temperature is returned
structure, we use a powerful programming technfque in AL.
called a call table. Here's how it works. Upon return, the binary '.'a]ue of the temperature is
The starting addresses of all the loop procedures are stored in a memory location called CURTEMP for future
put in a table called LOOP_ADDR_TABLE. as shown at reference. For testing purposes, we wanted to display
the start of module 2 in Figure 10-35b. The names the temperature on the address fIeld of the SDK-86
LOOPO. LOOPI, L00P2. etc.. are the names of the display. To do this, the binary value for the temperatpre
procedures to service each of the loops. Since these is converted to a BCD value using a reduced version of
procedures are FAR, the DD directive Is used. to reserve the binary-to-BCD procedure from the scale program
space for the IP and CS of each. When this program earlier in this chapter and the dispia routine from
module is linked and loaded into memory, the instruc- Chapter 9.
tion pointer and code segment addresses for each of the After the current temperature is displayed, it is com-
loop procedures will be loaded into this table. pared with the set-point temperature to see if the heater
To point to the desired loop procedure address in needs to be turned on. If the temperature is at or above
the table, we use a variable called LOOPNUM. During the set point. TIME1-i1 is loaded with fall-through value
initialization LOOPNUM is loaded with OOH. When it is and TIMELO is loaded with a large number.
time to service the first loop, the value in LOOPNUM is If the temperature is hlm the set point, we call a
loaded into HX The CALL DWORD PTR LOOP_ADDP_ procedure. DUTYLCY2LL. d computes the correct
TABLE IBXI instruction then gets the address of the values for TIMEHI and TIMELO based on the difference
LOOPO procedure from the call table and goes to that between the set point and the current temperature. In
address. For the first access to the table, BX is zero, so a more critical application, a complex PlO algorithm
the first address in the table is used to call LOOPO might be used for this procedure. For our example here.
procedure. however, we have used simple proportional feedback, To
When execution returns from the LOOPO procedure further simplify the calculations, a fixed value of 4 was
to the Interrupt handler, we add 4 to , the LOOPNUM. used for TIMEHI. The thinking for the value of TIMELO
This is done so that LOOP! will be called the next time then goes as follows.
the tick counter is counted down to zero. LOOPNUM If the difference in temperature is large, then TIMELO
must be incremented by 4 because each address in the should be small so the heater is on for a longer duty
call table uses 4 bytes. When all loops have been serviced, cycle. If the difference in temperature is small, then the
LOOPNUM is set back to 0 so LOOPO will be serviced value of TIMELO should be large so the heater has a
again. Now let's look at the actual temperature-control short duty cycle. Experimentally we found that a good
loop. first approximation for our system was ldifference in
THE TEMPERATURE-CONTROLLER PROCEDURE temperature) < TIMELO 100 decimal 164H). For ex-
ample, If the difference in temperature is 20° (I 4H), then
As we said previously, the amount of heat output by the 64R/141-I gives a value of 5 for TIMELO. The values
heater is controlled by the duty cycle of a pulse waveform for TIMEHI and TIMELO are returned in their named
sent to the solid-state relay. The time on for the output memory locations. Upon return to the main loop proce-
waveform to the solid-state relay Is determined by count- dure, we send a control word which turns on the heater.
ing down a value called TIMEHI. The time off for this Execution then jumps to EXIT.
waveform is determined by counting down a value called When execution returns to loop 0 again after 160 ms.

330 CHAPTER TEN


(s, tested and debugged, as we have described' previously.


[S % is - Likewise, the best way to develop the hardware is in small
parts which can be individually tested and debugged. To
6oI— —' j- give you a specific example of how to do this, here's how
we developed the SDK-86-basedJ factory-control system
described in the preceding section.
- MICROCOMPUT The basic SDK-86 does not have a timer to produce
: :L : THERMOSTAT CON TROL
SETPOINT 1-kHz clock ticks or a priority interrupt controller to
30 hane keyboard and clock-tick intepts. Therefore,
we first added these two devices and - some address
15 30 45 1H 2H 3H
MIN MIN MIN decoder circuitry to the SDK-86, as shown in Figure 8-
TIME
14. To tet this circuitry we used a short program which
FIGURE 10-36 Temperature versus time responses for wrote a byte to the starting address for the timer over
thermostat-controlled and microcomputer-controlled and over again. We ran this test program with an
heaters. emulator such as the Applied Microsystems ES1800
shown in Figure 3-17. With the program running, we
used a scope to check if the CS input of the timer was
TIMEHI will be decremented. if TIMEI-Il is not yet dowi getting asserted. It was, so we knew that the address
to 0 after the decrement, then we simply adjust a few decoding circuitry was working correctly.
things and return, If TIMEHI Is 0 after the decrement, We then connected the 2.45-MHz PCLK signal to the
the heater is turned off, and TIMELO is decremented. clock inputs of all three timers in the 8254 and wrote
TIMELO is then decremented every time loopo is serviced the instructions needed to initialize the three timers for
(every 160 ms) until TIMELO reaches 0. When TIMELO I -kHz square-wave outputs. Even though we need only
gets counted down to 0. a new A/D conversion is done, one timer here, it was very little additional work to check
and a new feedback value for TIMELO is calculated. the other two for future reference. Hurrah, the timers
An important point here is that the part of the program worked the first time; now on to the 8259A priority
that determines the feedback is separate from the rest interrupt controller (PlC).
of the program, so it can be easily.altered without Testing the 8259A was a little more complex because
changing the rest of the program. All that needs to be we had to provide an interrupt signal, initialize the
changed in this procedure is the value of TiMEI-il. the 8259A. initialize the interrupt vector table in low RAM,
value of TIMELO, and the rate at which these change in and provide a location for execution to go to when the
response to a difference in temperature to produce PlC received an interrupt. We used the 1-kHz clock tick
proportional, integral, and derivative feedback control. from the timer as the interrupt signal to the 8259A.
For 8259A initialization and the interrupt jump table
TEMPERATURE CONTROLLER RESPONSE initialization, we used the instructions in the mainline
The dotted line in Figure 10-36 shows the temperature program in Figure 10-35. For the test-interrupt proce-
versus time response of our system with traditional (lure, we actually used a real-time clock and display
thermostat control, which is often called on-off control procedure that we developed for examples in previous
or "bang-bang" controL As you can see, with thermostat chapters. We used these so that we could see if the
control the temperature initially overshoots the set point interrupt mechanism was working correctly by watching
a great deal and then oscillates over a wide range around the displays on the SDK-86 count off seconds. This
the set point. The solid line in Figure 10-36 shows the again shows the advantage of writing programs as
response of the system operating with our temperature separate, reusable modules. Note in the program in
controller program. The initial overshoot was caused by Figure 10-35 that we initialize the 8259A before we
the large thermal inertia of the hot plate we used. The inivalize and start the timer. When we first wrote a test
overshoot and the residual error of about l could be program to test an 8259A and an 8254. we did this in
eliminated by using a more complex feedback algorithm. the reverse order. When we ran the test program with
This example should make you aware of the advantages the emulator, the system would accept only one Interrupt
of computer feedback control. and then hang up. We did a trace with the emulator and
found that execution was returning from the interrupt
präcedure to the WAIT loop in the mainline program
DEVELOPING THE PROTOTYPE OF A properly, but it was not recognizing the next interrupt.
MICROCOMPUTER.I3AsED INSTRUMENT Careful reading of the 8259A data sheet showed us that
we had to initialize the 8259A before we started sending
The first step in developing a new instrument is to very it interrupt signals, or it would not respond correctly to
carefully define exactly what you want the Instrument the nonspecific EOI command that we used at the end
to do. The next step is to decide which parts of the of the interrupt procedure to reset the 8259A's in-service
instrument you want to do in hardware and which parts register.
you want to do In software. You then earl decide how After the interrupt mechanism was working correctly,
you want to do each of these. we wrote the interrupt procedure which implements the
For the software, you will break the overall program. decision structure showu in Figure lO-32b. Initially we
ming job down Into modules which cn be Individually made all eight loops dummy loops to test the basic

—44
ANALOC NT[RFACING AND NDUSTRIAL CONTROl 331
structure. By inserting breakpoints with the emulator. Smart machines such as these usually use specially
we were able to see whether execution was getting to designed microprocessors called embedded controllers
each of the eigIt loops. When all this was working. Instead of a general-purpose microprocessor such as
we went on to build and test the temperature-control the 6086 which we usii in the scale and the factory
section. controller examples. The main differences of these em-
For the temperature-control section. we first built the bedded controlled microprocessors is that they have
analog circuitry and tested it. Then we wrote a small additional functions included on the chip with the basic
program to read the temperature from the A/I) converter CPU and they have special instructions for working with
and display the result on the SDK-86 displays. Initially individual bits in a word. In the following sections
then, the loop 0 procedure simply read in the tempera- we give you an overview of a few common embedded
ture, displayed it in binary (hex) form, and returned. controller families. Consult the appropriate Intel hand-
This worked the first time, so we went on to add the books for additk,nal details when you need them.
binary-to-BCD conversion routine and run the result
with the emulator. This was a previously written and
tested module, and when it was added, the result worked The Intel 8051 Embedded Controller Family
fine. Figure iO-37a shows a block diagram of a basic 8051
Next we added a couple of instructions to turn the family controller and Figure l0-37b summarizes some
heater on during one execution of loop 0 and turn the of the features of the members of the family. These
heater off during the next time through loop 0. We then controllers are 8-bit units which can address up to 64
used an oscilloscope to check that the solid-state relay Kbytes of memoxy. All of the family members have some
was getting turned on and off correctly. RAM on the chip, and different members of the family
Finally, we added the actual duty cycle and control have some ROM or EPROM also Included on the chip.
Instructions and sat back waiting for the system to heat As shown in Figure lO-37b. members of this family
up a big container of water for tea. also have programmable timers and priority interrupt
The actual development cycle will obviously be some- controllers Included on the chips.
what different for every instrument developed. The main 11 an application does not require any memory other
points here are to develop and test both the hardware than that included on the chip, then all four parts are
and the software in small modules. To speed up the available for use as input or output ports. If additional
debugging process, take the time to learn to use all or memory is needed, then port 0 and port 2 can be
most of the power of the emulator and system you are programriied to function as a multiplexed address/data
working with. bus. When used with extern memo two lines on port
3 are used to generate the RD and WR signals.
The devices in the 8051 family also contain serial
ROBOTICS AND EMBEDDED CONTROL data interface circuitry. When this feature is used.
In recent years the term robot has become a "buzzword' two pins on port 3 function as the RxD and TxD
In the media and in many people's minds. Science fiction lines. Figure l0-37c shows the special uses of the port
movies have helped us form an image of robots as 3 pins.
mobile, rational companions. Robots, however, have
many forms, and In operation they are simply a combina- The Intel 8096 Embedded Controller Family
tion of feedback control systems such as we described
In the previous section. This Is why we have not Included Figure l0-38a. p. 334, shows a block diagram for the
a chapter dedIcated Just to robotics. The controller for Intel 8096 family of 16-bit microcontrollers. One of the
the Rhino robot arm shown In Figure 9-42. br example. most important features of the members of this family
uses optical encoders to detect the position of Its differ- is the 232-byte register file and the register ALU (RALU)
ent Joints, motors (actuators) to move each Joint to a shown in the center of Figure lO-38a. Instead of using
desired position, and a microcomputer to control the a single accumulator register as the 8086 does, the ALU
motors based on feedback from the sensors. Large in the 8096 famil, devices can perform most operations
Industrial robots such as those that weld or spray-paint on any of the registers in the register file. This structure
cars may also use tactile or visual sensors, and the is referred to as register-to-regIster architecture. The
actuators maybe hydraulic or pneumatic, but the control large number of registers makes it possible to have many
principle is the same, A microcomputer or several micro- data bytes in registers where they can be very quickly
computers use feedback from the various sensors to accessed. Also, since tire contents of any register can be
control one or more actuators. output to a port, the 110 'bottleneck" of 8086-type
Most of you have probably used some simple robots processors Is elimInated.The 8086, remember, requires
around your home without realizing it. One example Is that data be output from or input to AL/AX.
an electric garage door openei which starts to open or Other features found in all the 8096 family devices
close when you tell it to and then stops when a sensor are five ports which can be programmed for use in a
indicates that it is open or closed as desired. Common variety of ways. In addition to their use as standard
household examples of microcomputer-controlled robots ports. ports 3 and 4 can be used as a multiplexed
are a microwave oven with a temperature probe, a address/data bus to access external memory and ports.
programmable sewing machine, a remote-control Stereo Port 2 can be programmed for use as a serial port and!
system. etc. or an output for the pulse-width-modulated signal. The

- 332 CHAPTER TEN


11
E*TEB$IAL
N1IRUP1S

INTRUPT I 25 Vylts
TR4cB I

Th4ER 0
cOuNTtR
JPuTs

Iin
osc Bus SLRIAL
4 I/O PORTS
PORT


II 1*0 XD
P0 P2 Pt PS
ADORESS/DATA
270251-I

(a)

Device ________
___________ intirnal Memory
_______ Tkn.j,/
Progrm o.t. Event Counter,
8052AH OKx8AOM 256xORAM 3*16-Bit 6
OO51AH 4Kx8R0M 1288 RAM 2*16-Bit
8051 4Kx$ROM 5
I28xBRAM 2*16-Bit 5
8032AH none 258x8RAM 3*16-Bit
8031AH 6
flOfl 128*0 RAM 2*16-Bit 5
8031 none 128X8RAM 2*16-Bit
87511-I 4Kx8EPROM 5
128x6flAM 2*16-Bit 5
875lH-8 4Kx8EPROM I28x8flAM 2*16-Bit 5
fbi
Poll 3 also serves the functions of va41ous spec*al
features ot the MCS-51 Family, as listed below Figure 10-38b shows the numbering for the different
port
members of the 8096 family so you can see the options
pin AJt.rnativ. Function available in different parts. As you can see, devices are
P3.0 RXD (serial input poll) available with 8 Kbytes of internal EPROM. 8 Kbyte, of
P3.1 TXO (serial output port) Internal mask-programmed ROM. or no internal ROM.
P3.2 IT (external Intemjpt 0) Also note that some members of the 8096 family contain
P3.3 INTl (external lnternt 1) a 10-bit successive-approximation AID converter. As
P3.4 TO crner 0 external input) shown in Figure l0-38c. this AID has a sample-and-hold
P3.5 Ti(Thter I external Input)
P3.6 WP (external data memory wflte trobe) and an 8-input analog multiplexer on its input. This
P3.7 (external data memory read strobe) allows it to digitize any of eight input signals under
program control.
Ic) The 8096 instructions are designed for fast operations
FIGURE 10-37 8051 family. (a) Block diagram. (b) Family on registers and for easily working with individual bits
features, (c) Port pin uses. (Intel Corporation) in data words. The 8096 also has multiply and divide
instructions. From the scale and temperature controller
examples earlier in the chapter. you should see that
these features optimize the devices for use in hardware
PWM signal is software programmable and cart be used control applications.
to control the speed of a small motor or the duty cycle
of a heater, as we described earlier In the chapter.
The 8096 family devices also have two programmable The 80186 and 80188 Microprocessors
counters and 2) hardware and software Interrupt types. The 8051 and 8096 embedded controllers we described
Note that both the clock generator and the baud-rate lit the preceding sections have different Instruction sets
generator are included in the basic architecture. and vety different architectures from the 8086, which
ANAI.OG INTERFACING AND INDUSTRIAL CONTROL 333

POWE6 FREQUENCY
VRO AHGNO DOWN REFERENCE

Ow-cHP
EPRO676xeH
nJ
I

232 tuENOfi
________________________________
BYTE GSTER SGNAI.S
CONL
IWATcH000I. u :iiiwi

klux
Flu
___ I I
_________ __________ II
F
•l I I 6
1
•POQT3

: _________
• OATA
Jeus
Put.St SERIAL IJ_/IADOR
wiDTh PORT ;—) RT4
SPEED
I/O
P21

PORT 0 PORT I PORT 2 HSI HSO


ALT FUNCTIONS
270280-1
(a)

Tha MCS-96 Fomily Nonwi,cI.W


WitIoui A/D With A/D

p1, C8095BH Ceraric DIP


ROMI.,, P8095BH - Plootic DIP
8O9XBH
A80968H - Cerat,jc PGA A80978H Ceran,ic PGA
N80969H PLCC N8097BH - PLCC
C83958H Ceramic DIP
ROM P8395811 Plastic DIP
839XBH
68 PIn A8396B1-4 CerarYTc PGA A83978H Cermic PGA
N8396BH - PLCc N83978H PLCC
48 Pin C87958H - Ceramic DIP
EPROM
879XBH 68 Pn
A87968H Cremic PGA A8797BH Ceramic PDA
R87968H Ceramic LCC R87970H- Ceramic LCC
(b)

2702a6- 13
lc(

FIGURE 10-38 80% family. (a) Block diagram. (b) Family features.
334 (C) ND converter diagram. (Intel Corporatiol
INT3/INTAI
f
TMROUT1 TMAOUTO
CLKOUT GNO TMR IN TMR IN

PROGRAMMABLE 1
TIMERS
0 1 2
16-BIT MAX COUNT L'\
ALL) PROGRAMMABLE REGISTER B
INTERRUPT MAX COUNT
CONTROLLER REGISTER A
CLOCK
NE R AT 16-BIT
GENERAL I
1 i CONTROL REGISTERS
PURPOSE I I CONT AOL 16-BIT
REGISSJ j REGISTERS COUNT REGISTER

_________ ORGO
DRO1
(PROGRAMMABLE
I I DMA UNIT

CHIP-SELECT
UNIT RCE
SR DY - _________
AR))? BUS INTERFACE l6-BIT DESTINATION
rEST UNIT SEGMENT
HOLD REGISTEA5 PROGRAMMABLE
HLOA 6-BYTE CONTROL
4ES PREFETCH REGISTERS

UCS
I +5D V
LCS
L6 RD ADO- A16/S3
A015 A19/S6
01/N BHE/S7

FIGURE 10-39 60186 Internal block diagram. (Intel Corporation)

INT3/INTAI as well as an NMI interrupt input- If the


we have used for examples In this book. The 80186
four INT inputs are programmed in their internal mode,
and 80188 are 16-bit processors commonly used for
then a signal applied to one of them will cause the 80186
embedded control applications, and they have basically
to push the return address on the stack and vector
the same instructions set as the 8086. However, as
directly to the start of the interrupt service2dure
shown in Figure 10-39. they contain some peripheral
for that interrupt. The INT2/INTAO and INT3/INTAI pins
functions as well as a CPU. can be programmed to be used as interrupt Inputs,
The architecture and instruction Set of the 80188 are
or they can be programmed to function as interrupt
identical to those of the 80186 except that the 80188
has only an 8-bit data bus instead of the 16-bit data bus acknowledge outputs- This mode Is used to interlace
with external 8259As. The interrupt request line from
that the 80186 has. With this in mind, we will use the
an external 8259A Is connected to. for ple. the
80186 to represent both the 80186 and the 80188 in
80186 INTO input, and the 80186 INT2/INTAO pin is
our discussions here.
The 80186 has the same bus-interface unit and execu- connected to the interrupt acknowledge input of the
8259A. When the 8259A receives an interrupt request.
tion unit as the 8086 which we discussed previously. so
it asserts the INTO input of the 80186. When the 8259A
there is nothing new there for you. Unlike the 8086,
receives interrupt acknowledge signals from the INT2J
however, the 80186 has the clock generator built in so
INTAO pin. its sends the desired interrupt type to the
that all you have to add is an external crystal. Also note
that the 80186 does not have a pin labeled MN/MX. The 8018600 the data bus.
Next to look at in the block diagram is the built-in
80186 is packaged in a 68-pin ieadless package. so it
address decoder, referred to in the drawing as the chIp
has enough s to send out both the minimum-mode-
type signals RD and WR and the SO—S3 status signals select unit. This unit can be programmed to produce an
which can be connected to external bus controller lCs active low chip select signal when a memory address in
the specified range or a port address in a specified range
for maximum-mode systems. Now lets look at the four
peripheral chip function blocks in the 80186. is sent out. Six memory address chip select ,inalS are
avaIlable LCS. UCS, arid MCSO through MCS3. The
First is a priority interrupt controller which has up to
four interupt inputs. INTO. INTl. INT2JINTAO. and tower-chip select signal. LCS. will be asserted by ad-

ANALOG INTERFACING AND INDUSTRIAL CONTROL 335


dresses between 00000H and some address which you Note 186, Introduction to the 80186 MIcroprocessor,
specify in a control word. The specified ending address helpful.
can be anywhere between 1K and 256K. The highest
address that will assert the upper-chip select signal, The 10 add itinjia] instructions that the 80186 has are
as follows:
WCS. is fixed at FFFFFH. The lowest address for this
block of memozy is again programmable by some bits ENTER - Enter a procedure
you put in a control word. The size of the upper memory LEAVE - Leave a procedure
block can be anywhere between 1K and 256K. FInally. BOUND
there are four middle-chip select lines. MCSO through - Check if an array Index in a
MCS3. Each of these four Is asserted by an address in register is in range of array
INS - Input string byte or string word
a block of memory in the middle range of memory. Both OUTS
the starting address and the size of the four blocks can - Output string byte or string
Word
be specified for this middle-range block. The specified PUSHA
size of blocks can be anywhere from 2K to 128K. - Push all registers on stack
PUPA Pop all registers off stack
In addition to producing memory chip select signals. PUSH immediate
the 80186 can be programmed to pice up to seven - Push Immediate number on
pheraI chip, stack
ct signals on Its PCSO through PCS4. IMUL destination
PCS5/A I, and PCS6/A2 pins. You program a base address - Immediate X source to destina-
register, Source, tion
for these [/0 addresses in a control word. PCSO will be immediate
assexted when this base address is output during an IN 511111/ROTATE
or an OUT instruction. The other PCS outputs will be - Shift register or memory con-
destination, tents specified immediate num-
asserted by addresses at intervals of 128 bytes above the Immediate
base address. ber of times
Now lers look at the programmable DMA unit in the
80186. As you can see from the block diagram in Figure
10-39. the DMA unit has two DMA request Inputs, DRQO
The 80960 Embedded Controller
and DRQI. These Inputs allow external devices such as The 80960 family controllers are 32-bit devices which
disk controllers, CRT controllers, etc. to request use of are an evolutionary step up from the 8096 family. They
the microcomputer address and data bus so that data are built with a register-to-register architecture for fast
can be transferred directly from memory to the periph- processing, and they contain code and data caches. In
eral or from the peripheral to memory without going Chapter 11 we explain how these caches als help speed
through the CPU. In the next chapter we show you the up program execution.
details of how a DMA controller manages this transfer. The devices in the 80960 family also contain a floating.
For each DMA channel, the 80186 has a full 20-bit point processor which performs mathematical opera-
register to hold the address of the source of the DMA tions on 80-bit floating-point numbers, In the next
transfer, a 20-bit register to hold the destination ad- chapter we show you how a floating point processor
dress. and a 16-bit counter to keep track of how many such as this works.
words or bytes have been transferred. DMA transfers
can be from memory to memory, from 1/0 to 110. or
between [/0 and memory.
Finally, let's look at the three 16-bit programmable DIGITAL SIGNAL PROCESSING
counter/timers in the 80186. The inputs and outputs of AND DIGITAL FILTERS
counters 0 and I are available on pins of the 80186. The term digital signal processing, or DSP.
These two counters can be used to divide down the is a very
general term used to describe any system which takes
frequency of external signals, produce programmed
width pulses, etc. - just as you do with the counters in samples of a signal with an A/D converter, processes
an 8254. You can also internally direct the processor the samples with a microcomputer, and outputs the
computed results to a D/A converter or some other
clock to the input of one of these counter inputs by
device. The process-control system and temperature
clearing the appropriate bit in a control word. The input
controller we described carrier in the chapter is one
of the third number in the 80186 is Internally connected
to the processor clock. example of digital signal processing. Other applications
of DSP include antiskid braking and engine-control
As you can see from the preceding discussion, the
systems on automobiles, speech recognition and synthe-
80186 contains many of the peripheral chip functions
needed in a medium . complexity microcomputer system sis systems, and contrast enhancement of images sent
back from satellites and planet probes. When most
In order to use these integrated peripherals, you have
people think of DSP. however, the thought that probably
to initialize them just as you do external peripherals. If
comes to mind first isa special one called a digitalfihter.
you have to work with an 80186. you can find the
formats for these words in the 80186 data sheet, and A section at the start of this chapter showed how op
work out the control words you need for your particular amps can be used to build high-pass and low-pass filter
circuits. In this section of the chapter, we show how
application on a bit-bybit basis. just as you do for the
filtering of a signal can also be done by taking samples
separate peripherals. You may also find intel Application
of the signal with an AiD converter, performing mathe-

336 CHAPTER TEN


matical operations on the samples with a microcom-
puter. and outputting the results to a 1)/A converter. fo

'l _
This digital filter approach can easily produce a filter
response which is difficult, if not impossible, to produce "s, 3fo
with analog Circuitry. The digital approach has the
further advantage that the filter response can be changed V0
'\., Sb
under program control.
To most people it is not Intuitively obvious how an
"s.d ito
A/D converter. microcomputer. and 1)/A converter can
produce the same effect on a signal as. for example, an
RC low-pass filter. Before we can show you how digital
filters work, we need to review some basic signal relation-
ships and analog filter characteristics.
iv:-n-n--n-n- (a) (b)
-

*10
Time-Domain and Frequency-Domain
View of a Square Wave
There are two ways of producing or describing a wave-
to
form such as the square wave. One way is with a circuit
such as that in Figure 1 O-40a. If the switch is repeatedly
flipped up for one-half the period and down for one-half
the period, the output waveform will be a square wave —10
centered around 0 V. This way of producing or describing 3.33
a square wave is referred to as the time-domaf it method.
310 C
The second way of producing a square wave of a given
frequency is by adding together a series of sine-wave —3-33
signals which have Just the right amplitude and phase
relationships. This method of producing or describing
a square wave is called the frequency-domain method.
Figure lO-40b shows a circuit which generates a square A £4! A
wave by adding sine-wave signals.
Remember from basic electric circuits that when
voltage sources are connected in series, the output
voltage at any time is the sum of the individual voltages.
The lowest-frequency sine-wave signal added here has
the same frequency as the desired square-wave signal.
Added to this is a signal with a frequency 3 times the
frequency of the fundamental frequency, a signal with
a.frequency 5 times the frequency of the fundamental
frequency, a signal with a frequency 7 times the funda-
mental frequency. etc. These multiples of the fundamen-
tal frequency are called harmonics. As we said before.
Cd)
the added harmonics must have the right amplitude
and phase relationships to produce a square wave when
added. Figure 1O-40c shows the required phase and
relative amplitude relationships.
To help you further visualize this addition process.
Figure l0-40d shows the resultant wave1om that will
be produced by adding Just the fundamental frequency
and the third harmonic. It is somewhat difficult to show.
but the more harmonics you add, the more the resultant 0
waveform approaches. a square wave.
Ce)
Mathematically, the equation for this square wave can
be expressed in terms of a fundamental frequency and FIGURE 10-40 (a) Time-domain method of producing a
harmonics as square wave. (b) Frequency-domain method of
producing a square wave. (C) Amplitude and phase
sin (217fl) + sin 3(27rJ1) relationships of first, third, fifth, and seventh harmonics
which produce a square wave when added. (d I Addition
of first and third harmonics. (e) Amplitude versus
+ sin 5(2rJtl + Sifl 7(2lTJt) + frequency graph (frequency spectrum) for square wave.

ANALOG INT[RFACING AND INDUSTRIAL CONTROL 3l


The terms In the right-hand side of this equation are lower harmonics, and mathematically it can be shown
referred to as a Fourier series. As it turns out, any that the result is the waveform in Figure lO-41b.
periodic waveform can be described with a Fourier You can pull the time domain view of this circuit and
series, but for now, we will Just stay with a square wave, the frequency-domain view into the same equation as
When we want to graphically represent the frequency follows:
components in a signal. it is very messy to draw wave-
forms such as those In Figure lO-40c. Therefore, we 15 2.2RC soRC
usually use an amplitude-versus-frequency graph, such
as that in Figure l0-40e. From this graph you can easily
see that the frequency components of our square wave fc:; sofc=-;
are a fundamental frequency with a relative amplitude -- 0.35
of 1, a third harmonic with a relative amplitude of , a
fifth harmonic with a relative amplitude of L a seventh
harmonic with a relative amplitude of , etc. Later we The point of the preceding discussions was to show
will use this graph to help describe the effect of a low- you the two equivalent ways of describing the operation
pass filter on a square-wave signal. of a filter circuit. When we are designing analog filters,
such as those made with simple resistors and capacitors.
we usually think and work in the frequency domain.
Time-Domain View and Frequency-Domain When we are designing digital filters, we usually think
View of a low-Pass Filter and work in the time domain. Now let's see how you
Ifa square wave is passed through the simple RC circuit can use an AID, microcomputer, and 0/A converter to
shown in Figure 10-4 Ia, the output waveform will look function as a digital filter which modifies the waveform]
like that in Figure 10-41 b. The time-domain explanation frequency composition of a signal.
for this output waveform is that it takes time for the
capacitor to charge through the resistor, so the risetime Digital Filters
and failtime of the output signal will be increased. As
you may remember, the 10% to 90% risetime for the The basic principle of a digital filter is to take continuous
output signal is t = 2.2RC. samples of the input waveform with the A/I) converter.
Now, if you think of the square wave as a combination process the samples with the microcomputer, and out-
of harmonically related sine waves, as shown in Figure put the processed results to the 0/A converter. The
lO-40e. you can easily describe the operation of the processing done by the microcomputer de:"rmines the
circuit in the frequency domain. In the frequency do- filter response.
main, this circuit acts as a low-pass filter. This means If the samples are simply read in from 'he A/D converter
that it passes the fundamental frequency but reduces and output directly to he 0/A nverter, then the output
the amplitude of the harmonics. As we showed you in signal will be almost identical to the input signal. If the
Figure 10-40d, adding harmonics to the fundamental samples arc read in from tI'. A/fl converter and held in
frequency Is what produces the square wave. so reducing memory for some time before being output to the D/A
the amplitude of the harmonics will change the output Cr iverter, then the output signal will simply be a delayed
waveform. For the simple RC circuit in Figure 10-4 Ia. version of the input sinat.
the critical frequency, or in other words the frequency Now, to make it more ir sting. suppose that we
at which a sine-wave input signal will be attenuated to read in. for example, 100 samples from the A/I) converter
0.707 of its input value, is J'c l/(2r RC). Above the and use some mathematical algorithm to compute an
critical frequency the output decreases by a factor of 10 output value based on these samples. When we take in
for each increase of 10 in frequency. This means that the next sample from the A/D converter, we throw out

I
the upper harmonies will be attenuated more than the the oldest sample and use the latest 100 samples to
compute the next output value. The output value at any

T'.
time then will be a sort of "average" of the last 100
R
samples. To help visualize this, you might think of the
process as sliding a window of 100 samples along the
waveform and using some algorithm to compute an
C VOr "average" of the samples.
If the window is positioned so that all 100 samples
come from a section of the square wave where the
(a) waveform is at —V. as shown in Figure 10'42a. then
the computed output value will be —V. As the window
slides to the right so that it includes some samples
from the high section, as shown in Figure lO-42b, the
"average" will increase, so the computed output value
U' will increase. The risetime of the output or the rate at
which the output value increases is determined by the
FIGURE 10-41 Ia) Simple RC circuit. (b) Output weight given to new samples versus the weight given to
waveform trom RC circuit. old samples in computing the 'average." Using a low-

338 CHAPTER TEN


If$ , f(ffl l I sents a delay of one sample interval time. Circles con-
taining an X represent a multiplication operation, and
the letters to the left of each circle represent the numbers
or coefficients that the term will be multiplied by. Y0
t sampi., ill —V. ao co.nputed
Output value * - v represents the value of the current sample from the
A/D. Y 1 represents the vlue of the previous sample from
(a)
the AID. andY2 represents the value of the sample before
that. Here's how this works. The output value V at any
time is produced by summing the (current sample X
ii some coefficient) + (the previous sample x some coef-
ficient) + (the sample before that x some coefficient).
Sons. samples = —V. etc. To do all this with a microprocessor requires the
Some samples tV
So computed output value between -v and *V, depending simple operations of saving previous samples, multi-
on weighting used in computation. plying, and adding.
b) Figure l0-43b shows a functional diagram for an
hR digital filter. Here again the blocks containing Z'
represent a delay of one sample time. The value of the
current sample from the A/D converter is represented by
the X at the left of the diagram. The Y0 point represents
Output waveform produced by 0/A, Output value increases
the output from the microprocessor to the D/A converter.
as "average' increase. Note that for an HR filter, it is this output value which
is saved to be used in computing feedback terms for
Id future samples, In the FIR type, remember, the samples
FIGURE 10-42 Effective sample position on computed from the A/I) converter were saved directly for future
output value, use. The output for an hR type Is produced by summing
(the current sample x a calculated coefficient) + (the
previous output value x a calculated coefficient) +(the
output value before that x a calculated coefficient). etc.
pass ifiter weighting, the output waveform will took like FIR filters are easier to design, but they may require
that in Figure lO-42c. The algorithm usedto compute many terms to produce a given filter response. HR filters
the output values determines the characteristics of the require fewer stages, but they have to be carefully
output waveform. - designed so that they do not become oscillators. After
The two basic algorithms commonly used for comput- we take a look at the special hardware commonly used to
ing the output values are the finite tmpuls,e response or implement digital filters, we will describe how computer-
FIR type and the infinite impulse response or hR type. based tools are used to calculate the coefficients [or FIR
Figure I0-43u shows a functiona] diagram of the opera- and hR filters.
tion of an FIR-type filter. The box containing Z - ' repre-
Digital Filter Hardware
As we said before, the basic parts of a digital filter are
an A/D converter, a microcomputer, and a D/A converter.
For very low-speed applications the microprocesaor used
A 0_..(X) A, —.(X) A in the microcomputer can be a general-purpos= devke.
such as the 8086 we have used for other ap-piicatons
Y0 I'Y, I; throughout the book. For many real-time applicatuns
ri - I r—i -- such as digital speech processing, however, a genetal-
L_J purpose microprocessor is not nearly fast enough. The'-e
are several reasons for this.
The architecture ol general-purpose machines Is
mostly memory-based, so most operands must be
[etched from memory. The memory access time then
adds to the processing time.
The Von Neuman architecture of general-purpose
microprocessors uses the same bus for instructions
and data. This means that data cannot be fetched
until the code fetch is completed.
The multiply and add operations needed in most
Id digital filter applications each require several clock
cycles to execute in a general-purpose machine be-
FIGURE 10-43 Digital filter aIorithms. (a) FIR. fbI IIR. cause the Internal hardware is not optimized [or
—45
ANALOG INTERFACING AND INDUSTRIAL CONTROL 339
these operations. Since many computations are 4. A 32-bit barrel shifter which can shift an operand
needed to produce each output value, the time any number of bits in one clock cycle.
required for these instructions severely limits the
5. A 16-bit or a 32-bit CPU which maintains precision
sampling rate and the maximum frequency the filter during the chain calculations needed in most digital
can handle. filter applications.
To solve these and other problems, several companies
have designed microprocessors which have the specific 6. An instruction set optimized for DSP applications.
features needed for digital signal processing applica- For example, the single TMS32OC3O instruction
MPYI3 <srcA>, <srcB>, <dstl> IIADDI3 <srcC>,
tions. The leading examples of these types of processors
<srcD>, <dst2> will multiply two specified op-
are the TMS32OCXX family devices from Texas Instru-
ments. Currenfly the five generations in this family are erands (srcA x srcB) and add two different operands
the TMS32OC1X. the TMS32OC2X. the TMS32OC3X. (srcC + srcD}. Perhaps you can see how an instruc-
the TMS32OC4X, and the TMS32005X devices. These tion such as this would be useful in Implementing
devices have a wide variety of features, but here are the computations for an FIR filter such as we de-
serthed before. The TMS32OC3O also has a "zero-
some of the common features.
overhead' loop instruction which can be used to
1. Sizable amounts of on-chip registers. ROM. and quickly repeat an operation some number of times.
RAM. so data and instructions can be accessed very
quickly. 7. Some devices in the family also have built-in floating-
point processors which can directly perform opera-
2. Separate buses for code words and for data words. tions on numbers in floating-point format. (In the
This approach is commonly referred to as Haward next chapter we show you how the 8087 floating-
architecture. As you can see in Figure 10-44, the point processor works.)
TMS32OCXX devices' Implementation of Harvard
architecture has an address bus and a data bus for Figure 10-45 shows a block diagram of a complete
program words, an address bus and a data bus for digital filter system using one of the TMS320C25 family
data words, and even an address bus and a data bus parts. Note that a simple analog low-pass filter Is put In
for direct memory access (DMA) by an external series with the input. Remember the sampling theorem,
device. These parallel buses allow instructions and which states that the highest-frequency signal which
data to be fetched at the same time. can he digitized and reconstructed Is one which contains
3. An optimized multiplier which, depending on the two samples per cycle. if higher frequencies are digitized.
speciflcdevice.canperforma 16 x 16-ora32 x 32- alias frequencies will be generated when the signal Is
bit multiply in one clock cycle. For the TMS32005O reconstructed with a 0/A converter. This low-pass filter
device, a clock cycle can be as short as 35 ns. on the input helps prevent aliasing.

1 RAM II RAM 1 ROM


CACHE j BLOCK 0 I BLOCK 1 I I BLOCK
(64X32I (1 KX32) Ii KX32( 14KX32)

1 24t 24-1. 32.1. 24-1. 32-1. 24-I. 32-1.

RDY
MST RB
M M lOST RB
STAB -'K 1 U U P X R,W
x x E
XO(31-0(
0(31-0) 7p XA112-O)
Al 23-01
H
E
R
32.j. ..24j24 32j. J24 A
32-j_ -f.24 L
PROGRAM COUNTER/ DMA a
INSTRUCTION REGISTER CPU CONTROLLER U

FIGURE 10-44 The TMS32OCXX device's implementation ol Harvard


archilecture. (Texas Instruments Inc.)

340 CHAPTER TEN


x,lt) Low pea External
-- f,Iter memory

I_______________
DSP microcompoter I Digilil-to- _______ Low-pux YeW

hold chip convener ITMS32O-C25i


j- walog filter

-_] Clock I

FIGURE 10-45 Block diagram of a TMS32OI25 DSP-based filter.

After the anti-alias filter a sample-and-hold is used to Several DOS-compatible software packages are avail-
keep the value on the input of the A/D constant during able to help perform these tasks. Examples are the
conversion. A simple low-pass analog filter Is connected Digital Filter Design Package-2 (DFDP2) from Atlanta
to the output of the 0/A converter to "sniooth' the output Signal Processors Inc. and the Filter Design and Analysis
signal. System (FDAS2) from Momentum Data Systems. When
For development purposes and experimentation with given the desired filter type, break frequencies, and
a PC-type microcomputer, the DSP-16 board from Arid attenuation rates, these packages tell you if the desired
Corp. has two 16-bit, 50-kHz A/D converters, a 40-MHz filter can be implemented and generate the required
TMS320C25, and two 16-bit 50-kllz 0/A converters. The coefficients. After the coefficients are generated, another
dual channels allow two signals to be processed at the module in these software packages can be used to
same time. Other boards allow different combinations produce the assembly language progam for the DSP
of sampling rate and number of channels. microprocessor. To give you an example of how simple
the actual program is. Figure 10-46 shows a procedure
Digital Filter Software and Development Tools which implements a bandpass filter on the TMS320C25
in Figure 10-45. The RPTK 68 Instruction in this
As perhaps you can guess from the algorithms in Figure procedure causes the following instruction to be re-
10-43. developing the program for a digital filter involves peated 68 times. The MACD FDATA+ >FDOO. - that Is
two main tasks. The first task is to determine the repeated 68 times will multiply a data memory value
coefficients by which the terms in the equation will be by a program memory value, add the result to an
multiplied to implement the desired filter. The second accumulator, and decrement the pointer to point to the
task is to write a program which reads in values from next operands. These two Instructions then do most of
the A/fl converter, computes an output value, and sends the work of computing an output value.
the completed value to the D/A converter at the right Once the coefficients and program for a digital flltr
time. have been produced. the next step is to test the result.

DELAR EQU 1 *DELAY AR REGISTER


*
FILTER
LARP DELAR *POINT TO THE DELAY INDEX REGISTER
LRLK DELAR,Z000 * INDEX POINTS TO Z-0 (INPUT)
LAC VSAMPL,15 *GET I SCALE INPUT
SACH * *SAVE SCALED INPUT

MPYK 0 aP 0
ZAC *AC = 0
LRLK DELAR,ZLAST *INDEX POINTS TO Z-N
RPTK 68
MACI FDATA+>F000, * - *MULTXPLY,ACCUM.artd DELAY
APAC *FORM RESULT
SACH VSAMPL,O *SAVE OUTPUT
RET * RETURN
*
PENO
END

FIGURE 10-46 TMS320C25 digital filter program. (R.W. Schafer. "The Math
Behind the MIPS: DSP Basics." Electronic Design, September 1988)

ANALOG INTERFACING AND INDUSTRIAL CONTROL 341


One way to do this is with a PC-compatible board such Low-pass filter, high-pass filter, bandpass filter
as the Arlel unit described before. Another method is Critical frequency or breakpoint
to use an emulator such as the Texas instruments Second-order low-pass filter, second order high-pass
XDS 1000. ThIs emulator consists of a PC board which filter
plugs into an IBM PC-compatible computer and a buffer
pod which plugs into the prototype hardware. As with Photodlode. solar cell
other emulators we have discussed, it allows you to load Temperature-sensitive voltage sources
programs, set breakpoints, do traces. etc. A software
package and an emulator allow you to quickly design. Temperature-sensitive current sources
test, and debug a digital filter system.
Thermocouples, cold-junction compensation
Force and pressure transducers
Switched Capacitor Digital Filters Strain gage, LVDT. load cell
For simple filter designs, another type of digital filter Flow sensors—paddle wheel, differential pressure trans-
called a switched capacitor filter implements digital ducer
filtering without the need for the A/D and DIA converters.
An example of this type of device is the National MFIO. D/A converters
In this type of filter an input signal is sampled on a Resolution
capacitor. The signal is passed on to other capacitors. Full-scale output voltage
and fractions of the outputs from these capacitors are Maximum error
summed to produce an analog output signal directly. Linearity
Switched capacitor filters are less expensive, but they Settling time
do not give the degree of programmability that the
microprocessor-based filters do. A/D converters
Conversion time
Sample and hold
Sampling theorem
Quantizing error
CHECKLIST OF IMPORTANT TERMS AND
A/D conversion methods
CONCEPTS IN THIS CHAPTER Parallel-comparator AID converter
If you do not remember any of the terms in the following Dual-slope A/D converter
list. use the index to help you find them in the chapter Successive-approximation AID converter
hr review, Data acquisition system
Direct memory access. DMA
Op amp Set point
Comparator Servo control
aysteresis Settling time. underdamped and overdamped responses
Noninverting amplifier Residual error
Inverting amplifier Pr oportlonaiintegrajderivative control loop. P11)
Virtual ground Time-slice system
Gain-bandwidth product On/off control
Unity-gain bandwidth Robotics
Adder circuit—summing point Embedded controllers
Differential amplifier 80186. 80188
Common-mode signal. common-mode rejection Digital signal processing
Instrumentation amplifier Time-domain and frequency-domain view of a square
Op-amp integrator Circuit wave
Linear ramp Digital filter operation
Saturation Finite impulse response (FIR) filter algorithm
Op-amp differentiator Infinite impulse response (lIR) filter algorithm
Op-amp active filters Switched capacitor filter

342 CHAPTER TEN


REVIEW QUESTIONS AND PROBLEMS
1. a. A comparator circuit such as the one in Figure actual maximum output voltage of this converter?
10-Ibis powered by ± 15 V. the inverting input What accuracy should this Converter have to be
is tied to + 5 V. and the noninverting input is consistent with its resolution?
at -15.3 V. About what voltage will be on the
9. Why must a 12-bit D/A converter have latches on
output of the comparator?
Its inputs if it is to be connected to 8-bit ports or
b. An amplifier circuit, such as the one in Figure
10-id, has Hi = 10 kfl and R2 = 190 kfl. an 8-bit data bus?
Calculate the closed-loop voltage gain for the 10. Describe the operation of a flash-type A/D Converter.
circuit and the V, that will be produced by a What are its main advantages and disadvantages?
V of 0.030 V. What voltage would you measure
on the inverting Input? What would be the gain 11. For the dual-slope A/D converter in Figure 10-19.
of the circuit if R2 = 0 11? what will be the displayed Count for an input voltage
c. An amplifier circuit, such as the one in Figure of 2372 V? What is the resolution of a 4-digtt
lO-le. is built with an Hi of 15 kIl and an H1 slope-type A/D converter expressed in bits?
of 75 ML Calculate the closed-loop voltage gain 12. How many clock cycles does a 12-bit successive-
br the circuit and the output voltage for an approximation A/D converter take to do a conver-
input voltage of 0.73 V. What voltage will you sion on a 0.1-V input signal? On a 5-V input signal?
always measure on the Inverting input of this How does this compare with the number of clock
circuit? cycles required for a 12-bit dual-slope type?
d. A differential amplifier, such as the one in
Figure 10-19, is built with Ri = R2 = 100 ku 13. a. Assume the inputs of the MC 1408 D/A converter
andR1 = R = I Mu1.V 4.9V,andV2 = 5.1 in Figure 10-20 are connected to an output port
V. Cakulate the output voltage and polarity. on your microcomputer board and the output
e. Describe the main advantage of the instrumen- of the comparator is connected to bit DO of an
tation amplifier in Figure 10-lh over the simple input port. Write the algorithm for a procedure
differential amplifier in Figure 10-19. to do an AID conversion by outputting an
f. If the amplifier used in the circuit in part b has incrementing Count to the output port.
a gain-bandwidL product of 1 MHz, what will b. Write an algorithm for a procedure to do the
be the closed-loop bandwidth of the circuit? conversion by the successive-approxlmation
method. Which method will produce a faster
2. Draw a circuit showing how a light-dependent result? If the hardware is available, write the
resistor can be connected to a comparator so the programs for these algorithms and compare the
output of the comparator changes state when the times by watching the comparator output with
resistance of the LDR is 10 kfl. an oscilloscope.
3. For the photodiode amplifier circuit in Figure 10-5. 14. Show the detailed algorithm for the procedure you
what voltage will you measure on the inverting would use to read in the data from a multiplexed
Input of the amplifier? Why is it important to use BCD output A/D converter such as the MC 14433
an FET input amplifier for this circuit? Which in Figure 10-23 and assemble the value in a 16-bit
direction are electrons flowing through the photo. register for display.
diode?
15. The data sheet for an AID converter Indicates that
4. In what application might you use a temperature- its output is In offset-binary code. If the converter
dependent current device such as the AD590 rather is set up for a range of —5 to + 5 V and the output
than a temperature-dependent voltage device such code is 01011011, what input voltage does this
as the LM35? represent? How could you convert this code to 2's
S. Why must thermocouples be cold-junction compen- complement form after you read the code into your
sated in order to make accurate measurements? microcomputer?
How can the nonlinearity of a thermocouple be 16. Write a procedure to round a 32-bit BCD number
compensated for? in DXAX to a 16-bit BCD number in DX.
6. Why are strain gages usually connected in a bridge
17. For the scale circuitry in Figure 10-23. what voltage
configuration? Why do you use a dli erentiai ampli-
fier to amplify the signal from a strain gage bridge? should you measure on the Inverting input of
the LM308 amplifier? What voltages should you
7. Calculate the full-scale output voltage for the simple measure on the two inputs of the LM363 amplifier
DiA converter in Figure 10-14. with no load on the scale? What voltage should you
8. measure on the output of the LM363 with no load
What is the resolution of a 13-bit DIA converter? If
on the scale?
the converter has a full-scale output of 10.000 V.
what is the size of each step? What will be the 18. The section of the scale program following the label

ANALOG INTLRIACtNG AND INDUSTRIAl. CONTROL 343


NXTKEY in Figure 10-35 moves stme bytes around 23. a. Describe how a square wave can be generated
in mernuzy. Rewrite this section of the program by the time-domain method.
using an 8086 strIng instruction to do the move b. Describe how a square wave can be generated
operations. Which version seems more efficient In by the frequency-domain method.
this case?
24. a. Describe the basic operation of a dlgitaJ
19. Describe how feedback helps hold the value of some filter.
variable, such as a motor speed, constant. Refer to b. Describe the major difference in how an output
Figure 10-27 in your explanation. value is computed in an FIR digital filter and
20. how it is computed in an HR filter.
What problem In a control loop does integral feed-
back help solve? Why is derivative feedback some- 25. a. Why is a general-purpose microprocessor such
times added to a control loop? as the 8086 not suitable for most digital filter
21. What is the major advantage of a microcomputer. applications?
b. Describe three features designed into a digital
controlled loop over the analog approach shown in
Figure 10-29? signal processing microprocessor such as a
TMS32OCXX device to speed up processing.
22. Suppose that you want to control the speed of a
26. a. What Is the minimum frequency that a sine-
small dc motor, such as the one in Figure 10-27,
wave signal must be sampled with an AID
with LOOP 1 of our microcomputer-based process
controller. converter so that It can be reconstructed with
a. Show how you would Connect the output from a D/A converter?
b. Why is an analog low-pass filter often put before
the motor's tachometer to the system in Figure
the A/D In a digital filter?
10-33. Also show how you would connect, an
8-bit D/A to control the current to the motor. c. What is the purpose of the sample-and-
b. Write a flowchart for the LOOP! procedure to hold circuit on the input of the AID in Figure
10-45?
control the speed of the motor.
c. Describe how a lookup table could be used to 27. List the two tasks involved In writing the program
determine the feedback value. for a digital filter.

344 CHAPTER TEN

You might also like